text,length,is_long_context,metric_val,label_metric "#include ""caching_metric.h"" #include ""metric.h"" #include ""description_utils.h"" #include ""classification_utils.h"" #include ""kappa.h"" #include #include #include #include #include #include #include using NCB::AppendTemporaryMetricsVector; using NCB::AsVector; constexpr int BinaryClassesCount = 2; static const TString ConfusionMatrixCacheKey = ""Confusion Matrix""; static const TString MultiLabelConfusionMatrixCacheKey = ""MultiLabel Confusion Matrix""; /* Caching metric */ namespace { class ICacheHolder { public: virtual ~ICacheHolder() = default; }; template class TCacheHolder : public ICacheHolder { public: template TValue& Get(TValueMaker maker, const TKeys & ...keys) { auto key = std::make_tuple(keys...); if (!Cache.contains(key)) { Cache.insert({key, maker()}); } return Cache.at(key); } private: TMap, TValue> Cache; }; class TCache { public: template auto Get(const TString& cacheKey, TValueMaker maker, TKeys... keys) -> const decltype(maker()) & { if (!Cache.contains(cacheKey)) { Cache.insert({cacheKey, MakeHolder>()}); } auto cache = dynamic_cast *>(Cache.at(cacheKey).Get()); CB_ENSURE(cache, ""Cache is typed differently""); return cache->Get(maker, keys...); } private: TMap> Cache; }; struct ICachingSingleTargetEval { virtual TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef queriesInfo, int begin, int end, TMaybe cache ) const = 0; }; struct ICachingMultiTargetEval { virtual TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const = 0; }; template static TMetricHolder ParallelEvalIfPossible( const IMetric& metric, TEvalFunc&& evalFunc, int begin, int end, NPar::ILocalExecutor& executor ) { if (metric.IsAdditiveMetric()) { return ParallelEvalMetric(evalFunc, GetMinBlockSize(end - begin), begin, end, executor); } else { return evalFunc(begin, end); } } struct TCachingSingleTargetMetric: public TSingleTargetMetric, ICachingSingleTargetEval { explicit TCachingSingleTargetMetric(ELossFunction lossFunction, const TLossParams& params) : TSingleTargetMetric(lossFunction, params) {} using ICachingSingleTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef queriesInfo, int begin, int end, NPar::ILocalExecutor& executor ) const override { const auto evalMetric = [&](int from, int to) { return Eval(approx, approxDelta, isExpApprox, target, weight, queriesInfo, from, to, Nothing()); }; return ParallelEvalIfPossible(*this, evalMetric, begin, end, executor); } }; struct TCachingMultiTargetMetric: public TMultiTargetMetric, ICachingMultiTargetEval { explicit TCachingMultiTargetMetric(ELossFunction lossFunction, const TLossParams& params) : TMultiTargetMetric(lossFunction, params) {} using ICachingMultiTargetEval::Eval; virtual TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, NPar::ILocalExecutor& executor ) const override { const auto evalMetric = [&](int from, int to) { return Eval(approx, approxDelta, target, weight, from, to, Nothing()); }; return ParallelEvalIfPossible(*this, evalMetric, begin, end, executor); } }; struct TCachingUniversalMetric: public TUniversalMetric, ICachingSingleTargetEval, ICachingMultiTargetEval { explicit TCachingUniversalMetric(ELossFunction lossFunction, const TLossParams& params) : TUniversalMetric(lossFunction, params) {} using ISingleTargetEval::Eval; using ICachingSingleTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef queriesInfo, int begin, int end, NPar::ILocalExecutor& executor ) const override { const auto evalMetric = [&](int from, int to) { return Eval(approx, approxDelta, isExpApprox, target, weight, queriesInfo, from, to, Nothing()); }; return ParallelEvalIfPossible(*this, evalMetric, begin, end, executor); } using IMultiTargetEval::Eval; using ICachingMultiTargetEval::Eval; virtual TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, NPar::ILocalExecutor& executor ) const override { const auto evalMetric = [&](int from, int to) { return Eval(approx, approxDelta, target, weight, from, to, Nothing()); }; return ParallelEvalIfPossible(*this, evalMetric, begin, end, executor); } }; } /* Confusion matrix */ static TMetricHolder BuildConfusionMatrix( const TConstArrayRef> approx, TConstArrayRef target, TConstArrayRef weight, int begin, int end, double targetBorder, double predictionBorder ) { const bool isMultiClass = approx.size() > 1; const int classesCount = isMultiClass ? approx.size() : BinaryClassesCount; const double predictionLogitBorder = NCB::Logit(predictionBorder); const auto buildImpl = [&](auto useWeights, auto isMultiClass) { TMetricHolder confusionMatrix(classesCount * classesCount); for (int idx = begin; idx < end; ++idx) { int approxClass = GetApproxClass(approx, idx, predictionLogitBorder); int targetClass = isMultiClass ? static_cast(target[idx]) : target[idx] > targetBorder; float w = useWeights ? weight[idx] : 1; Y_ASSERT(targetClass >= 0 && targetClass < classesCount); confusionMatrix.Stats[approxClass * classesCount + targetClass] += w; } return confusionMatrix; }; return DispatchGenericLambda(buildImpl, !weight.empty(), isMultiClass); } /* MultiLabel Confusion matrix */ constexpr size_t BinaryConfusionMatrixSize = 4; static TMetricHolder BuildConfusionMatrix( const TConstArrayRef> approx, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, double targetBorder, double predictionBorder ) { const int classesCount = approx.size(); TMetricHolder confusionMatrix(BinaryConfusionMatrixSize * classesCount); for (int classIdx = 0; classIdx < classesCount; ++classIdx) { TConstArrayRef> classApprox(&approx[classIdx], 1); TMetricHolder classConfusionMatrix = BuildConfusionMatrix( classApprox, target[classIdx], weight, begin, end, targetBorder, predictionBorder ); for (size_t i = 0; i < BinaryConfusionMatrixSize; ++i) { confusionMatrix.Stats[classIdx * BinaryConfusionMatrixSize + i] = classConfusionMatrix.Stats[i]; } } return confusionMatrix; } /* MCC caching metric */ namespace { struct TMCCCachingMetric final : public TCachingSingleTargetMetric { explicit TMCCCachingMetric(const TLossParams& params, int classesCount) : TCachingSingleTargetMetric(ELossFunction::MCC, params) , ClassesCount(classesCount) { } explicit TMCCCachingMetric(const TLossParams& params, double predictionBorder) : TCachingSingleTargetMetric(ELossFunction::MCC, params) , PredictionBorder(predictionBorder) { } using TSingleTargetMetric::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef queriesInfo, int begin, int end, TMaybe cache ) const override; double GetFinalError(const TMetricHolder &error) const override; void GetBestValue(EMetricBestValue *valueType, float *bestPossibleValue) const override; bool IsAdditiveMetric() const override { return true; } static TVector ValidParamSets(); private: static constexpr double TargetBorder = GetDefaultTargetBorder(); const int ClassesCount = BinaryClassesCount; const double PredictionBorder = GetDefaultPredictionBorder(); }; } THolder MakeMCCMetric(const TLossParams& params, int classesCount) { return MakeHolder(params, classesCount); } TMetricHolder TMCCCachingMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(!isExpApprox); Y_ASSERT(approxDelta.empty()); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); return confusionMatrix; } double TMCCCachingMetric::GetFinalError(const TMetricHolder &error) const { TVector rowSum(ClassesCount); TVector columnSum(ClassesCount); double totalSum = 0; const auto getStats = [&](int i, int j) { return error.Stats[i * ClassesCount + j]; }; for (auto i : xrange(ClassesCount)) { for (auto j : xrange(ClassesCount)) { rowSum[i] += getStats(i, j); columnSum[j] += getStats(i, j); totalSum += getStats(i, j); } } double numerator = 0; for (auto i : xrange(ClassesCount)) { numerator += getStats(i, i) * totalSum - rowSum[i] * columnSum[i]; } double sumSquareRowSums = 0; double sumSquareColumnSums = 0; for (auto i : xrange(ClassesCount)) { sumSquareRowSums += Sqr(rowSum[i]); sumSquareColumnSums += Sqr(columnSum[i]); } double denominator = sqrt((Sqr(totalSum) - sumSquareRowSums) * (Sqr(totalSum) - sumSquareColumnSums)); return denominator != 0 ? numerator / denominator : 0.0; } void TMCCCachingMetric::GetBestValue(EMetricBestValue *valueType, float *) const { *valueType = EMetricBestValue::Max; } TVector TMCCCachingMetric::ValidParamSets() { return {TParamSet{{TParamInfo{""use_weights"", false, true}}, """"}}; }; /* Zero one loss caching metric */ namespace { struct TZeroOneLossCachingMetric final: public TCachingSingleTargetMetric { explicit TZeroOneLossCachingMetric(const TLossParams& params, int classesCount) : TCachingSingleTargetMetric(ELossFunction::ZeroOneLoss, params) , ClassesCount(classesCount) { } explicit TZeroOneLossCachingMetric(const TLossParams& params, double predictionBorder) : TCachingSingleTargetMetric(ELossFunction::ZeroOneLoss, params) , PredictionBorder(predictionBorder) { } using TSingleTargetMetric::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef queriesInfo, int begin, int end, TMaybe cache ) const override; double GetFinalError(const TMetricHolder &error) const override; void GetBestValue(EMetricBestValue *valueType, float *bestPossibleValue) const override; bool IsAdditiveMetric() const override { return true; } static TVector ValidParamSets(); private: static constexpr double TargetBorder = GetDefaultTargetBorder(); const int ClassesCount = BinaryClassesCount; const double PredictionBorder = GetDefaultPredictionBorder(); }; } TMetricHolder TZeroOneLossCachingMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(!isExpApprox); Y_ASSERT(approxDelta.empty()); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; }; TMetricHolder error(2); for (auto i : xrange(ClassesCount)) { error.Stats[0] += getStats(i, i); for (auto j : xrange(ClassesCount)) { error.Stats[1] += getStats(i, j); } } return error; } double TZeroOneLossCachingMetric::GetFinalError(const TMetricHolder &error) const { return 1 - error.Stats[0] / error.Stats[1]; } void TZeroOneLossCachingMetric::GetBestValue(EMetricBestValue *valueType, float *) const { *valueType = EMetricBestValue::Min; } TVector TZeroOneLossCachingMetric::ValidParamSets() { return {TParamSet{{TParamInfo{""use_weights"", false, true}}, """"}}; }; /* Accuracy caching metric */ namespace { struct TAccuracyCachingMetric final: public TCachingUniversalMetric { explicit TAccuracyCachingMetric(const TLossParams& params, double predictionBorder) : TCachingUniversalMetric(ELossFunction::Accuracy, params) , PredictionBorder(predictionBorder) { } explicit TAccuracyCachingMetric(const TLossParams& params, int classesCount) : TCachingUniversalMetric(ELossFunction::Accuracy, params) , ClassesCount(classesCount) { } explicit TAccuracyCachingMetric(const TLossParams& params, int classesCount, int classIdx) : TCachingUniversalMetric(ELossFunction::Accuracy, params) , ClassesCount(classesCount) , AccuracyType(EAccuracyType::PerClass) , ClassIdx(classIdx) { } using ISingleTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const override; using IMultiTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const override; void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override; TString GetDescription() const override; bool IsAdditiveMetric() const override { return true; } static TVector ValidParamSets(); private: static constexpr double TargetBorder = GetDefaultTargetBorder(); const double PredictionBorder = GetDefaultPredictionBorder(); const int ClassesCount = BinaryClassesCount; const EAccuracyType AccuracyType = EAccuracyType::Classic; const int ClassIdx = 0; }; } TMetricHolder TAccuracyCachingMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(!isExpApprox); Y_ASSERT(approxDelta.empty()); CB_ENSURE(AccuracyType == EAccuracyType::Classic, ""PerClass accuracy is meaningfull for multilabel only""); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; }; TMetricHolder error(2); for (auto i : xrange(ClassesCount)) { error.Stats[0] += getStats(i, i); for (auto j : xrange(ClassesCount)) { error.Stats[1] += getStats(i, j); } } return error; } TMetricHolder TAccuracyCachingMetric::Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const { Y_ASSERT(approxDelta.empty()); TMetricHolder error(2); if (AccuracyType == EAccuracyType::PerClass) { const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(MultiLabelConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[ClassIdx * BinaryConfusionMatrixSize + i * 2 + j]; }; for (auto i : xrange(2)) { error.Stats[0] += getStats(i, i); for (auto j : xrange(2)) { error.Stats[1] += getStats(i, j); } } } else { const double predictionLogitBorder = NCB::Logit(PredictionBorder); const bool useWeights = !weight.empty(); for (int idx = begin; idx < end; ++idx) { bool correct = true; for (int targetDim = 0; targetDim < target.ysize() && correct; ++targetDim) { const int approxClass = approx[targetDim][idx] > predictionLogitBorder; const int targetClass = target[targetDim][idx] > TargetBorder; correct &= approxClass == targetClass; } const double w = useWeights ? weight[idx] : 1.0f; error.Stats[0] += w * correct; error.Stats[1] += w; } } return error; } void TAccuracyCachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const { *valueType = EMetricBestValue::Max; } TString TAccuracyCachingMetric::GetDescription() const { if (AccuracyType == EAccuracyType::PerClass) { const TMetricParam classIdx(""class"", ClassIdx, /*userDefined*/true); return BuildDescription(ELossFunction::Accuracy, UseWeights, classIdx); } else { return TCachingUniversalMetric::GetDescription(); } } TVector TAccuracyCachingMetric::ValidParamSets() { return {TParamSet{ { TParamInfo{""use_weights"", false, true}, TParamInfo{""type"", false, ToString(EAccuracyType::Classic)} }, """" }}; }; /* HammingLoss caching metric */ namespace { struct THammingLossCachingMetric final: public TCachingUniversalMetric { explicit THammingLossCachingMetric(const TLossParams& params, double predictionBorder) : TCachingUniversalMetric(ELossFunction::HammingLoss, params) , PredictionBorder(predictionBorder) { } explicit THammingLossCachingMetric(const TLossParams& params, int classesCount) : TCachingUniversalMetric(ELossFunction::HammingLoss, params) , ClassesCount(classesCount) { } using ISingleTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const override; using IMultiTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const override; void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override; bool IsAdditiveMetric() const override { return true; } static TVector ValidParamSets(); private: static constexpr double TargetBorder = GetDefaultTargetBorder(); const double PredictionBorder = GetDefaultPredictionBorder(); const int ClassesCount = BinaryClassesCount; }; } TMetricHolder THammingLossCachingMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(!isExpApprox); Y_ASSERT(approxDelta.empty()); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; }; TMetricHolder error(2); for (auto i : xrange(ClassesCount)) { error.Stats[0] += getStats(i, i); for (auto j : xrange(ClassesCount)) { error.Stats[1] += getStats(i, j); } } error.Stats[0] = error.Stats[1] - error.Stats[0]; return error; } TMetricHolder THammingLossCachingMetric::Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const { Y_ASSERT(approxDelta.empty()); TMetricHolder error(2); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(MultiLabelConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); for (auto classIdx : xrange(ClassesCount)) { const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[classIdx * BinaryConfusionMatrixSize + i * 2 + j]; }; for (auto i : xrange(2)) { error.Stats[0] += getStats(i, 1 - i); for (auto j : xrange(2)) { error.Stats[1] += getStats(i, j); } } } return error; } void THammingLossCachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const { *valueType = EMetricBestValue::Min; } TVector THammingLossCachingMetric::ValidParamSets() { return { TParamSet{ { TParamInfo{""use_weights"", false, true}, TParamInfo{""border"", false, TargetBorder} }, """" } }; }; /* Recall caching metric */ namespace { struct TRecallCachingMetric final: public TCachingUniversalMetric { explicit TRecallCachingMetric(const TLossParams& params, double predictionBorder) : TCachingUniversalMetric(ELossFunction::Recall, params) , ClassesCount(BinaryClassesCount) , PredictionBorder(predictionBorder) , IsMultiClass(false) { } explicit TRecallCachingMetric(const TLossParams& params, int classesCount, int positiveClass) : TCachingUniversalMetric(ELossFunction::Recall, params) , ClassesCount(classesCount) , PositiveClass(positiveClass) , IsMultiClass(true) { } using ISingleTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const override; using IMultiTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const override; TString GetDescription() const override; double GetFinalError(const TMetricHolder& error) const override; void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override; bool IsAdditiveMetric() const override { return true; } static TVector ValidParamSets(); private: static constexpr double TargetBorder = GetDefaultTargetBorder(); const int ClassesCount = BinaryClassesCount; const int PositiveClass = 1; const double PredictionBorder = GetDefaultPredictionBorder(); const bool IsMultiClass = false; }; } THolder MakeBinClassRecallMetric(const TLossParams& params, double predictionBorder) { return MakeHolder(params, predictionBorder); } THolder MakeMultiClassRecallMetric(const TLossParams& params, int classesCount, int positiveClass) { return MakeHolder(params, classesCount, positiveClass); } TMetricHolder TRecallCachingMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(!isExpApprox); Y_ASSERT(approxDelta.empty()); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; }; TMetricHolder error(2); error.Stats[0] = getStats(PositiveClass, PositiveClass); for (auto i : xrange(ClassesCount)) { error.Stats[1] += getStats(i, PositiveClass); } return error; } TMetricHolder TRecallCachingMetric::Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const { Y_ASSERT(approxDelta.empty()); TMetricHolder error(2); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(MultiLabelConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[PositiveClass * BinaryConfusionMatrixSize + i * 2 + j]; }; error.Stats[0] = getStats(1, 1); error.Stats[1] = getStats(1, 1) + getStats(0, 1); return error; } TString TRecallCachingMetric::GetDescription() const { if (IsMultiClass) { const TMetricParam positiveClass(""class"", PositiveClass, /*userDefined*/true); return BuildDescription(ELossFunction::Recall, UseWeights, positiveClass); } else { return BuildDescription(ELossFunction::Recall, UseWeights, ""%.3g"", MakeTargetBorderParam(TargetBorder), MakePredictionBorderParam(PredictionBorder)); } } double TRecallCachingMetric::GetFinalError(const TMetricHolder& error) const { return error.Stats[1] != 0 ? error.Stats[0] / error.Stats[1] : 1; } void TRecallCachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const { *valueType = EMetricBestValue::Max; } TVector TRecallCachingMetric::ValidParamSets() { return {TParamSet{{TParamInfo{""use_weights"", false, true}}, """"}}; }; /* Precision caching metric */ namespace { struct TPrecisionCachingMetric final: public TCachingUniversalMetric { explicit TPrecisionCachingMetric(const TLossParams& params, double predictionBorder) : TCachingUniversalMetric(ELossFunction::Precision, params) , ClassesCount(BinaryClassesCount) , PredictionBorder(predictionBorder) , IsMultiClass(false) { } explicit TPrecisionCachingMetric(const TLossParams& params, int classesCount, int positiveClass) : TCachingUniversalMetric(ELossFunction::Precision, params) , ClassesCount(classesCount) , PositiveClass(positiveClass) , IsMultiClass(true) { } using ISingleTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const override; using IMultiTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const override; TString GetDescription() const override; double GetFinalError(const TMetricHolder& error) const override; void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override; bool IsAdditiveMetric() const override { return true; } static TVector ValidParamSets(); private: static constexpr double TargetBorder = GetDefaultTargetBorder(); const int ClassesCount = BinaryClassesCount; const int PositiveClass = 1; const double PredictionBorder = GetDefaultPredictionBorder(); const bool IsMultiClass = false; }; } THolder MakeBinClassPrecisionMetric(const TLossParams& params, double predictionBorder) { return MakeHolder(params, predictionBorder); } THolder MakeMultiClassPrecisionMetric(const TLossParams& params, int classesCount, int positiveClass) { return MakeHolder(params, classesCount, positiveClass); } TMetricHolder TPrecisionCachingMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(!isExpApprox); Y_ASSERT(approxDelta.empty()); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; }; TMetricHolder error(2); error.Stats[0] = getStats(PositiveClass, PositiveClass); for (auto i : xrange(ClassesCount)) { error.Stats[1] += getStats(PositiveClass, i); } return error; } TMetricHolder TPrecisionCachingMetric::Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const { Y_ASSERT(approxDelta.empty()); TMetricHolder error(2); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(MultiLabelConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[PositiveClass * BinaryConfusionMatrixSize + i * 2 + j]; }; error.Stats[0] = getStats(1, 1); error.Stats[1] = getStats(1, 1) + getStats(1, 0); return error; } TString TPrecisionCachingMetric::GetDescription() const { if (IsMultiClass) { const TMetricParam positiveClass(""class"", PositiveClass, /*userDefined*/true); return BuildDescription(ELossFunction::Precision, UseWeights, positiveClass); } else { return BuildDescription(ELossFunction::Precision, UseWeights, ""%.3g"", MakeTargetBorderParam(TargetBorder), MakePredictionBorderParam(PredictionBorder)); } } double TPrecisionCachingMetric::GetFinalError(const TMetricHolder& error) const { return error.Stats[1] != 0 ? error.Stats[0] / error.Stats[1] : 1; } void TPrecisionCachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const { *valueType = EMetricBestValue::Max; } TVector TPrecisionCachingMetric::ValidParamSets() { return {TParamSet{{TParamInfo{""use_weights"", false, true}}, """"}}; }; /* F beta caching metric */ namespace { struct TFCachingMetric: public TCachingUniversalMetric { explicit TFCachingMetric(const TLossParams& params, double beta, double predictionBorder) : TCachingUniversalMetric(ELossFunction::F, params) , ClassesCount(BinaryClassesCount) , Beta(beta) , PredictionBorder(predictionBorder) , IsMultiClass(false) { Y_ASSERT(Beta > 0); } explicit TFCachingMetric(const TLossParams& params, double beta, int classesCount, int positiveClass) : TCachingUniversalMetric(ELossFunction::F, params) , ClassesCount(classesCount) , PositiveClass(positiveClass) , Beta(beta) , IsMultiClass(true) { Y_ASSERT(Beta > 0); } using ISingleTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const override; using IMultiTargetEval::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const override; TString GetDescription() const override; TVector GetStatDescriptions() const override; double GetFinalError(const TMetricHolder& error) const override; void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override; bool IsAdditiveMetric() const override { return true; } static TVector ValidParamSets(); protected: static constexpr double TargetBorder = GetDefaultTargetBorder(); const int ClassesCount = BinaryClassesCount; const int PositiveClass = 1; const double Beta = 1; const double PredictionBorder = GetDefaultPredictionBorder(); const bool IsMultiClass = false; }; } THolder MakeBinClassFMetric(const TLossParams& params, double beta, double predictionBorder) { return MakeHolder(params, beta, predictionBorder); } THolder MakeMultiClassFMetric(const TLossParams& params, double beta, int classesCount, int positiveClass) { return MakeHolder(params, beta, classesCount, positiveClass); } TMetricHolder TFCachingMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(!isExpApprox); Y_ASSERT(approxDelta.empty()); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; }; TMetricHolder error(3); error.Stats[0] = getStats(PositiveClass, PositiveClass); for (auto i : xrange(ClassesCount)) { error.Stats[1] += getStats(PositiveClass, i); error.Stats[2] += getStats(i, PositiveClass); } return error; } TMetricHolder TFCachingMetric::Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, TConstArrayRef> target, TConstArrayRef weight, int begin, int end, TMaybe cache ) const { Y_ASSERT(approxDelta.empty()); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() ? makeMatrix() : cache.GetRef()->Get(MultiLabelConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[PositiveClass * BinaryConfusionMatrixSize + i * 2 + j]; }; TMetricHolder error(3); error.Stats[0] = getStats(1, 1); error.Stats[1] = getStats(1, 1) + getStats(1, 0); error.Stats[2] = getStats(1, 1) + getStats(0, 1); return error; } TVector TFCachingMetric::GetStatDescriptions() const { return {""TP"", ""TP+FP"", ""TP+FN""}; } TString TFCachingMetric::GetDescription() const { const TMetricParam beta(""beta"", Beta, /*userDefined*/true); if (IsMultiClass) { const TMetricParam positiveClass(""class"", PositiveClass, /*userDefined*/true); return BuildDescription(ELossFunction::F, UseWeights, ""%.3g"", beta, positiveClass); } else { return BuildDescription(ELossFunction::F, UseWeights, ""%.3g"", beta,""%.3g"", MakeTargetBorderParam(TargetBorder), MakePredictionBorderParam(PredictionBorder)); } } double TFCachingMetric::GetFinalError(const TMetricHolder& error) const { double precision = error.Stats[1] != 0 ? error.Stats[0] / error.Stats[1] : 1.0; double recall = error.Stats[2] != 0 ? error.Stats[0] / error.Stats[2] : 1.0; double beta_square = Beta * Beta; return precision + recall != 0 ? (1 + beta_square) * precision * recall / (beta_square * precision + recall) : 0.0; } void TFCachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const { *valueType = EMetricBestValue::Max; } TVector TFCachingMetric::ValidParamSets() { return { TParamSet{ { TParamInfo{""use_weights"", false, true}, TParamInfo{""beta"", true, {}} }, """" } }; } /* F1 caching metric */ namespace { struct TF1CachingMetric final : public TFCachingMetric { explicit TF1CachingMetric(const TLossParams ¶ms, double predictionBorder) : TFCachingMetric(params, 1.0, predictionBorder) { } explicit TF1CachingMetric(const TLossParams ¶ms, int classesCount, int positiveClass) : TFCachingMetric(params, 1.0, classesCount, positiveClass) { } TString GetDescription() const override; static TVector ValidParamSets(); }; } THolder MakeBinClassF1Metric(const TLossParams& params, double predictionBorder) { return MakeHolder(params, predictionBorder); } THolder MakeMultiClassF1Metric(const TLossParams& params, int classesCount, int positiveClass) { return MakeHolder(params, classesCount, positiveClass); } TString TF1CachingMetric::GetDescription() const { if (IsMultiClass) { const TMetricParam positiveClass(""class"", PositiveClass, /*userDefined*/true); return BuildDescription(ELossFunction::F1, UseWeights, positiveClass); } else { return BuildDescription(ELossFunction::F1, UseWeights, ""%.3g"", MakeTargetBorderParam(TargetBorder), MakePredictionBorderParam(PredictionBorder)); } } TVector TF1CachingMetric::ValidParamSets() { return {TParamSet{{TParamInfo{""use_weights"", false, true}}, """"}}; }; /* TotalF1 caching metric */ namespace { struct TTotalF1CachingMetric final: public TCachingSingleTargetMetric { static constexpr int StatsCardinality = 3; explicit TTotalF1CachingMetric(const TLossParams& params, double predictionBorder, EF1AverageType averageType) : TCachingSingleTargetMetric(ELossFunction::TotalF1, params) , ClassesCount(BinaryClassesCount) , PredictionBorder(predictionBorder) , AverageType(averageType) { } explicit TTotalF1CachingMetric(const TLossParams& params, int classesCount, EF1AverageType averageType) : TCachingSingleTargetMetric(ELossFunction::TotalF1, params) , ClassesCount(classesCount) , AverageType(averageType) { } using TSingleTargetMetric::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const override; TVector GetStatDescriptions() const override; double GetFinalError(const TMetricHolder& error) const override; void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override; bool IsAdditiveMetric() const override { return true; } static TVector ValidParamSets(); private: static constexpr double TargetBorder = GetDefaultTargetBorder(); const int ClassesCount = BinaryClassesCount; const double PredictionBorder = GetDefaultPredictionBorder(); const EF1AverageType AverageType; }; } THolder MakeTotalF1Metric(const TLossParams& params, int classesCount, EF1AverageType averageType) { return MakeHolder(params, classesCount, averageType); } TMetricHolder TTotalF1CachingMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(!isExpApprox); Y_ASSERT(approxDelta.empty()); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; auto confusionMatrix = cache.Empty() || 1 ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; }; TVector classTruePositive(ClassesCount); TVector classSize(ClassesCount); TVector classPredictedSize(ClassesCount); for (auto i : xrange(ClassesCount)) { classTruePositive[i] = getStats(i, i); for (auto j : xrange(ClassesCount)) { classSize[i] += getStats(j, i); classPredictedSize[i] += getStats(i, j); } } TMetricHolder error(StatsCardinality * ClassesCount); for (auto i : xrange(ClassesCount)) { error.Stats[StatsCardinality * i + 0] = classSize[i]; error.Stats[StatsCardinality * i + 1] = classPredictedSize[i]; error.Stats[StatsCardinality * i + 2] = classTruePositive[i]; } return error; } TVector TTotalF1CachingMetric::GetStatDescriptions() const { TVector description; for (auto classIdx : xrange(ClassesCount)) { auto prefix = ""Class="" + ToString(classIdx) + "",""; description.push_back(prefix + ""TP+FN""); description.push_back(prefix + ""TP+FP""); description.push_back(prefix + ""TP""); } return description; } double TTotalF1CachingMetric::GetFinalError(const TMetricHolder& error) const { double numerator = 0.0; double denumerator = 0.0; for (auto i : xrange(ClassesCount)) { double classSize = error.Stats[StatsCardinality * i + 0]; double classPredictedSize = error.Stats[StatsCardinality * i + 1]; double truePositive = error.Stats[StatsCardinality * i + 2]; double f1 = classSize + classPredictedSize != 0 ? 2 * truePositive / (classSize + classPredictedSize) : 0.0; if (AverageType == EF1AverageType::Weighted) { numerator += f1 * classSize; denumerator += classSize; } else if (AverageType == EF1AverageType::Micro) { numerator += 2 * truePositive; denumerator += classSize + classPredictedSize; } else if (AverageType == EF1AverageType::Macro) { numerator += f1; denumerator += 1; } } return numerator / denumerator; } void TTotalF1CachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const { *valueType = EMetricBestValue::Max; } TVector TTotalF1CachingMetric::ValidParamSets() { return { TParamSet{ { TParamInfo{""use_weights"", false, true}, TParamInfo{""average"", false, ToString(EF1AverageType::Weighted)} }, """" } }; }; /* Kappa */ namespace { struct TKappaMetric final: public TCachingSingleTargetMetric { explicit TKappaMetric(const TLossParams& params, int classCount = 2, double predictionBorder = GetDefaultPredictionBorder()) : TCachingSingleTargetMetric(ELossFunction::Kappa, params) , TargetBorder(GetDefaultTargetBorder()) , PredictionBorder(predictionBorder) , ClassCount(classCount) { } static TVector> Create(const TMetricConfig& config); static TVector ValidParamSets(); using TSingleTargetMetric::Eval; TMetricHolder Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef queriesInfo, int begin, int end, TMaybe cache ) const override; TString GetDescription() const override; double GetFinalError(const TMetricHolder& error) const override; void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override; bool IsAdditiveMetric() const override { return true; } private: const double TargetBorder = GetDefaultTargetBorder(); const double PredictionBorder = GetDefaultPredictionBorder(); const int ClassCount; }; } // static. TVector> TKappaMetric::Create(const TMetricConfig& config) { if (config.ApproxDimension == 1) { config.ValidParams->insert(""border""); return AsVector(MakeHolder(config.Params, /*classCount=*/2, config.GetPredictionBorderOrDefault())); } else { return AsVector(MakeHolder(config.Params, config.ApproxDimension)); } } TMetricHolder TKappaMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(approxDelta.empty()); Y_ASSERT(!isExpApprox); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; return cache.Empty() || 1 ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); } TString TKappaMetric::GetDescription() const { return BuildDescription(ELossFunction::Kappa, ""%.3g"", MakeTargetBorderParam(TargetBorder), MakePredictionBorderParam(PredictionBorder)); } void TKappaMetric::GetBestValue(EMetricBestValue* valueType, float*) const { *valueType = EMetricBestValue::Max; } double TKappaMetric::GetFinalError(const TMetricHolder& error) const { return CalcKappa(error, ClassCount, EKappaMetricType::Cohen); } TVector TKappaMetric::ValidParamSets() { return {TParamSet{{TParamInfo{""use_weights"", false, true}}, """"}}; }; /* WKappa */ namespace { struct TWKappaMetric final: public TCachingSingleTargetMetric { explicit TWKappaMetric(const TLossParams& params, int classCount = 2, double predictionBorder = GetDefaultPredictionBorder()) : TCachingSingleTargetMetric(ELossFunction::WKappa, params) , TargetBorder(GetDefaultTargetBorder()) , PredictionBorder(predictionBorder) , ClassCount(classCount) { } static TVector> Create(const TMetricConfig& config); static TVector ValidParamSets(); using TSingleTargetMetric::Eval; TMetricHolder Eval( TConstArrayRef> approx, TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef queriesInfo, int begin, int end, TMaybe cache ) const override; TString GetDescription() const override; double GetFinalError(const TMetricHolder& error) const override; void GetBestValue(EMetricBestValue *valueType, float *bestValue) const override; bool IsAdditiveMetric() const override { return true; } private: const double TargetBorder = GetDefaultTargetBorder(); const double PredictionBorder = GetDefaultPredictionBorder(); const int ClassCount; }; } // static. TVector> TWKappaMetric::Create(const TMetricConfig& config) { if (config.ApproxDimension == 1) { config.ValidParams->insert(""border""); return AsVector(MakeHolder(config.Params, /*classCount=*/2, config.GetPredictionBorderOrDefault())); } else { return AsVector(MakeHolder(config.Params, config.ApproxDimension)); } } TMetricHolder TWKappaMetric::Eval( const TConstArrayRef> approx, const TConstArrayRef> approxDelta, bool isExpApprox, TConstArrayRef target, TConstArrayRef weight, TConstArrayRef /*queriesInfo*/, int begin, int end, TMaybe cache ) const { Y_ASSERT(approxDelta.empty()); Y_ASSERT(!isExpApprox); const auto makeMatrix = [&]() { return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector{}, begin, end, TargetBorder, PredictionBorder); }; return cache.Empty() || 1 ? makeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, makeMatrix, bool(UseWeights), TargetBorder, PredictionBorder); } TString TWKappaMetric::GetDescription() const { return BuildDescription(ELossFunction::WKappa, ""%.3g"", MakeTargetBorderParam(TargetBorder), MakePredictionBorderParam(PredictionBorder)); } void TWKappaMetric::GetBestValue(EMetricBestValue* valueType, float*) const { *valueType = EMetricBestValue::Max; } double TWKappaMetric::GetFinalError(const TMetricHolder& error) const { return CalcKappa(error, ClassCount, EKappaMetricType::Weighted); } TVector TWKappaMetric::ValidParamSets() { return {TParamSet{{TParamInfo{""use_weights"", false, true}}, """"}}; }; TVector EvalErrorsWithCaching( const TVector>& approx, const TVector>& approxDelta, bool isExpApprox, TConstArrayRef> target, TConstArrayRef weight, TConstArrayRef queriesInfo, TConstArrayRef metrics, NPar::ILocalExecutor* localExecutor ) { const auto threadCount = localExecutor->GetThreadCount() + 1; const auto objectCount = approx.front().size(); const auto queryCount = queriesInfo.size(); const auto approxRef = To2DConstArrayRef(approx); const auto approxDeltaRef = To2DConstArrayRef(approxDelta); const auto calcCaching = [&](auto metric, auto from, auto to, auto *cache) { if (target.size() <= 1 && dynamic_cast(metric) != nullptr) { CB_ENSURE(!metric->NeedTarget() || target.size() == 1, ""Metric ["" + metric->GetDescription() + ""] requires "" << (target.size() > 1 ? ""one-dimensional"" : """") << ""target""); return dynamic_cast(metric)->Eval( approxRef, approxDeltaRef, isExpApprox, metric->NeedTarget() ? target[0] : TConstArrayRef(), weight, queriesInfo, from, to, cache ); } else { CB_ENSURE(!isExpApprox, ""Metric ["" << metric->GetDescription() << ""] does not support exponentiated approxes""); return dynamic_cast(metric)->Eval( approxRef, approxDeltaRef, target, weight, from, to, cache ); } }; const auto calcNonCaching = [&](auto metric, auto from, auto to) { if (target.size() <= 1 && dynamic_cast(metric) != nullptr) { CB_ENSURE(!metric->NeedTarget() || target.size() == 1, ""Metric ["" + metric->GetDescription() + ""] requires "" << (target.size() > 1 ? ""one-dimensional"" : """") << ""target""); return dynamic_cast(metric)->Eval( approxRef, approxDeltaRef, isExpApprox, metric->NeedTarget() ? target[0] : TConstArrayRef(), weight, queriesInfo, from, to, *localExecutor ); } else { CB_ENSURE(!isExpApprox, ""Metric ["" << metric->GetDescription() << ""] does not support exponentiated approxes""); return dynamic_cast(metric)->Eval( approxRef, approxDeltaRef, target, weight, from, to, *localExecutor ); } }; TVector errors; errors.reserve(metrics.size()); NPar::ILocalExecutor::TExecRangeParams objectwiseBlockParams(0, objectCount); if (!target.empty()) { const auto objectwiseEffectiveBlockCount = Min(threadCount, int(ceil(double(objectCount) / GetMinBlockSize(objectCount)))); objectwiseBlockParams.SetBlockCount(objectwiseEffectiveBlockCount); } NPar::ILocalExecutor::TExecRangeParams querywiseBlockParams(0, queryCount); if (!queriesInfo.empty()) { const auto querywiseEffectiveBlockCount = Min(threadCount, int(ceil(double(queryCount) / GetMinBlockSize(objectCount)))); querywiseBlockParams.SetBlockCount(querywiseEffectiveBlockCount); } TCache nonAdditiveCache; TVector objectwiseAdditiveCache(objectwiseBlockParams.GetBlockCount()); TVector querywiseAdditiveCache(querywiseBlockParams.GetBlockCount()); TVector objectwiseBlockResults(objectwiseBlockParams.GetBlockCount()); TVector querywiseBlockResults(querywiseBlockParams.GetBlockCount()); for (auto i : xrange(metrics.size())) { auto metric = metrics[i]; const bool isObjectwise = metric->GetErrorType() == EErrorType::PerObjectError; const auto end = isObjectwise ? objectCount : queryCount; const bool isCaching = dynamic_cast(metric) || dynamic_cast(metric); if (isCaching && metric->IsAdditiveMetric()) { const auto blockSize = isObjectwise ? objectwiseBlockParams.GetBlockSize() : querywiseBlockParams.GetBlockSize(); const auto blockCount = isObjectwise ? objectwiseBlockParams.GetBlockCount() : querywiseBlockParams.GetBlockCount(); auto &results = isObjectwise ? objectwiseBlockResults : querywiseBlockResults; auto &cache = isObjectwise ? objectwiseAdditiveCache : querywiseAdditiveCache; NPar::ParallelFor(*localExecutor, 0, blockCount, [&](auto blockId) { const auto from = blockId * blockSize; const auto to = Min((blockId + 1) * blockSize, end); results[blockId] = calcCaching(metric, from, to, &cache[blockId]); }); TMetricHolder error; for (const auto &blockResult : results) { error.Add(blockResult); } errors.push_back(error); } else { if (isCaching) { errors.push_back(calcCaching(metric, 0, end, &nonAdditiveCache)); } else { errors.push_back(calcNonCaching(metric, 0, end)); } } } return errors; } template static TVector> CreateMetric(int approxDimension, const TMetricConfig& config) { TVector> result; if (approxDimension == 1) { result.emplace_back(MakeHolder(config.Params, config.GetPredictionBorderOrDefault())); } else { result.emplace_back(MakeHolder(config.Params, approxDimension)); } return result; } template static TVector> CreateMetricClasswise(int approxDimension, const TMetricConfig& config) { TVector> result; if (approxDimension == 1) { result.emplace_back(MakeHolder(config.Params, config.GetPredictionBorderOrDefault())); } else { for (int i : xrange(approxDimension)) { result.emplace_back(MakeHolder(config.Params, approxDimension, i)); } } return result; } TVector> CreateCachingMetrics(const TMetricConfig& config) { *config.ValidParams = TSet{}; TVector> result; switch(config.Metric) { case ELossFunction::F1: { return CreateMetricClasswise(config.ApproxDimension, config); } case ELossFunction::F: { CB_ENSURE(config.GetParamsMap().contains(""beta""), ""Metric "" << ELossFunction::F << "" requires beta as parameter""); config.ValidParams->insert(""beta""); double beta_param = FromString(config.GetParamsMap().at(""beta"")); if (config.ApproxDimension == 1) { result.emplace_back(MakeHolder(config.Params, beta_param, config.GetPredictionBorderOrDefault())); } else { for (int i : xrange(config.ApproxDimension)) { result.emplace_back(MakeHolder(config.Params, beta_param, config.ApproxDimension, i)); } } return result; } case ELossFunction::TotalF1: { config.ValidParams->insert(""average""); EF1AverageType averageType = EF1AverageType::Weighted; if (config.GetParamsMap().contains(""average"")) { averageType = FromString(config.GetParamsMap().at(""average"")); } if (config.ApproxDimension == 1) { result.emplace_back(MakeHolder(config.Params, config.GetPredictionBorderOrDefault(), averageType)); } else { result.emplace_back(MakeHolder(config.Params, config.ApproxDimension, averageType)); } return result; } case ELossFunction::MCC: { return CreateMetric(config.ApproxDimension, config); } case ELossFunction::BrierScore: { CB_ENSURE(config.ApproxDimension == 1, ""Brier Score is used only for binary classification problems.""); result.emplace_back(MakeBrierScoreMetric(config.Params)); return result; } case ELossFunction::ZeroOneLoss: { return CreateMetric(config.ApproxDimension, config); } case ELossFunction::HammingLoss: { return CreateMetric(config.ApproxDimension, config); } case ELossFunction::Accuracy: { config.ValidParams->insert(""type""); EAccuracyType accuracyType = EAccuracyType::Classic; if (config.GetParamsMap().contains(""type"")) { accuracyType = FromString(config.GetParamsMap().at(""type"")); } if (accuracyType == EAccuracyType::Classic) { return CreateMetric(config.ApproxDimension, config); } else if (accuracyType == EAccuracyType::PerClass) { return CreateMetricClasswise(config.ApproxDimension, config); } else { CB_ENSURE_INTERNAL(false, ""Unhandled accuracy type "" << accuracyType); } } case ELossFunction::CtrFactor: { result.emplace_back(MakeCtrFactorMetric(config.Params)); return result; } case ELossFunction::Precision: { return CreateMetricClasswise(config.ApproxDimension, config); } case ELossFunction::Recall: return CreateMetricClasswise(config.ApproxDimension, config); break; case ELossFunction::Kappa: AppendTemporaryMetricsVector(TKappaMetric::Create(config), &result); break; case ELossFunction::WKappa: AppendTemporaryMetricsVector(TWKappaMetric::Create(config), &result); break; default: break; } return result; } TVector CachingMetricValidParamSets(ELossFunction metric) { switch (metric) { case ELossFunction::F: return TFCachingMetric::ValidParamSets(); case ELossFunction::F1: return TF1CachingMetric::ValidParamSets(); case ELossFunction::TotalF1: return TTotalF1CachingMetric::ValidParamSets(); case ELossFunction::MCC: return TMCCCachingMetric::ValidParamSets(); case ELossFunction::ZeroOneLoss: return TZeroOneLossCachingMetric::ValidParamSets(); case ELossFunction::Accuracy: return TAccuracyCachingMetric::ValidParamSets(); case ELossFunction::HammingLoss: return THammingLossCachingMetric::ValidParamSets(); case ELossFunction::Precision: return TPrecisionCachingMetric::ValidParamSets(); case ELossFunction::Recall: return TRecallCachingMetric::ValidParamSets(); case ELossFunction::Kappa: return TKappaMetric::ValidParamSets(); case ELossFunction::WKappa: return TWKappaMetric::ValidParamSets(); default: CB_ENSURE(false, ""Unsupported metric: "" << metric); } } ",16243,True,3830.951729207512,median " = Elytron Elytron can generate the audit log to the same directory where the {Thorntail} application is executed. Include the following section in the `project-defaults.yml` file in your application: [source,text] ---- thorntail: elytron: file-audit-logs: local-audit: path: audit.log ---- In some environments, for example cloud, you might have to relocate the audit file to a globally writable directory, for example: ---- thorntail: elytron: file-audit-logs: local-audit: path: /tmp/audit.log ---- .Maven Coordinates [source,xml] ---- io.thorntail elytron ---- .Configuration thorntail.elytron.add-prefix-role-mappers._KEY_.prefix:: The prefix to add to each role. thorntail.elytron.add-suffix-role-mappers._KEY_.suffix:: The suffix to add to each role. thorntail.elytron.aggregate-http-server-mechanism-factories._KEY_.available-mechanisms:: The HTTP mechanisms available from this factory instance. thorntail.elytron.aggregate-http-server-mechanism-factories._KEY_.http-server-mechanism-factories:: The referenced http server factories to aggregate. thorntail.elytron.aggregate-principal-decoders._KEY_.principal-decoders:: The referenced principal decoders to aggregate. thorntail.elytron.aggregate-principal-transformers._KEY_.principal-transformers:: The referenced principal transformers to aggregate. thorntail.elytron.aggregate-providers._KEY_.providers:: The referenced Provider[] resources to aggregate. thorntail.elytron.aggregate-realms._KEY_.authentication-realm:: Reference to the security realm to use for authentication steps (obtaining or validating credentials). thorntail.elytron.aggregate-realms._KEY_.authorization-realm:: Reference to the security realm to use for loading the identity for authorization steps (loading of the identity). thorntail.elytron.aggregate-role-mappers._KEY_.role-mappers:: The referenced role mappers to aggregate. thorntail.elytron.aggregate-sasl-server-factories._KEY_.available-mechanisms:: The SASL mechanisms available from this factory after all filtering has been applied. thorntail.elytron.aggregate-sasl-server-factories._KEY_.sasl-server-factories:: The referenced sasl server factories to aggregate. thorntail.elytron.aggregate-security-event-listeners._KEY_.security-event-listeners:: The referenced security event listener resources to aggregate. thorntail.elytron.authentication-configurations._KEY_.anonymous:: Enables anonymous authentication. thorntail.elytron.authentication-configurations._KEY_.attribute-extends:: A previously defined authentication configuration to extend. thorntail.elytron.authentication-configurations._KEY_.authentication-name:: The authentication name to use. thorntail.elytron.authentication-configurations._KEY_.authorization-name:: The authorization name to use. thorntail.elytron.authentication-configurations._KEY_.credential-reference:: The reference to credential stored in CredentialStore under defined alias or clear text password. thorntail.elytron.authentication-configurations._KEY_.forwarding-mode:: The type of security identity forwarding to use. A mode of 'authentication' forwarding forwards the principal and credential. A mode of 'authorization' forwards the authorization id, allowing for a different authentication identity. thorntail.elytron.authentication-configurations._KEY_.host:: The host to use. thorntail.elytron.authentication-configurations._KEY_.kerberos-security-factory:: Reference to a kerberos security factory used to obtain a GSS kerberos credential thorntail.elytron.authentication-configurations._KEY_.mechanism-properties:: Configuration properties for the SASL authentication mechanism. thorntail.elytron.authentication-configurations._KEY_.port:: The port to use. thorntail.elytron.authentication-configurations._KEY_.protocol:: The protocol to use. thorntail.elytron.authentication-configurations._KEY_.realm:: The realm to use. thorntail.elytron.authentication-configurations._KEY_.sasl-mechanism-selector:: The SASL mechanism selector string. thorntail.elytron.authentication-configurations._KEY_.security-domain:: Reference to a security domain to obtain a forwarded identity. thorntail.elytron.authentication-contexts._KEY_.attribute-extends:: A previously defined authentication context to extend. thorntail.elytron.authentication-contexts._KEY_.match-rules:: The match-rules for this authentication context. thorntail.elytron.caching-realms._KEY_.maximum-age:: The time in milliseconds that an item can stay in the cache. thorntail.elytron.caching-realms._KEY_.maximum-entries:: The maximum number of entries to keep in the cache. thorntail.elytron.caching-realms._KEY_.realm:: A reference to a cacheable security realm. thorntail.elytron.certificate-authority-accounts._KEY_.alias:: The alias of certificate authority account key in the keystore. If the alias does not already exist in the keystore, a certificate authority account key will be automatically generated and stored as a PrivateKeyEntry under the alias. thorntail.elytron.certificate-authority-accounts._KEY_.certificate-authority:: The name of the certificate authority to use. Allowed values: 'LetsEncrypt' thorntail.elytron.certificate-authority-accounts._KEY_.contact-urls:: A list of URLs that the certificate authority can contact about any issues related to this account. thorntail.elytron.certificate-authority-accounts._KEY_.credential-reference:: Credential to be used when accessing the certificate authority account key. thorntail.elytron.certificate-authority-accounts._KEY_.key-store:: The keystore that contains the certificate authority account key. thorntail.elytron.chained-principal-transformers._KEY_.principal-transformers:: The referenced principal transformers to chain. thorntail.elytron.client-ssl-contexts._KEY_.active-session-count:: The count of current active sessions. thorntail.elytron.client-ssl-contexts._KEY_.cipher-suite-filter:: The filter to apply to specify the enabled cipher suites. thorntail.elytron.client-ssl-contexts._KEY_.key-manager:: Reference to the key manager to use within the SSLContext. thorntail.elytron.client-ssl-contexts._KEY_.protocols:: The enabled protocols. thorntail.elytron.client-ssl-contexts._KEY_.provider-name:: The name of the provider to use. If not specified, all providers from providers will be passed to the SSLContext. thorntail.elytron.client-ssl-contexts._KEY_.providers:: The name of the providers to obtain the Provider[] to use to load the SSLContext. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.application-buffer-size:: The application buffer size as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.cipher-suite:: The selected cipher suite as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.creation-time:: The creation time as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.last-accessed-time:: The last accessed time as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.local-certificates:: The local certificates from the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.local-principal:: The local principal as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.packet-buffer-size:: The packet buffer size as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.peer-certificates:: The peer certificates from the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.peer-host:: The peer host as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.peer-port:: The peer port as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.peer-principal:: The peer principal as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.protocol:: The protocol as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.ssl-sessions._KEY_.valid:: The validity of the session as reported by the SSLSession. thorntail.elytron.client-ssl-contexts._KEY_.trust-manager:: Reference to the trust manager to use within the SSLContext. thorntail.elytron.concatenating-principal-decoders._KEY_.joiner:: The string to use to join the results of the referenced principal decoders. thorntail.elytron.concatenating-principal-decoders._KEY_.principal-decoders:: The referenced principal decoders to concatenate. thorntail.elytron.configurable-http-server-mechanism-factories._KEY_.available-mechanisms:: The HTTP mechanisms available from this factory instance. thorntail.elytron.configurable-http-server-mechanism-factories._KEY_.filters:: Filtering to be applied to enable / disable mechanisms based on the name. thorntail.elytron.configurable-http-server-mechanism-factories._KEY_.http-server-mechanism-factory:: The http server factory to be wrapped. thorntail.elytron.configurable-http-server-mechanism-factories._KEY_.properties:: Custom properties to be passed in to the http server factory calls. thorntail.elytron.configurable-sasl-server-factories._KEY_.available-mechanisms:: The SASL mechanisms available from this factory after all filtering has been applied. thorntail.elytron.configurable-sasl-server-factories._KEY_.filters:: List of filters to be evaluated sequentially combining the results using 'or'. thorntail.elytron.configurable-sasl-server-factories._KEY_.properties:: Custom properties to be passed in to the sasl server factory calls. thorntail.elytron.configurable-sasl-server-factories._KEY_.protocol:: The protocol that should be passed into factory when creating the mechanism. thorntail.elytron.configurable-sasl-server-factories._KEY_.sasl-server-factory:: The sasl server factory to be wrapped. thorntail.elytron.configurable-sasl-server-factories._KEY_.server-name:: The server name that should be passed into factory when creating the mechanism. thorntail.elytron.constant-permission-mappers._KEY_.permission-sets:: The permission sets to assign. thorntail.elytron.constant-principal-decoders._KEY_.constant:: The constant value the principal decoder will always return. thorntail.elytron.constant-principal-transformers._KEY_.constant:: The constant value this PrincipalTransformer will always return. thorntail.elytron.constant-realm-mappers._KEY_.realm-name:: The name of the constant realm to return. thorntail.elytron.constant-role-mappers._KEY_.roles:: The constant roles to be returned by this role mapper. thorntail.elytron.credential-stores._KEY_.create:: Specifies whether credential store should create storage when it doesn't exist. thorntail.elytron.credential-stores._KEY_.credential-reference:: Credential reference to be used to create protection parameter. thorntail.elytron.credential-stores._KEY_.implementation-properties:: Map of credentials store implementation specific properties. thorntail.elytron.credential-stores._KEY_.location:: File name of credential store storage. thorntail.elytron.credential-stores._KEY_.modifiable:: Specifies whether credential store is modifiable. thorntail.elytron.credential-stores._KEY_.other-providers:: The name of the providers defined within the subsystem to obtain the Providers to search for the one that can create the required JCA objects within credential store. This is valid only for key-store based CredentialStore. If this is not specified then the global list of Providers is used instead. thorntail.elytron.credential-stores._KEY_.provider-name:: The name of the provider to use to instantiate the CredentialStoreSpi. If the provider is not specified then the first provider found that can create an instance of the specified 'type' will be used. thorntail.elytron.credential-stores._KEY_.providers:: The name of the providers defined within the subsystem to obtain the Providers to search for the one that can create the required CredentialStore type. If this is not specified then the global list of Providers is used instead. thorntail.elytron.credential-stores._KEY_.relative-to:: A reference to a previously defined path that the file name is relative to. thorntail.elytron.credential-stores._KEY_.state:: The state of the underlying service that represents this credential store at runtime. thorntail.elytron.credential-stores._KEY_.type:: The credential store type, e.g. KeyStoreCredentialStore. thorntail.elytron.custom-credential-security-factories._KEY_.class-name:: The class name of the implementation of the custom security factory. thorntail.elytron.custom-credential-security-factories._KEY_.configuration:: The optional key/value configuration for the custom security factory. thorntail.elytron.custom-credential-security-factories._KEY_.module:: The module to use to load the custom security factory. thorntail.elytron.custom-modifiable-realms._KEY_.class-name:: The class name of the implementation of the custom realm. thorntail.elytron.custom-modifiable-realms._KEY_.configuration:: The optional key/value configuration for the custom realm. thorntail.elytron.custom-modifiable-realms._KEY_.module:: The module to use to load the custom realm. thorntail.elytron.custom-permission-mappers._KEY_.class-name:: Fully qualified class name of the permission mapper thorntail.elytron.custom-permission-mappers._KEY_.configuration:: The optional kay/value configuration for the permission mapper thorntail.elytron.custom-permission-mappers._KEY_.module:: Name of the module to use to load the permission mapper thorntail.elytron.custom-principal-decoders._KEY_.class-name:: Fully qualified class name of the principal decoder thorntail.elytron.custom-principal-decoders._KEY_.configuration:: The optional kay/value configuration for the principal decoder thorntail.elytron.custom-principal-decoders._KEY_.module:: Name of the module to use to load the principal decoder thorntail.elytron.custom-principal-transformers._KEY_.class-name:: The class name of the implementation of the custom principal transformer. thorntail.elytron.custom-principal-transformers._KEY_.configuration:: The optional key/value configuration for the custom principal transformer. thorntail.elytron.custom-principal-transformers._KEY_.module:: The module to use to load the custom principal transformer. thorntail.elytron.custom-realm-mappers._KEY_.class-name:: Fully qualified class name of the RealmMapper thorntail.elytron.custom-realm-mappers._KEY_.configuration:: The optional kay/value configuration for the RealmMapper thorntail.elytron.custom-realm-mappers._KEY_.module:: Name of the module to use to load the RealmMapper thorntail.elytron.custom-realms._KEY_.class-name:: The class name of the implementation of the custom realm. thorntail.elytron.custom-realms._KEY_.configuration:: The optional key/value configuration for the custom realm. thorntail.elytron.custom-realms._KEY_.module:: The module to use to load the custom realm. thorntail.elytron.custom-role-decoders._KEY_.class-name:: Fully qualified class name of the RoleDecoder thorntail.elytron.custom-role-decoders._KEY_.configuration:: The optional kay/value configuration for the RoleDecoder thorntail.elytron.custom-role-decoders._KEY_.module:: Name of the module to use to load the RoleDecoder thorntail.elytron.custom-role-mappers._KEY_.class-name:: Fully qualified class name of the RoleMapper thorntail.elytron.custom-role-mappers._KEY_.configuration:: The optional key/value configuration for the RoleMapper thorntail.elytron.custom-role-mappers._KEY_.module:: Name of the module to use to load the RoleMapper thorntail.elytron.custom-security-event-listeners._KEY_.class-name:: The class name of the implementation of the custom security event listener. thorntail.elytron.custom-security-event-listeners._KEY_.configuration:: The optional key/value configuration for the custom security event listener. thorntail.elytron.custom-security-event-listeners._KEY_.module:: The module to use to load the custom security event listener. thorntail.elytron.default-authentication-context:: The default authentication context to be associated with all deployments. thorntail.elytron.default-ssl-context:: Reference to the SSLContext which should be globally registered as the default. thorntail.elytron.dir-contexts._KEY_.authentication-context:: The authentication context to obtain login credentials to connect to the LDAP server. Can be omitted if authentication-level is 'none' (anonymous). thorntail.elytron.dir-contexts._KEY_.authentication-level:: The authentication level (security level/authentication mechanism) to use. Corresponds to SECURITY_AUTHENTICATION ('java.naming.security.authentication') environment property. Allowed values: 'none', 'simple', sasl_mech, where sasl_mech is a space-separated list of SASL mechanism names. thorntail.elytron.dir-contexts._KEY_.connection-timeout:: The timeout for connecting to the LDAP server in milliseconds. thorntail.elytron.dir-contexts._KEY_.credential-reference:: The credential reference to authenticate and connect to the LDAP server. Can be omitted if authentication-level is 'none' (anonymous). thorntail.elytron.dir-contexts._KEY_.enable-connection-pooling:: Indicates if connection pooling is enabled. thorntail.elytron.dir-contexts._KEY_.module:: Name of module that will be used as class loading base. thorntail.elytron.dir-contexts._KEY_.principal:: The principal to authenticate and connect to the LDAP server. Can be omitted if authentication-level is 'none' (anonymous). thorntail.elytron.dir-contexts._KEY_.properties:: The additional connection properties for the DirContext. thorntail.elytron.dir-contexts._KEY_.read-timeout:: The read timeout for an LDAP operation in milliseconds. thorntail.elytron.dir-contexts._KEY_.referral-mode:: If referrals should be followed. thorntail.elytron.dir-contexts._KEY_.ssl-context:: The name of ssl-context used to secure connection to the LDAP server. thorntail.elytron.dir-contexts._KEY_.url:: The connection url. thorntail.elytron.disallowed-providers:: A list of providers that are not allowed, and will be removed from the providers list. thorntail.elytron.file-audit-logs._KEY_.attribute-synchronized:: Whether every event should be immediately synchronised to disk. thorntail.elytron.file-audit-logs._KEY_.autoflush:: Whether every event should be immediately flushed to disk (If undefined will default to the value of synchronized). thorntail.elytron.file-audit-logs._KEY_.format:: The format to use to record the audit event. thorntail.elytron.file-audit-logs._KEY_.path:: Path of the file to be written. thorntail.elytron.file-audit-logs._KEY_.relative-to:: The relative path to the audit log. thorntail.elytron.filesystem-realms._KEY_.encoded:: Whether the identity names should be stored encoded (Base32) in file names. thorntail.elytron.filesystem-realms._KEY_.levels:: The number of levels of directory hashing to apply. thorntail.elytron.filesystem-realms._KEY_.path:: The path to the file containing the realm. thorntail.elytron.filesystem-realms._KEY_.relative-to:: The pre-defined path the path is relative to. thorntail.elytron.filtering-key-stores._KEY_.alias-filter:: A filter to apply to the aliases returned from the KeyStore, can either be a comma separated list of aliases to return or one of the following formats ALL:-alias1:-alias2, NONE:+alias1:+alias2 thorntail.elytron.filtering-key-stores._KEY_.key-store:: Name of filtered KeyStore. thorntail.elytron.filtering-key-stores._KEY_.state:: The state of the underlying service that represents this KeyStore at runtime, if it is anything other than UP runtime operations will not be available. thorntail.elytron.final-providers:: Reference to the Providers that should be registered after all existing Providers. thorntail.elytron.http-authentication-factories._KEY_.available-mechanisms:: The HTTP mechanisms available from this configuration after all filtering has been applied. thorntail.elytron.http-authentication-factories._KEY_.http-server-mechanism-factory:: The HttpServerAuthenticationMechanismFactory to associate with this resource thorntail.elytron.http-authentication-factories._KEY_.mechanism-configurations:: Mechanism specific configuration thorntail.elytron.http-authentication-factories._KEY_.security-domain:: The SecurityDomain to associate with this resource thorntail.elytron.identity-realms._KEY_.attribute-name:: The name of the attribute associated with this identity. thorntail.elytron.identity-realms._KEY_.attribute-values:: The values associated with the identity attributes. thorntail.elytron.identity-realms._KEY_.identity:: The name of the identity available from the security realm. thorntail.elytron.initial-providers:: Reference to the Providers that should be registered ahead of all existing Providers. thorntail.elytron.jaspi-configurations._KEY_.application-context:: The application-context this configuration is to be associated with or '*' for all application contexts. thorntail.elytron.jaspi-configurations._KEY_.description:: Description of this configuration. thorntail.elytron.jaspi-configurations._KEY_.layer:: The layer this configuration is to be associated with or '*' for all layers. thorntail.elytron.jaspi-configurations._KEY_.server-auth-modules:: List of ServerAuthModule definitions for this configuration. thorntail.elytron.jdbc-realms._KEY_.principal-query:: The authentication query used to authenticate users based on specific key types. thorntail.elytron.kerberos-security-factories._KEY_.debug:: Should the JAAS step of obtaining the credential have debug logging enabled. thorntail.elytron.kerberos-security-factories._KEY_.fail-cache:: Amount of seconds before new try to obtain server credential should be done if it has failed last time. thorntail.elytron.kerberos-security-factories._KEY_.mechanism-names:: The mechanism names the credential should be usable with. Names will be converted to OIDs and used together with OIDs from mechanism-oids attribute. thorntail.elytron.kerberos-security-factories._KEY_.mechanism-oids:: The mechanism OIDs the credential should be usable with. Will be used together with OIDs derived from names from mechanism-names attribute. thorntail.elytron.kerberos-security-factories._KEY_.minimum-remaining-lifetime:: How much lifetime (in seconds) should a cached credential have remaining before it is recreated. thorntail.elytron.kerberos-security-factories._KEY_.obtain-kerberos-ticket:: Should the KerberosTicket also be obtained and associated with the credential. This is required to be true where credentials are delegated to the server. thorntail.elytron.kerberos-security-factories._KEY_.options:: The Krb5LoginModule additional options. thorntail.elytron.kerberos-security-factories._KEY_.path:: The path of the KeyTab to load to obtain the credential. thorntail.elytron.kerberos-security-factories._KEY_.principal:: The principal represented by the KeyTab thorntail.elytron.kerberos-security-factories._KEY_.relative-to:: The name of another previously named path, or of one of the standard paths provided by the system. If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute. thorntail.elytron.kerberos-security-factories._KEY_.request-lifetime:: How much lifetime (in seconds) should be requested for newly created credentials. thorntail.elytron.kerberos-security-factories._KEY_.required:: Is the keytab file with adequate principal required to exist at the time the service starts? thorntail.elytron.kerberos-security-factories._KEY_.server:: If this for use server side or client side? thorntail.elytron.kerberos-security-factories._KEY_.wrap-gss-credential:: Should generated GSS credentials be wrapped to prevent improper disposal or not? thorntail.elytron.key-managers._KEY_.algorithm:: The name of the algorithm to use to create the underlying KeyManagerFactory. thorntail.elytron.key-managers._KEY_.alias-filter:: A filter to apply to the aliases returned from the KeyStore, can either be a comma separated list of aliases to return or one of the following formats ALL:-alias1:-alias2, NONE:+alias1:+alias2 thorntail.elytron.key-managers._KEY_.credential-reference:: The credential reference to decrypt KeyStore item. (Not a password of the KeyStore.) thorntail.elytron.key-managers._KEY_.key-store:: Reference to the KeyStore to use to initialise the underlying KeyManagerFactory. thorntail.elytron.key-managers._KEY_.provider-name:: The name of the provider to use to create the underlying KeyManagerFactory. thorntail.elytron.key-managers._KEY_.providers:: Reference to obtain the Provider[] to use when creating the underlying KeyManagerFactory. thorntail.elytron.key-store-realms._KEY_.key-store:: Reference to the KeyStore that should be used to back this security realm. thorntail.elytron.key-stores._KEY_.alias-filter:: A filter to apply to the aliases returned from the KeyStore, can either be a comma separated list of aliases to return or one of the following formats ALL:-alias1:-alias2, NONE:+alias1:+alias2 thorntail.elytron.key-stores._KEY_.attribute-synchronized:: The time this KeyStore was last loaded or saved. Note: Some providers may continue to apply updates after the KeyStore was loaded within the application server. thorntail.elytron.key-stores._KEY_.credential-reference:: The reference to credential stored in CredentialStore under defined alias or clear text password. thorntail.elytron.key-stores._KEY_.loaded-provider:: Information about the provider that was used for this KeyStore. thorntail.elytron.key-stores._KEY_.modified:: Indicates if the in-memory representation of the KeyStore has been changed since it was last loaded or stored. Note: For some providers updates may be immediate without further load or store calls. thorntail.elytron.key-stores._KEY_.path:: The path to the KeyStore file. thorntail.elytron.key-stores._KEY_.provider-name:: The name of the provider to use to load the KeyStore, disables searching for the first Provider that can create a KeyStore of the specified type. thorntail.elytron.key-stores._KEY_.providers:: A reference to the providers that should be used to obtain the list of Provider instances to search, if not specified the global list of providers will be used instead. thorntail.elytron.key-stores._KEY_.relative-to:: The base path this store is relative to. thorntail.elytron.key-stores._KEY_.required:: Is the file required to exist at the time the KeyStore service starts? thorntail.elytron.key-stores._KEY_.size:: The number of entries in the KeyStore. thorntail.elytron.key-stores._KEY_.state:: The state of the underlying service that represents this KeyStore at runtime, if it is anything other than UP runtime operations will not be available. thorntail.elytron.key-stores._KEY_.type:: The type of the KeyStore, used when creating the new KeyStore instance. thorntail.elytron.ldap-key-stores._KEY_.alias-attribute:: The name of LDAP attribute, where will be item alias stored. thorntail.elytron.ldap-key-stores._KEY_.certificate-attribute:: The name of LDAP attribute, where will be certificate stored. thorntail.elytron.ldap-key-stores._KEY_.certificate-chain-attribute:: The name of LDAP attribute, where will be certificate chain stored. thorntail.elytron.ldap-key-stores._KEY_.certificate-chain-encoding:: The encoding of the certificate chain. thorntail.elytron.ldap-key-stores._KEY_.certificate-type:: The type of the Certificate. thorntail.elytron.ldap-key-stores._KEY_.dir-context:: The name of DirContext, which will be used to communication with LDAP server. thorntail.elytron.ldap-key-stores._KEY_.filter-alias:: The LDAP filter for obtaining an item of the KeyStore by alias. If this is not specified then the default value will be (alias_attribute={0}). The string '{0}' will be replaced by the searched alias and the 'alias_attribute' value will be the value of the attribute 'alias-attribute'. thorntail.elytron.ldap-key-stores._KEY_.filter-certificate:: The LDAP filter for obtaining an item of the KeyStore by certificate. If this is not specified then the default value will be (certificate_attribute={0}). The string '{0}' will be replaced by searched encoded certificate and the 'certificate_attribute' will be the value of the attribute 'certificate-attribute'. thorntail.elytron.ldap-key-stores._KEY_.filter-iterate:: The LDAP filter for iterating over all items of the KeyStore. If this is not specified then the default value will be (alias_attribute=*). The 'alias_attribute' will be the value of the attribute 'alias-attribute'. thorntail.elytron.ldap-key-stores._KEY_.key-attribute:: The name of LDAP attribute, where will be key stored. thorntail.elytron.ldap-key-stores._KEY_.key-type:: The type of KeyStore, in which will be key serialized to LDAP attribute. thorntail.elytron.ldap-key-stores._KEY_.new-item-template:: Configuration for item creation. Define how will look LDAP entry of newly created keystore item. thorntail.elytron.ldap-key-stores._KEY_.search-path:: The path in LDAP, where will be KeyStore items searched. thorntail.elytron.ldap-key-stores._KEY_.search-recursive:: If the LDAP search should be recursive. thorntail.elytron.ldap-key-stores._KEY_.search-time-limit:: The time limit for obtaining keystore items from LDAP. thorntail.elytron.ldap-key-stores._KEY_.size:: The size of LDAP KeyStore in amount of items/aliases. thorntail.elytron.ldap-key-stores._KEY_.state:: The state of the underlying service that represents this KeyStore at runtime, if it is anything other than UP runtime operations will not be available. thorntail.elytron.ldap-realms._KEY_.allow-blank-password:: Does this realm support blank password direct verification? Blank password attempt will be rejected otherwise. thorntail.elytron.ldap-realms._KEY_.dir-context:: The configuration to connect to a LDAP server. thorntail.elytron.ldap-realms._KEY_.direct-verification:: Does this realm support verification of credentials by directly connecting to LDAP as the account being authenticated? thorntail.elytron.ldap-realms._KEY_.identity-mapping:: The configuration options that define how principals are mapped to their corresponding entries in the underlying LDAP server. thorntail.elytron.logical-permission-mappers._KEY_.left:: Reference to the permission mapper to use to the left of the operation. thorntail.elytron.logical-permission-mappers._KEY_.logical-operation:: The logical operation to use to combine the permission mappers. thorntail.elytron.logical-permission-mappers._KEY_.right:: Reference to the permission mapper to use to the right of the operation. thorntail.elytron.logical-role-mappers._KEY_.left:: Reference to a role mapper to be used on the left side of the operation. thorntail.elytron.logical-role-mappers._KEY_.logical-operation:: The logical operation to be performed on the role mapper mappings. thorntail.elytron.logical-role-mappers._KEY_.right:: Reference to a role mapper to be used on the right side of the operation. thorntail.elytron.mapped-regex-realm-mappers._KEY_.delegate-realm-mapper:: The RealmMapper to delegate to if the pattern does not match. If no delegate is specified then the default realm on the domain will be used instead. If the username does not match the pattern and a delegate realm-mapper is present, the result of delegate-realm-mapper is mapped via the realm-map. thorntail.elytron.mapped-regex-realm-mappers._KEY_.pattern:: The regular expression which must contain at least one capture group to extract the realm from the name. If the regular expression matches more than one capture group, the first capture group is used. thorntail.elytron.mapped-regex-realm-mappers._KEY_.realm-map:: Mapping of realm name extracted using the regular expression to a defined realm name. If the value for the mapping is not in the map or the realm whose name is the result of the mapping does not exist in the given security domain, the default realm is used. thorntail.elytron.mapped-role-mappers._KEY_.keep-mapped:: When set to 'true' the mapped roles will retain all roles, that have defined mappings. thorntail.elytron.mapped-role-mappers._KEY_.keep-non-mapped:: When set to 'true' the mapped roles will retain all roles, that have no defined mappings. thorntail.elytron.mapped-role-mappers._KEY_.role-map:: A string to string list map for mapping roles. thorntail.elytron.mechanism-provider-filtering-sasl-server-factories._KEY_.available-mechanisms:: The SASL mechanisms available from this factory after all filtering has been applied. thorntail.elytron.mechanism-provider-filtering-sasl-server-factories._KEY_.enabling:: When set to 'true' no provider loaded mechanisms are enabled unless matched by one of the filters, setting to 'false' has the inverse effect. thorntail.elytron.mechanism-provider-filtering-sasl-server-factories._KEY_.filters:: The filters to apply when comparing the mechanisms from the providers, a filter matches when all of the specified values match the mechanism / provider pair. thorntail.elytron.mechanism-provider-filtering-sasl-server-factories._KEY_.sasl-server-factory:: Reference to a sasl server factory to be wrapped by this definition. thorntail.elytron.periodic-rotating-file-audit-logs._KEY_.attribute-synchronized:: Whether every event should be immediately synchronised to disk. thorntail.elytron.periodic-rotating-file-audit-logs._KEY_.autoflush:: Whether every event should be immediately flushed to disk (If undefined will default to the value of synchronized). thorntail.elytron.periodic-rotating-file-audit-logs._KEY_.format:: The format to use to record the audit event. thorntail.elytron.periodic-rotating-file-audit-logs._KEY_.path:: Path of the file to be written. thorntail.elytron.periodic-rotating-file-audit-logs._KEY_.relative-to:: The relative path to the audit log. thorntail.elytron.periodic-rotating-file-audit-logs._KEY_.suffix:: The suffix string in a format which can be understood by java.time.format.DateTimeFormatter. The period of the rotation is automatically calculated based on the suffix. thorntail.elytron.permission-sets._KEY_.permissions:: The permissions in the permission set. thorntail.elytron.policies._KEY_.custom-policy:: A custom policy provider definition. thorntail.elytron.policies._KEY_.jacc-policy:: A policy provider definition that sets up JACC and related services. thorntail.elytron.properties-realms._KEY_.attribute-synchronized:: The time the properties files that back this realm were last loaded. thorntail.elytron.properties-realms._KEY_.groups-attribute:: The name of the attribute in the returned AuthorizationIdentity that should contain the group membership information for the identity. thorntail.elytron.properties-realms._KEY_.groups-properties:: The properties file containing the users and their groups. thorntail.elytron.properties-realms._KEY_.users-properties:: The properties file containing the users and their passwords. thorntail.elytron.provider-http-server-mechanism-factories._KEY_.available-mechanisms:: The HTTP mechanisms available from this factory instance. thorntail.elytron.provider-http-server-mechanism-factories._KEY_.providers:: The providers to use to locate the factories, if not specified the globally registered list of Providers will be used. thorntail.elytron.provider-loaders._KEY_.argument:: An argument to be passed into the constructor as the Provider is instantiated. thorntail.elytron.provider-loaders._KEY_.class-names:: The fully qualified class names of the providers to load, these are loaded after the service-loader discovered providers and duplicates will be skipped. thorntail.elytron.provider-loaders._KEY_.configuration:: The key/value configuration to be passed to the Provider to initialise it. thorntail.elytron.provider-loaders._KEY_.loaded-providers:: The list of providers loaded by this provider loader. thorntail.elytron.provider-loaders._KEY_.module:: The name of the module to load the provider from. thorntail.elytron.provider-loaders._KEY_.path:: The path of the file to use to initialise the providers. thorntail.elytron.provider-loaders._KEY_.relative-to:: The base path of the configuration file. thorntail.elytron.provider-sasl-server-factories._KEY_.available-mechanisms:: The SASL mechanisms available from this factory after all filtering has been applied. thorntail.elytron.provider-sasl-server-factories._KEY_.providers:: The providers to use to locate the factories, if not specified the globally registered list of Providers will be used. thorntail.elytron.regex-principal-transformers._KEY_.pattern:: The regular expression to use to locate the portion of the name to be replaced. thorntail.elytron.regex-principal-transformers._KEY_.replace-all:: Should all occurrences of the pattern matched be replaced or only the first occurrence. thorntail.elytron.regex-principal-transformers._KEY_.replacement:: The value to be used as the replacement. thorntail.elytron.regex-validating-principal-transformers._KEY_.match:: If set to true, the name must match the given pattern to make validation successful. If set to false, the name must not match the given pattern to make validation successful. thorntail.elytron.regex-validating-principal-transformers._KEY_.pattern:: The regular expression to use for the principal transformer. thorntail.elytron.register-jaspi-factory:: Should the Elytron JASPI factory be globally registered? thorntail.elytron.sasl-authentication-factories._KEY_.available-mechanisms:: The SASL mechanisms available from this configuration after all filtering has been applied. thorntail.elytron.sasl-authentication-factories._KEY_.mechanism-configurations:: Mechanism specific configuration thorntail.elytron.sasl-authentication-factories._KEY_.sasl-server-factory:: The SaslServerFactory to associate with this resource thorntail.elytron.sasl-authentication-factories._KEY_.security-domain:: The SecurityDomain to associate with this resource thorntail.elytron.security-domains._KEY_.default-realm:: The default realm contained by this security domain. thorntail.elytron.security-domains._KEY_.outflow-anonymous:: When outflowing to a security domain if outflow is not possible should the anonymous identity be used? Outflowing anonymous has the effect of clearing any identity already established for that domain. thorntail.elytron.security-domains._KEY_.outflow-security-domains:: The list of security domains that the security identity from this domain should automatically outflow to. thorntail.elytron.security-domains._KEY_.permission-mapper:: A reference to a PermissionMapper to be used by this domain. thorntail.elytron.security-domains._KEY_.post-realm-principal-transformer:: A reference to a principal transformer to be applied after the realm has operated on the supplied identity name. thorntail.elytron.security-domains._KEY_.pre-realm-principal-transformer:: A reference to a principal transformer to be applied before the realm is selected. thorntail.elytron.security-domains._KEY_.principal-decoder:: A reference to a PrincipalDecoder to be used by this domain. thorntail.elytron.security-domains._KEY_.realm-mapper:: Reference to the RealmMapper to be used by this domain. thorntail.elytron.security-domains._KEY_.realms:: The list of realms contained by this security domain. thorntail.elytron.security-domains._KEY_.role-mapper:: Reference to the RoleMapper to be used by this domain. thorntail.elytron.security-domains._KEY_.security-event-listener:: Reference to a listener for security events. thorntail.elytron.security-domains._KEY_.trusted-security-domains:: The list of security domains that are trusted by this security domain. thorntail.elytron.security-properties:: Security properties to be set. thorntail.elytron.server-ssl-contexts._KEY_.active-session-count:: The count of current active sessions. thorntail.elytron.server-ssl-contexts._KEY_.authentication-optional:: Rejecting of the client certificate by the security domain will not prevent the connection. Allows a fall through to use other authentication mechanisms (like form login) when the client certificate is rejected by security domain. Has an effect only when the security domain is set. thorntail.elytron.server-ssl-contexts._KEY_.cipher-suite-filter:: The filter to apply to specify the enabled cipher suites. thorntail.elytron.server-ssl-contexts._KEY_.final-principal-transformer:: A final principal transformer to apply for this mechanism realm. thorntail.elytron.server-ssl-contexts._KEY_.key-manager:: Reference to the key manager to use within the SSLContext. thorntail.elytron.server-ssl-contexts._KEY_.maximum-session-cache-size:: The maximum number of SSL sessions in the cache. The default value -1 means use the JVM default value. Value zero means there is no limit. thorntail.elytron.server-ssl-contexts._KEY_.need-client-auth:: To require a client certificate on SSL handshake. Connection without trusted client certificate (see trust-manager) will be rejected. thorntail.elytron.server-ssl-contexts._KEY_.post-realm-principal-transformer:: A principal transformer to apply after the realm is selected. thorntail.elytron.server-ssl-contexts._KEY_.pre-realm-principal-transformer:: A principal transformer to apply before the realm is selected. thorntail.elytron.server-ssl-contexts._KEY_.protocols:: The enabled protocols. thorntail.elytron.server-ssl-contexts._KEY_.provider-name:: The name of the provider to use. If not specified, all providers from providers will be passed to the SSLContext. thorntail.elytron.server-ssl-contexts._KEY_.providers:: The name of the providers to obtain the Provider[] to use to load the SSLContext. thorntail.elytron.server-ssl-contexts._KEY_.realm-mapper:: The realm mapper to be used for SSL authentication. thorntail.elytron.server-ssl-contexts._KEY_.security-domain:: The security domain to use for authentication during SSL session establishment. thorntail.elytron.server-ssl-contexts._KEY_.session-timeout:: The timeout for SSL sessions, in seconds. The default value -1 means use the JVM default value. Value zero means there is no limit. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.application-buffer-size:: The application buffer size as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.cipher-suite:: The selected cipher suite as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.creation-time:: The creation time as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.last-accessed-time:: The last accessed time as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.local-certificates:: The local certificates from the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.local-principal:: The local principal as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.packet-buffer-size:: The packet buffer size as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.peer-certificates:: The peer certificates from the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.peer-host:: The peer host as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.peer-port:: The peer port as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.peer-principal:: The peer principal as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.protocol:: The protocol as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.ssl-sessions._KEY_.valid:: The validity of the session as reported by the SSLSession. thorntail.elytron.server-ssl-contexts._KEY_.trust-manager:: Reference to the trust manager to use within the SSLContext. thorntail.elytron.server-ssl-contexts._KEY_.use-cipher-suites-order:: To honor local cipher suites preference. thorntail.elytron.server-ssl-contexts._KEY_.want-client-auth:: To request (but not to require) a client certificate on SSL handshake. If a security domain is referenced and supports X509 evidence, this will be set to true automatically. Ignored when need-client-auth is set. thorntail.elytron.server-ssl-contexts._KEY_.wrap:: Should the SSLEngine, SSLSocket, and SSLServerSocket instances returned be wrapped to protect against further modification. thorntail.elytron.server-ssl-sni-contexts._KEY_.default-ssl-context:: The context to use if no SNI information is present, or if it does not match any mappings thorntail.elytron.server-ssl-sni-contexts._KEY_.host-context-map:: A mapping between a server name and an SSContext thorntail.elytron.service-loader-http-server-mechanism-factories._KEY_.available-mechanisms:: The HTTP mechanisms available from this factory instance. thorntail.elytron.service-loader-http-server-mechanism-factories._KEY_.module:: The module to use to obtain the classloader to load the factories, if not specified the classloader to load the resource will be used instead. thorntail.elytron.service-loader-sasl-server-factories._KEY_.available-mechanisms:: The SASL mechanisms available from this factory after all filtering has been applied. thorntail.elytron.service-loader-sasl-server-factories._KEY_.module:: The module to use to obtain the classloader to load the factories, if not specified the classloader to load the resource will be used instead. thorntail.elytron.simple-permission-mappers._KEY_.mapping-mode:: The mapping mode that should be used in the event of multiple matches. thorntail.elytron.simple-permission-mappers._KEY_.permission-mappings:: The defined permission mappings. thorntail.elytron.simple-regex-realm-mappers._KEY_.delegate-realm-mapper:: The RealmMapper to delegate to if there is no match using the pattern. thorntail.elytron.simple-regex-realm-mappers._KEY_.pattern:: The regular expression which must contain at least one capture group to extract the realm from the name. If the regular expression matches more than one capture group, the first capture group is used. thorntail.elytron.simple-role-decoders._KEY_.attribute:: The name of the attribute from the identity to map directly to roles. thorntail.elytron.size-rotating-file-audit-logs._KEY_.attribute-synchronized:: Whether every event should be immediately flushed to disk (If undefined will default to the value of synchronized). thorntail.elytron.size-rotating-file-audit-logs._KEY_.autoflush:: Whether every event should be immediately flushed to disk. thorntail.elytron.size-rotating-file-audit-logs._KEY_.format:: The format to use to record the audit event. thorntail.elytron.size-rotating-file-audit-logs._KEY_.max-backup-index:: The maximum number of files to backup when rotating. thorntail.elytron.size-rotating-file-audit-logs._KEY_.path:: Path of the file to be written. thorntail.elytron.size-rotating-file-audit-logs._KEY_.relative-to:: The relative path to the audit log. thorntail.elytron.size-rotating-file-audit-logs._KEY_.rotate-on-boot:: Whether the file should be rotated before the a new file is set. thorntail.elytron.size-rotating-file-audit-logs._KEY_.rotate-size:: The log file size the file should rotate at. thorntail.elytron.size-rotating-file-audit-logs._KEY_.suffix:: Format of date used as suffix of log file names in java.time.format.DateTimeFormatter. The suffix does not play a role in determining when the file should be rotated. thorntail.elytron.syslog-audit-logs._KEY_.format:: The format to use to record the audit event. thorntail.elytron.syslog-audit-logs._KEY_.host-name:: The host name to embed withing all events sent to the remote syslog server. thorntail.elytron.syslog-audit-logs._KEY_.port:: The listening port on the syslog server. thorntail.elytron.syslog-audit-logs._KEY_.server-address:: The server address of the syslog server the events should be sent to. thorntail.elytron.syslog-audit-logs._KEY_.ssl-context:: The SSLContext to use to connect to the syslog server when SSL_TCP transport is used. thorntail.elytron.syslog-audit-logs._KEY_.transport:: The transport to use to connect to the syslog server. thorntail.elytron.token-realms._KEY_.jwt:: A token validator to be used in conjunction with a token-based realm that handles security tokens based on the JWT/JWS standard. thorntail.elytron.token-realms._KEY_.oauth2-introspection:: A token validator to be used in conjunction with a token-based realm that handles OAuth2 Access Tokens and validates them using an endpoint compliant with OAuth2 Token Introspection specification(RFC-7662). thorntail.elytron.token-realms._KEY_.principal-claim:: The name of the claim that should be used to obtain the principal's name. thorntail.elytron.trust-managers._KEY_.algorithm:: The name of the algorithm to use to create the underlying TrustManagerFactory. thorntail.elytron.trust-managers._KEY_.alias-filter:: A filter to apply to the aliases returned from the KeyStore, can either be a comma separated list of aliases to return or one of the following formats ALL:-alias1:-alias2, NONE:+alias1:+alias2 thorntail.elytron.trust-managers._KEY_.certificate-revocation-list:: Enables certificate revocation list checks to a trust manager. thorntail.elytron.trust-managers._KEY_.key-store:: Reference to the KeyStore to use to initialise the underlying TrustManagerFactory. thorntail.elytron.trust-managers._KEY_.provider-name:: The name of the provider to use to create the underlying TrustManagerFactory. thorntail.elytron.trust-managers._KEY_.providers:: Reference to obtain the Provider[] to use when creating the underlying TrustManagerFactory. thorntail.elytron.x500-attribute-principal-decoders._KEY_.attribute-name:: The name of the X.500 attribute to map (can be defined using OID instead) thorntail.elytron.x500-attribute-principal-decoders._KEY_.convert:: When set to 'true', if the Principal is not already an X500Principal conversion will be attempted thorntail.elytron.x500-attribute-principal-decoders._KEY_.joiner:: The joining string thorntail.elytron.x500-attribute-principal-decoders._KEY_.maximum-segments:: The maximum number of occurrences of the attribute to map thorntail.elytron.x500-attribute-principal-decoders._KEY_.oid:: The OID of the X.500 attribute to map (can be defined using attribute name instead) thorntail.elytron.x500-attribute-principal-decoders._KEY_.required-attributes:: The attributes names of the attributes that must be present in the principal thorntail.elytron.x500-attribute-principal-decoders._KEY_.required-oids:: The OIDs of the attributes that must be present in the principal thorntail.elytron.x500-attribute-principal-decoders._KEY_.reverse:: When set to 'true', the attribute values will be processed and returned in reverse order thorntail.elytron.x500-attribute-principal-decoders._KEY_.start-segment:: The 0-based starting occurrence of the attribute to map ",12496,True,3136.682585105019,median " //// This file is generated! See _meta/fields.yml and scripts/generate_field_docs.py //// [[exported-fields]] = Exported fields [partintro] -- This document describes the fields that are exported by Winlogbeat. They are grouped in the following categories: * <> * <> * <> * <> * <> * <> * <> * <> -- [[exported-fields-beat]] == Beat fields Contains common beat fields available in all event types. *`beat.timezone`*:: + -- type: alias alias to: event.timezone -- *`fields`*:: + -- type: object Contains user configurable fields. -- [float] == error fields Error fields containing additional info in case of errors. *`error.type`*:: + -- type: keyword Error type. -- [[exported-fields-cloud]] == Cloud provider metadata fields Metadata from cloud providers added by the add_cloud_metadata processor. *`cloud.project.id`*:: + -- example: project-x Name of the project in Google Cloud. -- *`meta.cloud.provider`*:: + -- type: alias alias to: cloud.provider -- *`meta.cloud.instance_id`*:: + -- type: alias alias to: cloud.instance.id -- *`meta.cloud.instance_name`*:: + -- type: alias alias to: cloud.instance.name -- *`meta.cloud.machine_type`*:: + -- type: alias alias to: cloud.machine.type -- *`meta.cloud.availability_zone`*:: + -- type: alias alias to: cloud.availability_zone -- *`meta.cloud.project_id`*:: + -- type: alias alias to: cloud.project.id -- *`meta.cloud.region`*:: + -- type: alias alias to: cloud.region -- [[exported-fields-common]] == Common Winlogbeat fields Contains common fields available in all event types. *`type`*:: + -- required: True The event log API type used to read the record. The possible values are ""wineventlog"" for the Windows Event Log API or ""eventlogging"" for the Event Logging API. The Event Logging API was designed for Windows Server 2003 or Windows 2000 operating systems. In Windows Vista, the event logging infrastructure was redesigned. On Windows Vista or later operating systems, the Windows Event Log API is used. Winlogbeat automatically detects which API to use for reading event logs. -- [[exported-fields-docker-processor]] == Docker fields Docker stats collected from Docker. *`docker.container.id`*:: + -- type: keyword Unique container id. -- *`docker.container.image`*:: + -- type: keyword Name of the image the container was built on. -- *`docker.container.name`*:: + -- type: keyword Container name. -- *`docker.container.labels`*:: + -- type: object Image labels. -- [[exported-fields-ecs]] == ECS fields ECS fields. *`@timestamp`*:: + -- type: date example: 2016-05-23T08:05:34.853Z required: True Date/time when the event originated. For log events this is the date/time when the event was generated, and not when it was read. Required field for all events. -- *`tags`*:: + -- type: keyword example: [""production"", ""env2""] List of keywords used to tag each event. -- *`labels`*:: + -- type: object example: {'application': 'foo-bar', 'env': 'production'} Key/value pairs. Can be used to add meta information to events. Should not contain nested objects. All values are stored as keyword. Example: `docker` and `k8s` labels. -- *`message`*:: + -- type: text example: Hello World For log events the message field contains the log message. In other use cases the message field can be used to concatenate different values which are then freely searchable. If multiple messages exist, they can be combined into one message. -- [float] == agent fields The agent fields contain the data about the software entity, if any, that collects, detects, or observes events on a host, or takes measurements on a host. Examples include Beats. Agents may also run on observers. ECS agent.* fields shall be populated with details of the agent running on the host or observer where the event happened or the measurement was taken. *`agent.version`*:: + -- type: keyword example: 6.0.0-rc2 Version of the agent. -- *`agent.name`*:: + -- type: keyword example: foo Name of the agent. This is a name that can be given to an agent. This can be helpful if for example two Filebeat instances are running on the same host but a human readable separation is needed on which Filebeat instance data is coming from. If no name is given, the name is often left empty. -- *`agent.type`*:: + -- type: keyword example: filebeat Type of the agent. The agent type stays always the same and should be given by the agent used. In case of Filebeat the agent would always be Filebeat also if two Filebeat instances are run on the same machine. -- *`agent.id`*:: + -- type: keyword example: 8a4f500d Unique identifier of this agent (if one exists). Example: For Beats this would be beat.id. -- *`agent.ephemeral_id`*:: + -- type: keyword example: 8a4f500f Ephemeral identifier of this agent (if one exists). This id normally changes across restarts, but `agent.id` does not. -- [float] == client fields A client is defined as the initiator of a network connection for events regarding sessions, connections, or bidirectional flow records. For TCP events, the client is the initiator of the TCP connection that sends the SYN packet(s). For other protocols, the client is generally the initiator or requestor in the network transaction. Some systems use the term ""originator"" to refer the client in TCP connections. The client fields describe details about the system acting as the client in the network event. Client fields are usually populated in conjuction with server fields. Client fields are generally not populated for packet-level events. *`client.ip`*:: + -- type: ip IP address of the client. Can be one or multiple IPv4 or IPv6 addresses. -- *`client.port`*:: + -- type: long Port of the client. -- *`client.mac`*:: + -- type: keyword MAC address of the client. -- *`client.domain`*:: + -- type: keyword Client domain. -- *`client.bytes`*:: + -- type: long example: 184 Bytes sent from the client to the server. -- *`client.packets`*:: + -- type: long example: 12 Packets sent from the client to the server. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`client.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`client.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`client.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`client.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`client.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`client.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`client.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`client.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == cloud fields Fields related to the cloud or infrastructure the events are coming from. *`cloud.provider`*:: + -- type: keyword example: ec2 Name of the cloud provider. Example values are ec2, gce, or digitalocean. -- *`cloud.availability_zone`*:: + -- type: keyword example: us-east-1c Availability zone in which this host is running. -- *`cloud.region`*:: + -- type: keyword example: us-east-1 Region in which this host is running. -- *`cloud.instance.id`*:: + -- type: keyword example: i-1234567890abcdef0 Instance ID of the host machine. -- *`cloud.instance.name`*:: + -- type: keyword Instance name of the host machine. -- *`cloud.machine.type`*:: + -- type: keyword example: t2.medium Machine type of the host machine. -- *`cloud.account.id`*:: + -- type: keyword example: 666777888999 The cloud account or organization id used to identify different entities in a multi-tenant environment. Examples: AWS account id, Google Cloud ORG Id, or other unique identifier. -- [float] == container fields Container fields are used for meta information about the specific container that is the source of information. These fields help correlate data based containers from any runtime. *`container.runtime`*:: + -- type: keyword example: docker Runtime managing this container. -- *`container.id`*:: + -- type: keyword Unique container id. -- *`container.image.name`*:: + -- type: keyword Name of the image the container was built on. -- *`container.image.tag`*:: + -- type: keyword Container image tag. -- *`container.name`*:: + -- type: keyword Container name. -- *`container.labels`*:: + -- type: object Image labels. -- [float] == destination fields Destination fields describe details about the destination of a packet/event. Destination fields are usually populated in conjunction with source fields. *`destination.ip`*:: + -- type: ip IP address of the destination. Can be one or multiple IPv4 or IPv6 addresses. -- *`destination.port`*:: + -- type: long Port of the destination. -- *`destination.mac`*:: + -- type: keyword MAC address of the destination. -- *`destination.domain`*:: + -- type: keyword Destination domain. -- *`destination.bytes`*:: + -- type: long example: 184 Bytes sent from the destination to the source. -- *`destination.packets`*:: + -- type: long example: 12 Packets sent from the destination to the source. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`destination.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`destination.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`destination.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`destination.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`destination.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`destination.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`destination.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`destination.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == ecs fields Meta-information specific to ECS. *`ecs.version`*:: + -- type: keyword example: 1.0.0-beta1 required: True ECS version this event conforms to. `ecs.version` is a required field and must exist in all events. When querying across multiple indices -- which may conform to slightly different ECS versions -- this field lets integrations adjust to the schema version of the events. The current version is 1.0.0-beta1 . -- [float] == error fields These fields can represent errors of any kind. Use them for errors that happen while fetching events or in cases where the event itself contains an error. *`error.id`*:: + -- type: keyword Unique identifier for the error. -- *`error.message`*:: + -- type: text Error message. -- *`error.code`*:: + -- type: keyword Error code describing the error. -- [float] == event fields The event fields are used for context information about the log or metric event itself. A log is defined as an event containing details of something that happened. Log events must include the time at which the thing happened. Examples of log events include a process starting on a host, a network packet being sent from a source to a destination, or a network connection between a client and a server being initiated or closed. A metric is defined as an event containing one or more numerical or categorical measurements and the time at which the measurement was taken. Examples of metric events include memory pressure measured on a host, or vulnerabilities measured on a scanned host. *`event.id`*:: + -- type: keyword example: 8a4f500d Unique ID to describe the event. -- *`event.kind`*:: + -- type: keyword example: state The kind of the event. This gives information about what type of information the event contains, without being specific to the contents of the event. Examples are `event`, `state`, `alarm`. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.category`*:: + -- type: keyword example: user-management Event category. This contains high-level information about the contents of the event. It is more generic than `event.action`, in the sense that typically a category contains multiple actions. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.action`*:: + -- type: keyword example: user-password-change The action captured by the event. This describes the information in the event. It is more specific than `event.category`. Examples are `group-add`, `process-started`, `file-created`. The value is normally defined by the implementer. -- *`event.outcome`*:: + -- type: keyword example: success The outcome of the event. If the event describes an action, this fields contains the outcome of that action. Examples outcomes are `success` and `failure`. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.type`*:: + -- type: keyword Reserved for future usage. Please avoid using this field for user data. -- *`event.module`*:: + -- type: keyword example: mysql Name of the module this data is coming from. This information is coming from the modules used in Beats or Logstash. -- *`event.dataset`*:: + -- type: keyword example: stats Name of the dataset. The concept of a `dataset` (fileset / metricset) is used in Beats as a subset of modules. It contains the information which is currently stored in metricset.name and metricset.module or fileset.name. -- *`event.severity`*:: + -- type: long example: 7 Severity describes the severity of the event. What the different severity values mean can very different between use cases. It's up to the implementer to make sure severities are consistent across events. -- *`event.original`*:: + -- type: keyword example: Sep 19 08:26:10 host CEF:0|Security| threatmanager|1.0|100| worm successfully stopped|10|src=10.0.0.1 dst=2.1.2.2spt=1232 Raw text message of entire event. Used to demonstrate log integrity. This field is not indexed and doc_values are disabled. It cannot be searched, but it can be retrieved from `_source`. Field is not indexed. -- *`event.hash`*:: + -- type: keyword example: 123456789012345678901234567890ABCD Hash (perhaps logstash fingerprint) of raw field to be able to demonstrate log integrity. -- *`event.duration`*:: + -- type: long Duration of the event in nanoseconds. If event.start and event.end are known this value should be the difference between the end and start time. -- *`event.timezone`*:: + -- type: keyword This field should be populated when the event's timestamp does not include timezone information already (e.g. default Syslog timestamps). It's optional otherwise. Acceptable timezone formats are: a canonical ID (e.g. ""Europe/Amsterdam""), abbreviated (e.g. ""EST"") or an HH:mm differential (e.g. ""-05:00""). -- *`event.created`*:: + -- type: date event.created contains the date when the event was created. This timestamp is distinct from @timestamp in that @timestamp contains the processed timestamp. For logs these two timestamps can be different as the timestamp in the log line and when the event is read for example by Filebeat are not identical. `@timestamp` must contain the timestamp extracted from the log line, event.created when the log line is read. The same could apply to package capturing where @timestamp contains the timestamp extracted from the network package and event.created when the event was created. In case the two timestamps are identical, @timestamp should be used. -- *`event.start`*:: + -- type: date event.start contains the date when the event started or when the activity was first observed. -- *`event.end`*:: + -- type: date event.end contains the date when the event ended or when the activity was last observed. -- *`event.risk_score`*:: + -- type: float Risk score or priority of the event (e.g. security solutions). Use your system's original value here. -- *`event.risk_score_norm`*:: + -- type: float Normalized risk score or priority of the event, on a scale of 0 to 100. This is mainly useful if you use more than one system that assigns risk scores, and you want to see a normalized value across all systems. -- [float] == file fields A file is defined as a set of information that has been created on, or has existed on a filesystem. File objects can be associated with host events, network events, and/or file events (e.g., those produced by File Integrity Monitoring [FIM] products or services). File fields provide details about the affected file associated with the event or metric. *`file.path`*:: + -- type: keyword Path to the file. -- *`file.target_path`*:: + -- type: keyword Target path for symlinks. -- *`file.extension`*:: + -- type: keyword example: png File extension. This should allow easy filtering by file extensions. -- *`file.type`*:: + -- type: keyword File type (file, dir, or symlink). -- *`file.device`*:: + -- type: keyword Device that is the source of the file. -- *`file.inode`*:: + -- type: keyword Inode representing the file in the filesystem. -- *`file.uid`*:: + -- type: keyword The user ID (UID) or security identifier (SID) of the file owner. -- *`file.owner`*:: + -- type: keyword File owner's username. -- *`file.gid`*:: + -- type: keyword Primary group ID (GID) of the file. -- *`file.group`*:: + -- type: keyword Primary group name of the file. -- *`file.mode`*:: + -- type: keyword example: 416 Mode of the file in octal representation. -- *`file.size`*:: + -- type: long File size in bytes (field is only added when `type` is `file`). -- *`file.mtime`*:: + -- type: date Last time file content was modified. -- *`file.ctime`*:: + -- type: date Last time file metadata changed. -- [float] == group fields The group fields are meant to represent groups that are relevant to the event. *`group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`group.name`*:: + -- type: keyword Name of the group. -- [float] == host fields A host is defined as a general computing instance. ECS host.* fields should be populated with details about the host on which the event happened, or on which the measurement was taken. Host types include hardware, virtual machines, Docker containers, and Kubernetes nodes. *`host.hostname`*:: + -- type: keyword Hostname of the host. It normally contains what the `hostname` command returns on the host machine. -- *`host.name`*:: + -- type: keyword Name of the host. It can contain what `hostname` returns on Unix systems, the fully qualified domain name, or a name specified by the user. The sender decides which value to use. -- *`host.id`*:: + -- type: keyword Unique host id. As hostname is not always unique, use values that are meaningful in your environment. Example: The current usage of `beat.name`. -- *`host.ip`*:: + -- type: ip Host ip address. -- *`host.mac`*:: + -- type: keyword Host mac address. -- *`host.type`*:: + -- type: keyword Type of host. For Cloud providers this can be the machine type like `t2.medium`. If vm, this could be the container, for example, or other information meaningful in your environment. -- *`host.architecture`*:: + -- type: keyword example: x86_64 Operating system architecture. -- [float] == os fields The OS fields contain information about the operating system. *`host.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`host.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`host.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`host.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`host.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`host.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`host.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`host.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`host.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`host.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`host.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`host.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`host.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == http fields Fields related to HTTP activity. *`http.request.method`*:: + -- type: keyword example: GET, POST, PUT Http request method. -- *`http.request.referrer`*:: + -- type: keyword example: https://blog.example.com/ Referrer for this HTTP request. -- *`http.response.status_code`*:: + -- type: long example: 404 Http response status code. -- *`http.response.body`*:: + -- type: keyword example: Hello world The full http response body. -- *`http.version`*:: + -- type: keyword example: 1.1 Http version. -- [float] == log fields Fields which are specific to log events. *`log.level`*:: + -- type: keyword example: ERR Log level of the log event. Some examples are `WARN`, `ERR`, `INFO`. -- *`log.original`*:: + -- type: keyword example: Sep 19 08:26:10 localhost My log This is the original log message and contains the full log message before splitting it up in multiple parts. In contrast to the `message` field which can contain an extracted part of the log message, this field contains the original, full log message. It can have already some modifications applied like encoding or new lines removed to clean up the log message. This field is not indexed and doc_values are disabled so it can't be queried but the value can be retrieved from `_source`. Field is not indexed. -- [float] == network fields The network is defined as the communication path over which a host or network event happens. The network.* fields should be populated with details about the network activity associated with an event. *`network.name`*:: + -- type: keyword example: Guest Wifi Name given by operators to sections of their network. -- *`network.type`*:: + -- type: keyword example: IPv4 In the OSI Model this would be the Network Layer. IPv4, IPv6, IPSec, PIM, etc -- *`network.iana_number`*:: + -- type: keyword example: 6 IANA Protocol Number (https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml). Standardized list of protocols. This aligns well with NetFlow and sFlow related logs which use the IANA Protocol Number. -- *`network.transport`*:: + -- type: keyword example: TCP Same as network.iana_number, but instead using the Keyword name of the transport layer (UDP, TCP, IPv6-ICMP, etc.) -- *`network.application`*:: + -- type: keyword example: AIM A name given to an application. This can be arbitrarily assigned for things like microservices, but also apply to things like skype, icq, facebook, twitter. This would be used in situations where the vendor or service can be decoded such as from the source/dest IP owners, ports, or wire format. -- *`network.protocol`*:: + -- type: keyword example: http L7 Network protocol name. ex. http, lumberjack, transport protocol -- *`network.direction`*:: + -- type: keyword example: inbound Direction of the network traffic. Recommended values are: * inbound * outbound * internal * external * unknown When mapping events from a host-based monitoring context, populate this field from the host's point of view. When mapping events from a network or perimeter-based monitoring context, populate this field from the point of view of your network perimeter. -- *`network.forwarded_ip`*:: + -- type: ip example: 192.1.1.2 Host IP address when the source IP address is the proxy. -- *`network.community_id`*:: + -- type: keyword example: 1:hO+sN4H+MG5MY/8hIrXPqc4ZQz0= A hash of source and destination IPs and ports, as well as the protocol used in a communication. This is a tool-agnostic standard to identify flows. Learn more at https://github.com/corelight/community-id-spec. -- *`network.bytes`*:: + -- type: long example: 368 Total bytes transferred in both directions. If `source.bytes` and `destination.bytes` are known, `network.bytes` is their sum. -- *`network.packets`*:: + -- type: long example: 24 Total packets transferred in both directions. If `source.packets` and `destination.packets` are known, `network.packets` is their sum. -- [float] == observer fields An observer is defined as a special network, security, or application device used to detect, observe, or create network, security, or application-related events and metrics. This could be a custom hardware appliance or a server that has been configured to run special network, security, or application software. Examples include firewalls, intrusion detection/prevention systems, network monitoring sensors, web application firewalls, data loss prevention systems, and APM servers. The observer.* fields shall be populated with details of the system, if any, that detects, observes and/or creates a network, security, or application event or metric. Message queues and ETL components used in processing events or metrics are not considered observers in ECS. *`observer.mac`*:: + -- type: keyword MAC address of the observer -- *`observer.ip`*:: + -- type: ip IP address of the observer. -- *`observer.hostname`*:: + -- type: keyword Hostname of the observer. -- *`observer.vendor`*:: + -- type: keyword observer vendor information. -- *`observer.version`*:: + -- type: keyword Observer version. -- *`observer.serial_number`*:: + -- type: keyword Observer serial number. -- *`observer.type`*:: + -- type: keyword example: firewall The type of the observer the data is coming from. There is no predefined list of observer types. Some examples are `forwarder`, `firewall`, `ids`, `ips`, `proxy`, `poller`, `sensor`, `APM server`. -- [float] == os fields The OS fields contain information about the operating system. *`observer.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`observer.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`observer.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`observer.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`observer.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`observer.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`observer.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`observer.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`observer.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`observer.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`observer.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`observer.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`observer.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == organization fields The organization fields enrich data with information about the company or entity the data is associated with. These fields help you arrange or filter data stored in an index by one or multiple organizations. *`organization.name`*:: + -- type: keyword Organization name. -- *`organization.id`*:: + -- type: keyword Unique identifier for the organization. -- [float] == os fields The OS fields contain information about the operating system. *`os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == process fields These fields contain information about a process. These fields can help you correlate metrics information with a process id/name from a log message. The `process.pid` often stays in the metric itself and is copied to the global field for correlation. *`process.pid`*:: + -- type: long Process id. -- *`process.name`*:: + -- type: keyword example: ssh Process name. Sometimes called program name or similar. -- *`process.ppid`*:: + -- type: long Process parent id. -- *`process.args`*:: + -- type: keyword example: ['ssh', '-l', 'user', '10.0.0.16'] Process arguments. May be filtered to protect sensitive information. -- *`process.executable`*:: + -- type: keyword example: /usr/bin/ssh Absolute path to the process executable. -- *`process.title`*:: + -- type: keyword Process title. The proctitle, some times the same as process name. Can also be different: for example a browser setting its title to the web page currently opened. -- *`process.thread.id`*:: + -- type: long example: 4242 Thread ID. -- *`process.start`*:: + -- type: date example: 2016-05-23T08:05:34.853Z The time the process started. -- *`process.working_directory`*:: + -- type: keyword example: /home/alice The working directory of the process. -- [float] == related fields This field set is meant to facilitate pivoting around a piece of data. Some pieces of information can be seen in many places in ECS. To facilitate searching for them, append values to their corresponding field in `related.`. A concrete example is IP addresses, which can be under host, observer, source, destination, client, server, and network.forwarded_ip. If you append all IPs to `related.ip`, you can then search for a given IP trivially, no matter where it appeared, by querying `related.ip:a.b.c.d`. *`related.ip`*:: + -- type: ip All of the IPs seen on your event. -- [float] == server fields A Server is defined as the responder in a network connection for events regarding sessions, connections, or bidirectional flow records. For TCP events, the server is the receiver of the initial SYN packet(s) of the TCP connection. For other protocols, the server is generally the responder in the network transaction. Some systems actually use the term ""responder"" to refer the server in TCP connections. The server fields describe details about the system acting as the server in the network event. Server fields are usually populated in conjunction with client fields. Server fields are generally not populated for packet-level events. *`server.ip`*:: + -- type: ip IP address of the server. Can be one or multiple IPv4 or IPv6 addresses. -- *`server.port`*:: + -- type: long Port of the server. -- *`server.mac`*:: + -- type: keyword MAC address of the server. -- *`server.domain`*:: + -- type: keyword Server domain. -- *`server.bytes`*:: + -- type: long example: 184 Bytes sent from the server to the client. -- *`server.packets`*:: + -- type: long example: 12 Packets sent from the server to the client. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`server.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`server.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`server.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`server.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`server.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`server.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`server.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`server.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == service fields The service fields describe the service for or from which the data was collected. These fields help you find and correlate logs for a specific service and version. *`service.id`*:: + -- type: keyword example: d37e5ebfe0ae6c4972dbe9f0174a1637bb8247f6 Unique identifier of the running service. This id should uniquely identify this service. This makes it possible to correlate logs and metrics for one specific service. Example: If you are experiencing issues with one redis instance, you can filter on that id to see metrics and logs for that single instance. -- *`service.name`*:: + -- type: keyword example: elasticsearch-metrics Name of the service data is collected from. The name of the service is normally user given. This allows if two instances of the same service are running on the same machine they can be differentiated by the `service.name`. Also it allows for distributed services that run on multiple hosts to correlate the related instances based on the name. In the case of Elasticsearch the service.name could contain the cluster name. For Beats the service.name is by default a copy of the `service.type` field if no name is specified. -- *`service.type`*:: + -- type: keyword example: elasticsearch The type of the service data is collected from. The type can be used to group and correlate logs and metrics from one service type. Example: If logs or metrics are collected from Elasticsearch, `service.type` would be `elasticsearch`. -- *`service.state`*:: + -- type: keyword Current state of the service. -- *`service.version`*:: + -- type: keyword example: 3.2.4 Version of the service the data was collected from. This allows to look at a data set only for a specific version of a service. -- *`service.ephemeral_id`*:: + -- type: keyword example: 8a4f500f Ephemeral identifier of this service (if one exists). This id normally changes across restarts, but `service.id` does not. -- [float] == source fields Source fields describe details about the source of a packet/event. Source fields are usually populated in conjunction with destination fields. *`source.address`*:: + -- type: keyword Some event source addresses are defined ambiguously. The event will sometimes list an IP, a domain or a unix socket. You should always store the raw address in the `.address` field. Then it should be duplicated to `.ip` or `.domain`, depending on which one it is. -- *`source.ip`*:: + -- type: ip IP address of the source. Can be one or multiple IPv4 or IPv6 addresses. -- *`source.port`*:: + -- type: long Port of the source. -- *`source.mac`*:: + -- type: keyword MAC address of the source. -- *`source.domain`*:: + -- type: keyword Source domain. -- *`source.bytes`*:: + -- type: long example: 184 Bytes sent from the source to the destination. -- *`source.packets`*:: + -- type: long example: 12 Packets sent from the source to the destination. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`source.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`source.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`source.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`source.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`source.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`source.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`source.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`source.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == url fields URL fields provide a complete URL, with scheme, host, and path. *`url.original`*:: + -- type: keyword example: https://www.elastic.co:443/search?q=elasticsearch#top or /search?q=elasticsearch Unmodified original url as seen in the event source. Note that in network monitoring, the observed URL may be a full URL, whereas in access logs, the URL is often just represented as a path. This field is meant to represent the URL as it was observed, complete or not. -- *`url.full`*:: + -- type: keyword example: https://www.elastic.co:443/search?q=elasticsearch#top If full URLs are important to your use case, they should be stored in `url.full`, whether this field is reconstructed or present in the event source. -- *`url.scheme`*:: + -- type: keyword example: https Scheme of the request, such as ""https"". Note: The `:` is not part of the scheme. -- *`url.domain`*:: + -- type: keyword example: www.elastic.co Domain of the request, such as ""www.elastic.co"". In some cases a URL may refer to an IP and/or port directly, without a domain name. In this case, the IP address would go to the `domain` field. -- *`url.port`*:: + -- type: integer example: 443 Port of the request, such as 443. -- *`url.path`*:: + -- type: keyword Path of the request, such as ""/search"". -- *`url.query`*:: + -- type: keyword The query field describes the query string of the request, such as ""q=elasticsearch"". The `?` is excluded from the query string. If a URL contains no `?`, there is no query field. If there is a `?` but no query, the query field exists with an empty string. The `exists` query can be used to differentiate between the two cases. -- *`url.fragment`*:: + -- type: keyword Portion of the url after the `#`, such as ""top"". The `#` is not part of the fragment. -- *`url.username`*:: + -- type: keyword Username of the request. -- *`url.password`*:: + -- type: keyword Password of the request. -- [float] == user fields The user fields describe information about the user that is relevant to the event. Fields can have one entry or multiple entries. If a user has more than one id, provide an array that includes all of them. *`user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- *`user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`user.email`*:: + -- type: keyword User email address. -- *`user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`user.group`*:: + -- type: keyword Group the user is a part of. This field can contain a list of groups, if necessary. -- [float] == user_agent fields The user_agent fields normally come from a browser request. They often show up in web service logs coming from the parsed user agent string. *`user_agent.original`*:: + -- type: keyword example: Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1 Unparsed version of the user_agent. Field is not indexed. -- *`user_agent.name`*:: + -- type: keyword example: Safari Name of the user agent. -- *`user_agent.version`*:: + -- type: keyword example: 12.0 Version of the user agent. -- *`user_agent.device.name`*:: + -- type: keyword example: iPhone Name of the device. -- [float] == os fields The OS fields contain information about the operating system. *`user_agent.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`user_agent.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`user_agent.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`user_agent.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`user_agent.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- *`beat.name`*:: + -- type: alias alias to: agent.type -- *`beat.hostname`*:: + -- type: alias alias to: agent.hostname -- *`agent.hostname`*:: + -- type: keyword Hostname of the agent. -- *`user_agent.patch`*:: + -- type: keyword Patch version of the user agent. -- *`user_agent.minor`*:: + -- type: keyword Minor version of the user agent. -- *`user_agent.major`*:: + -- type: keyword Major version of the user agent. -- *`user_agent.device`*:: + -- type: keyword Name of the physical device. -- *`user_agent.os.major`*:: + -- type: long Major version of the operating system. -- *`user_agent.os.minor`*:: + -- type: long Minor version of the operating system. -- *`url.hostname`*:: + -- type: keyword Hostname of the request, such as ""elastic.co"". -- [[exported-fields-eventlog]] == Event log record fields Contains data from a Windows event log record. *`activity_id`*:: + -- type: keyword required: False A globally unique identifier that identifies the current activity. The events that are published with this identifier are part of the same activity. -- *`computer_name`*:: + -- type: keyword required: True The name of the computer that generated the record. When using Windows event forwarding, this name can differ from the `beat.hostname`. -- *`event_data`*:: + -- type: object required: False The event-specific data. This field is mutually exclusive with `user_data`. If you are capturing event data on versions prior to Windows Vista, the parameters in `event_data` are named `param1`, `param2`, and so on, because event log parameters are unnamed in earlier versions of Windows. -- *`event_id`*:: + -- type: long required: True The event identifier. The value is specific to the source of the event. -- *`keywords`*:: + -- type: keyword required: False The keywords are used to classify an event. -- *`log_name`*:: + -- type: keyword required: True The name of the event log from which this record was read. This value is one of the names from the `event_logs` collection in the configuration. -- *`level`*:: + -- type: keyword required: False The level of the event. There are five levels of events that can be logged: Success, Information, Warning, Error, Audit Success, and Audit Failure. -- *`message_error`*:: + -- type: keyword required: False The error that occurred while reading and formatting the message from the log. -- *`record_number`*:: + -- type: keyword required: True The record number of the event log record. The first record written to an event log is record number 1, and other records are numbered sequentially. If the record number reaches the maximum value (2^32^ for the Event Logging API and 2^64^ for the Windows Event Log API), the next record number will be 0. -- *`related_activity_id`*:: + -- type: keyword required: False A globally unique identifier that identifies the activity to which control was transferred to. The related events would then have this identifier as their `activity_id` identifier. -- *`opcode`*:: + -- type: keyword required: False The opcode defined in the event. Task and opcode are typically used to identify the location in the application from where the event was logged. -- *`provider_guid`*:: + -- type: keyword required: False A globally unique identifier that identifies the provider that logged the event. -- *`process_id`*:: + -- type: long required: False The process_id identifies the process that generated the event. -- *`source_name`*:: + -- type: keyword required: True The source of the event log record (the application or service that logged the record). -- *`task`*:: + -- type: keyword required: False The task defined in the event. Task and opcode are typically used to identify the location in the application from where the event was logged. The category used by the Event Logging API (on pre Windows Vista operating systems) is written to this field. -- *`thread_id`*:: + -- type: long required: False The thread_id identifies the thread that generated the event. -- *`user_data`*:: + -- type: object required: False The event specific data. This field is mutually exclusive with `event_data`. -- *`user.identifier`*:: + -- type: keyword example: S-1-5-21-3541430928-2051711210-1391384369-1001 required: False The Windows security identifier (SID) of the account associated with this event. If Winlogbeat cannot resolve the SID to a name, then the `user.name`, `user.domain`, and `user.type` fields will be omitted from the event. If you discover Winlogbeat not resolving SIDs, review the log for clues as to what the problem may be. -- *`user.domain`*:: + -- type: keyword required: False The domain that the account associated with this event is a member of. -- *`user.type`*:: + -- type: keyword required: False The type of account associated with this event. -- *`version`*:: + -- type: long required: False The version number of the event's definition. -- *`xml`*:: + -- type: text required: False The raw XML representation of the event obtained from Windows. This field is only available on operating systems supporting the Windows Event Log API (Microsoft Windows Vista and newer). This field is not included by default and must be enabled by setting `include_xml: true` as a configuration option for an individual event log. The XML representation of the event is useful for troubleshooting purposes. The data in the fields reported by Winlogbeat can be compared to the data in the XML to diagnose problems. -- [[exported-fields-host-processor]] == Host fields Info collected for the host machine. [[exported-fields-kubernetes-processor]] == Kubernetes fields Kubernetes metadata added by the kubernetes processor *`kubernetes.pod.name`*:: + -- type: keyword Kubernetes pod name -- *`kubernetes.pod.uid`*:: + -- type: keyword Kubernetes Pod UID -- *`kubernetes.namespace`*:: + -- type: keyword Kubernetes namespace -- *`kubernetes.node.name`*:: + -- type: keyword Kubernetes node name -- *`kubernetes.labels`*:: + -- type: object Kubernetes labels map -- *`kubernetes.annotations`*:: + -- type: object Kubernetes annotations map -- *`kubernetes.container.name`*:: + -- type: keyword Kubernetes container name -- *`kubernetes.container.image`*:: + -- type: keyword Kubernetes container image -- ",12385,True,2980.762575667273,median "// (c) Copyright 1995-2022 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE ""AS IS"" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, ""Critical // Applications""). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. #include ""video_cp_auto_cc_11_sc.h"" #include ""video_cp_auto_cc_11.h"" #include ""axi_clock_converter.h"" #include #include #ifdef XILINX_SIMULATOR video_cp_auto_cc_11::video_cp_auto_cc_11(const sc_core::sc_module_name& nm) : video_cp_auto_cc_11_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // initialize socket stubs } void video_cp_auto_cc_11::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""S_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'S_AXI' transactor parameters xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); // S_AXI' transactor ports mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // S_AXI' transactor sockets mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""M_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'M_AXI' transactor parameters xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); // M_AXI' transactor ports mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // M_AXI' transactor sockets mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { } } #endif // XILINX_SIMULATOR #ifdef XM_SYSTEMC video_cp_auto_cc_11::video_cp_auto_cc_11(const sc_core::sc_module_name& nm) : video_cp_auto_cc_11_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // initialize socket stubs } void video_cp_auto_cc_11::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""S_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'S_AXI' transactor parameters xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); // S_AXI' transactor ports mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // S_AXI' transactor sockets mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""M_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'M_AXI' transactor parameters xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); // M_AXI' transactor ports mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // M_AXI' transactor sockets mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { } } #endif // XM_SYSTEMC #ifdef RIVIERA video_cp_auto_cc_11::video_cp_auto_cc_11(const sc_core::sc_module_name& nm) : video_cp_auto_cc_11_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // initialize socket stubs } void video_cp_auto_cc_11::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""S_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'S_AXI' transactor parameters xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); // S_AXI' transactor ports mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // S_AXI' transactor sockets mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""M_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'M_AXI' transactor parameters xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); // M_AXI' transactor ports mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // M_AXI' transactor sockets mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { } } #endif // RIVIERA #ifdef VCSSYSTEMC video_cp_auto_cc_11::video_cp_auto_cc_11(const sc_core::sc_module_name& nm) : video_cp_auto_cc_11_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // Instantiate Socket Stubs // configure S_AXI_transactor xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // configure M_AXI_transactor xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // initialize transactors stubs S_AXI_transactor_target_wr_socket_stub = nullptr; S_AXI_transactor_target_rd_socket_stub = nullptr; M_AXI_transactor_initiator_wr_socket_stub = nullptr; M_AXI_transactor_initiator_rd_socket_stub = nullptr; } void video_cp_auto_cc_11::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""S_AXI_TLM_MODE"") != 1) { mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { S_AXI_transactor_target_wr_socket_stub = new xtlm::xtlm_aximm_target_stub(""wr_socket"",0); S_AXI_transactor_target_wr_socket_stub->bind(*(mp_S_AXI_transactor->wr_socket)); S_AXI_transactor_target_rd_socket_stub = new xtlm::xtlm_aximm_target_stub(""rd_socket"",0); S_AXI_transactor_target_rd_socket_stub->bind(*(mp_S_AXI_transactor->rd_socket)); mp_S_AXI_transactor->disable_transactor(); } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""M_AXI_TLM_MODE"") != 1) { mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { M_AXI_transactor_initiator_wr_socket_stub = new xtlm::xtlm_aximm_initiator_stub(""wr_socket"",0); M_AXI_transactor_initiator_wr_socket_stub->bind(*(mp_M_AXI_transactor->wr_socket)); M_AXI_transactor_initiator_rd_socket_stub = new xtlm::xtlm_aximm_initiator_stub(""rd_socket"",0); M_AXI_transactor_initiator_rd_socket_stub->bind(*(mp_M_AXI_transactor->rd_socket)); mp_M_AXI_transactor->disable_transactor(); } } #endif // VCSSYSTEMC #ifdef MTI_SYSTEMC video_cp_auto_cc_11::video_cp_auto_cc_11(const sc_core::sc_module_name& nm) : video_cp_auto_cc_11_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // Instantiate Socket Stubs // configure S_AXI_transactor xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // configure M_AXI_transactor xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""2""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // initialize transactors stubs S_AXI_transactor_target_wr_socket_stub = nullptr; S_AXI_transactor_target_rd_socket_stub = nullptr; M_AXI_transactor_initiator_wr_socket_stub = nullptr; M_AXI_transactor_initiator_rd_socket_stub = nullptr; } void video_cp_auto_cc_11::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""S_AXI_TLM_MODE"") != 1) { mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { S_AXI_transactor_target_wr_socket_stub = new xtlm::xtlm_aximm_target_stub(""wr_socket"",0); S_AXI_transactor_target_wr_socket_stub->bind(*(mp_S_AXI_transactor->wr_socket)); S_AXI_transactor_target_rd_socket_stub = new xtlm::xtlm_aximm_target_stub(""rd_socket"",0); S_AXI_transactor_target_rd_socket_stub->bind(*(mp_S_AXI_transactor->rd_socket)); mp_S_AXI_transactor->disable_transactor(); } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_11"", ""M_AXI_TLM_MODE"") != 1) { mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { M_AXI_transactor_initiator_wr_socket_stub = new xtlm::xtlm_aximm_initiator_stub(""wr_socket"",0); M_AXI_transactor_initiator_wr_socket_stub->bind(*(mp_M_AXI_transactor->wr_socket)); M_AXI_transactor_initiator_rd_socket_stub = new xtlm::xtlm_aximm_initiator_stub(""rd_socket"",0); M_AXI_transactor_initiator_rd_socket_stub->bind(*(mp_M_AXI_transactor->rd_socket)); mp_M_AXI_transactor->disable_transactor(); } } #endif // MTI_SYSTEMC video_cp_auto_cc_11::~video_cp_auto_cc_11() { delete mp_S_AXI_transactor; delete mp_M_AXI_transactor; } #ifdef MTI_SYSTEMC SC_MODULE_EXPORT(video_cp_auto_cc_11); #endif #ifdef XM_SYSTEMC XMSC_MODULE_EXPORT(video_cp_auto_cc_11); #endif #ifdef RIVIERA SC_MODULE_EXPORT(video_cp_auto_cc_11); #endif ",16332,True,4802.785959797224,median "// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. [[native_software]] = Building native software [CAUTION] ==== The https://blog.gradle.org/state-and-future-of-the-gradle-software-model[software model] is being retired and the plugins mentioned in this chapter will eventually be deprecated and removed. We recommend new projects looking to build C++ applications and libraries use the newer <>. ==== The native software plugins add support for building native software components, such as executables or shared libraries, from code written in C++, C and other languages. While many excellent build tools exist for this space of software development, Gradle offers developers its trademark power and flexibility together with dependency management practices more traditionally found in the JVM development space. The native software plugins make use of the Gradle software model. [[sec:native_features]] == Features The native software plugins provide: * Support for building native libraries and applications on Windows, Linux, macOS and other platforms. * Support for several source languages. * Support for building different variants of the same software, for different architectures, operating systems, or for any purpose. * Incremental parallel compilation, precompiled headers. * Dependency management between native software components. * Unit test execution. * Generate Visual studio solution and project files. * Deep integration with various tool chain, including discovery of installed tool chains. [[sec:supported_languages]] == Supported languages The following source languages are currently supported: * C * C++ * Objective-C * Objective-C++ * Assembly * Windows resources [[native-binaries:tool-chain-support]] == Tool chain support Gradle offers the ability to execute the same build using different tool chains. When you build a native binary, Gradle will attempt to locate a tool chain installed on your machine that can build the binary. You can fine tune exactly how this works, see <<#native_binaries:tool_chain,Tool chain support>> for details. The following tool chains are supported: [%header%autowidth,compact] |=== | Operating System | Tool Chain | Notes | Linux | http://gcc.gnu.org/[GCC] | | Linux | http://clang.llvm.org[Clang] | | macOS | XCode | Uses the Clang tool chain bundled with XCode. | Windows | https://visualstudio.microsoft.com/[Visual C++] | Windows XP and later, Visual C++ 2010/2012/2013/2015/2017/2019. | Windows | http://gcc.gnu.org/[GCC] with http://cygwin.com[Cygwin 32 and Cygwin 64] | Windows XP and later. | Windows | http://gcc.gnu.org/[GCC] with http://www.mingw.org/[MinGW] and https://mingw-w64.org/doku.php[MinGW64] | Windows XP and later. |=== The following tool chains are unofficially supported. They generally work fine, but are not tested continuously: [%header%autowidth,compact] |=== | Operating System | Tool Chain | Notes | macOS | http://gcc.gnu.org/[GCC] from Macports | | macOS | http://clang.llvm.org[Clang] from Macports | | UNIX-like | http://gcc.gnu.org/[GCC] | | UNIX-like | http://clang.llvm.org[Clang] | |=== [[sec:tool_chain_installation]] == Tool chain installation [NOTE] ==== Note that if you are using GCC then you currently need to install support for C+\\+, even if you are not building from C++ source. This restriction will be removed in a future Gradle version. ==== To build native software, you will need to have a compatible tool chain installed: [[sec:windows]] === Windows To build on Windows, install a compatible version of Visual Studio. The native plugins will discover the Visual Studio installations and select the latest version. There is no need to mess around with environment variables or batch scripts. This works fine from a Cygwin shell or the Windows command-line. Alternatively, you can install Cygwin with GCC or MinGW. Clang is currently not supported. [[sec:macOS]] === macOS To build on macOS, you should install XCode. The native plugins will discover the XCode installation using the system PATH. The native plugins also work with GCC and Clang bundled with Macports. To use one of the Macports tool chains, you will need to make the tool chain the default using the `port select` command and add Macports to the system PATH. [[sec:linux]] === Linux To build on Linux, install a compatible version of GCC or Clang. The native plugins will discover GCC or Clang using the system PATH. [[sec:native_software_model]] == Native software model The native software model builds on the base Gradle software model. To build native software using Gradle, your project should define one or more _native components_. Each component represents either an executable or a library that Gradle should build. A project can define any number of components. Gradle does not define any components by default. For each component, Gradle defines a _source set_ for each language that the component can be built from. A source set is essentially just a set of source directories containing source files. For example, when you apply the `c` plugin and define a library called `helloworld`, Gradle will define, by default, a source set containing the C source files in the `src/helloworld/c` directory. It will use these source files to build the `helloworld` library. This is described in more detail below. For each component, Gradle defines one or more _binaries_ as output. To build a binary, Gradle will take the source files defined for the component, compile them as appropriate for the source language, and link the result into a binary file. For an executable component, Gradle can produce executable binary files. For a library component, Gradle can produce both static and shared library binary files. For example, when you define a library called `helloworld` and build on Linux, Gradle will, by default, produce `libhelloworld.so` and `libhelloworld.a` binaries. In many cases, more than one binary can be produced for a component. These binaries may vary based on the tool chain used to build, the compiler/linker flags supplied, the dependencies provided, or additional source files provided. Each native binary produced for a component is referred to as a _variant_. Binary variants are discussed in detail below. [[sec:parallel_compilation]] == Parallel Compilation Gradle uses the single build worker pool to concurrently compile and link native components, by default. No special configuration is required to enable concurrent building. By default, the worker pool size is determined by the number of available processors on the build machine (as reported to the build JVM). To explicitly set the number of workers use the `--max-workers` command-line option or `org.gradle.workers.max` system property. There is generally no need to change this setting from its default. The build worker pool is shared across all build tasks. This means that when using <>, the maximum number of concurrent individual compilation operations does not increase. For example, if the build machine has 4 processing cores and 10 projects are compiling in parallel, Gradle will only use 4 total workers, not 40. [[sec:building_a_library]] == Building a library To build either a static or shared native library, you define a library component in the `components` container. The following sample defines a library called `hello`: === Example: Defining a library component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/c/groovy/build.gradle[tag=libraries] ---- A library component is represented using link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec]. Each library component can produce at least one shared library binary (link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec]) and at least one static library binary (link:{javadocPath}/org/gradle/nativeplatform/StaticLibraryBinarySpec.html[StaticLibraryBinarySpec]). [[sec:building_an_executable]] == Building an executable To build a native executable, you define an executable component in the `components` container. The following sample defines an executable called `main`: === Example: Defining executable components [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/c/groovy/build.gradle[tag=executables] ---- An executable component is represented using link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec]. Each executable component can produce at least one executable binary (link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec]). For each component defined, Gradle adds a link:{javadocPath}/org/gradle/language/base/FunctionalSourceSet.html[FunctionalSourceSet] with the same name. Each of these functional source sets will contain a language-specific source set for each of the languages supported by the project. [[sec:dependents]] == Assembling or building dependents Sometimes, you may need to _assemble_ (compile and link) or _build_ (compile, link and test) a component or binary and its _dependents_ (things that depend upon the component or binary). The native software model provides tasks that enable this capability. First, the _dependent components_ report gives insight about the relationships between each component. Second, the _build and assemble dependents_ tasks allow you to assemble or build a component and its dependents in one step. In the following example, the build file defines `OpenSSL` as a dependency of `libUtil` and `libUtil` as a dependency of `LinuxApp` and `WindowsApp`. Test suites are treated similarly. Dependents can be thought of as reverse dependencies. .Dependent Components Example image::nativeDependents.png[] [NOTE] ==== By following the dependencies backwards, you can see `LinuxApp` and `WindowsApp` are _dependents_ of `libUtil`. When `libUtil` is changed, Gradle will need to recompile or relink `LinuxApp` and `WindowsApp`. ==== When you _assemble_ dependents of a component, the component and all of its dependents are compiled and linked, including any test suite binaries. Gradle's up-to-date checks are used to only compile or link if something has changed. For instance, if you have changed source files in a way that do not affect the headers of your project, Gradle will be able to skip compilation for dependent components and only need to re-link with the new library. Tests are not run when assembling a component. When you _build_ dependents of a component, the component and all of its dependent binaries are compiled, linked _and checked_. Checking components means running any <<#sec:check_tasks,check task>> including executing any test suites, so tests _are_ run when building a component. In the following sections, we will demonstrate the usage of the `assembleDependents\\*`, `buildDependents*` and `dependentComponents` tasks with a sample build that contains a CUnit test suite. The build script for the sample is the following: === Example: Sample build [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cunit/groovy/build.gradle[tag=terse-example] ---- [[sec:dependents_report]] === Dependent components report Gradle provides a report that you can run from the command-line that shows a graph of components in your project and components that depend upon them. The following is an example of running `gradle dependentComponents` on the sample project: === Example: Dependent components report .Output of **`gradle dependentComponents`** ---- > gradle dependentComponents include::{snippetsPath}/native-binaries/cunit/tests/dependentComponentsReport.out[] ---- [NOTE] ==== See link:{groovyDslPath}/org.gradle.api.reporting.dependents.DependentComponentsReport.html[DependentComponentsReport] API documentation for more details. ==== By default, non-buildable binaries and test suites are hidden from the report. The `dependentComponents` task provides options that allow you to see all dependents by using the `--all` option: === Example: Dependent components report .Output of **`gradle dependentComponents --all`** ---- > gradle dependentComponents --all include::{snippetsPath}/native-binaries/cunit/tests/dependentComponentsReportAll.out[] ---- Here is the corresponding report for the `operators` component, showing dependents of all its binaries: === Example: Report of components that depends on the operators component .Output of **`gradle dependentComponents --component operators`** ---- > gradle dependentComponents --component operators include::{snippetsPath}/native-binaries/cunit/tests/assembleDependentComponentsReport.out[] ---- Here is the corresponding report for the `operators` component, showing dependents of all its binaries, including test suites: === Example: Report of components that depends on the operators component, including test suites .Output of **`gradle dependentComponents --test-suites --component operators`** ---- > gradle dependentComponents --test-suites --component operators include::{snippetsPath}/native-binaries/cunit/tests/buildDependentComponentsReport.out[] ---- [[sec:assemble_dependents]] === Assembling dependents For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec], Gradle will create a task named `assembleDependents__${component.name}${binary.variant}__` that _assembles_ (compile and link) the binary and all of its dependent binaries. For each link:{javadocPath}/org/gradle/nativeplatform/NativeComponentSpec.html[NativeComponentSpec], Gradle will create a task named `assembleDependents__${component.name}__` that _assembles_ all the binaries of the component and all of their dependent binaries. For example, to assemble the dependents of the ""passing"" flavor of the ""static"" library binary of the ""operators"" component, you would run the `assembleDependentsOperatorsPassingStaticLibrary` task: === Example: Assemble components that depends on the passing/static binary of the operators component .Output of **`gradle assembleDependentsOperatorsPassingStaticLibrary --max-workers=1`** ---- > gradle assembleDependentsOperatorsPassingStaticLibrary --max-workers=1 include::{snippetsPath}/native-binaries/cunit/tests/assembleDependentComponents.out[] ---- In the output above, the targeted binary gets assembled as well as the test suite binary that depends on it. You can also assemble _all_ of the dependents of a component (i.e. of all its binaries/variants) using the corresponding component task, e.g. `assembleDependentsOperators`. This is useful if you have many combinations of build types, flavors and platforms and want to assemble all of them. [[sec:build_dependents]] === Building dependents For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec], Gradle will create a task named `buildDependents__${component.name}${binary.variant}__` that _builds_ (compile, link and check) the binary and all of its dependent binaries. For each link:{javadocPath}/org/gradle/nativeplatform/NativeComponentSpec.html[NativeComponentSpec], Gradle will create a task named `buildDependents__${component.name}__` that _builds_ all the binaries of the component and all of their dependent binaries. For example, to build the dependents of the ""passing"" flavor of the ""static"" library binary of the ""operators"" component, you would run the `buildDependentsOperatorsPassingStaticLibrary` task: === Example: Build components that depends on the passing/static binary of the operators component .Output of **`gradle buildDependentsOperatorsPassingStaticLibrary --max-workers=1`** ---- > gradle buildDependentsOperatorsPassingStaticLibrary --max-workers=1 include::{snippetsPath}/native-binaries/cunit/tests/buildDependentComponents.out[] ---- In the output above, the targeted binary as well as the test suite binary that depends on it are built and the test suite has run. You can also build _all_ of the dependents of a component (i.e. of all its binaries/variants) using the corresponding component task, e.g. `buildDependentsOperators`. [[sec:native_tasks]] == Tasks For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] that can be produced by a build, a single _lifecycle task_ is constructed that can be used to create that binary, together with a set of other tasks that do the actual work of compiling, linking or assembling the binary. `__${component.name}__Executable`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec] Location of created binary;; `__${project.buildDir}__/exe/__${component.name}__/__${component.name}__` `__${component.name}__SharedLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] Location of created binary;; `__${project.buildDir}__/libs/__${component.name}__/shared/lib__${component.name}__.so` `__${component.name}__StaticLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/StaticLibraryBinarySpec.html[StaticLibraryBinarySpec] Location of created binary;; `__${project.buildDir}__/libs/__${component.name}__/static/__${component.name}__.a` [[sec:check_tasks]] === Check tasks For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] that can be produced by a build, a single _check task_ is constructed that can be used to assemble and check that binary. `check__${component.name}__Executable`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec] `check__${component.name}__SharedLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] `check__${component.name}__StaticLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] The built-in `check` task depends on all the _check tasks_ for binaries in the project. Without either <<#native_binaries:cunit,CUnit>> or <<#native_binaries:google_test,GoogleTest>> plugins, the binary check task only depends on the _lifecycle task_ that assembles the binary, see <<#sec:native_tasks,Native tasks>>. When the <<#native_binaries:cunit,CUnit>> or <<#native_binaries:google_test,GoogleTest>> plugins are applied, the task that executes the test suites for a component are automatically wired to the appropriate _check task_. You can also add custom check tasks as follows: === Example: Adding a custom check task [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/custom-check/groovy/build.gradle[tag=custom-check] ---- Now, running `check` or any of the _check tasks_ for the `hello` binaries will run the custom check task: === Example: Running checks for a given binary .Output of **`gradle checkHelloSharedLibrary`** ---- > gradle checkHelloSharedLibrary include::{snippetsPath}/native-binaries/custom-check/tests/nativeComponentCustomCheckOutput.out[] ---- [[sec:working_with_shared_libraries]] === Working with shared libraries For each executable binary produced, the `cpp` plugin provides an `install${binary.name}` task, which creates a development install of the executable, along with the shared libraries it requires. This allows you to run the executable without needing to install the shared libraries in their final locations. [[sec:finding_out_more_about_your_project]] == Finding out more about your project Gradle provides a report that you can run from the command-line that shows some details about the components and binaries that your project produces. To use this report, just run `gradle components`. Below is an example of running this report for one of the sample projects: === Example: The components report .Output of **`gradle components`** ---- > gradle components include::{snippetsPath}/native-binaries/cpp/tests/nativeComponentReport.out[] ---- [[native_binaries:languages]] == Language support Presently, Gradle supports building native software from any combination of source languages listed below. A native binary project will contain one or more named `FunctionalSourceSet` instances (e.g. 'main', 'test', etc), each of which can contain ``LanguageSourceSet``s containing source files, one for each language. * C * C++ * Objective-C * Objective-C++ * Assembly * Windows resources [[sec:cpp_sources]] === C++ sources C++ language support is provided by means of the `'cpp'` plugin. === Example: The 'cpp' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cpp/groovy/build.gradle[tag=apply-plugin] ---- $$C++$$ sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet], which defines a set of C++ source files and optionally a set of exported header files (for a library). By default, for any named component the link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet] contains `.cpp` source files in `src/${name}/cpp`, and header files in `src/${name}/headers`. While the `cpp` plugin defines these default locations for each link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet], it is possible to extend or override these defaults to allow for a different project layout. === Example: C++ source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippetsPath}/native-binaries/custom-layout/groovy/build.gradle[tag=cpp-sources] ---- For a library named 'main', header files in `src/main/headers` are considered the ""public"" or ""exported"" headers. Header files that should not be exported should be placed inside the `src/main/cpp` directory (though be aware that such header files should always be referenced in a manner relative to the file including them). [[sec:c_sources]] === C sources C language support is provided by means of the `'c'` plugin. === Example: The 'c' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/c/groovy/build.gradle[tag=apply-plugin] ---- C sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet], which defines a set of C source files and optionally a set of exported header files (for a library). By default, for any named component the link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet] contains `.c` source files in `src/${name}/c`, and header files in `src/${name}/headers`. While the `c` plugin defines these default locations for each link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet], it is possible to extend or override these defaults to allow for a different project layout. === Example: C source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippetsPath}/native-binaries/custom-layout/groovy/build.gradle[tag=c-sources] ---- For a library named 'main', header files in `src/main/headers` are considered the ""public"" or ""exported"" headers. Header files that should not be exported should be placed inside the `src/main/c` directory (though be aware that such header files should always be referenced in a manner relative to the file including them). [[sec:assembler_sources]] === Assembler sources Assembly language support is provided by means of the `'assembler'` plugin. === Example: The 'assembler' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/assembler/groovy/build.gradle[tag=apply-plugin] ---- Assembler sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.assembler.AssemblerSourceSet.html[AssemblerSourceSet], which defines a set of Assembler source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.assembler.AssemblerSourceSet.html[AssemblerSourceSet] contains `.s` source files under `src/${name}/asm`. [[sec:objectivec_sources]] === Objective-C sources Objective-C language support is provided by means of the `'objective-c'` plugin. === Example: The 'objective-c' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/objective-c/groovy/build.gradle[tag=apply-plugin] ---- Objective-C sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.objectivec.ObjectiveCSourceSet.html[ObjectiveCSourceSet], which defines a set of Objective-C source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.objectivec.ObjectiveCSourceSet.html[ObjectiveCSourceSet] contains `.m` source files under `src/${name}/objectiveC`. [[sec:objectivecpp_sources]] === Objective-C++ sources Objective-C++ language support is provided by means of the `'objective-cpp'` plugin. === Example: The 'objective-cpp' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/objective-cpp/groovy/build.gradle[tag=apply-plugin] ---- Objective-C$$++$$ sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.objectivecpp.ObjectiveCppSourceSet.html[ObjectiveCppSourceSet], which defines a set of Objective-C++ source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.objectivecpp.ObjectiveCppSourceSet.html[ObjectiveCppSourceSet] contains `.mm` source files under `src/${name}/objectiveCpp`. [[sec:configuring_the_compiler_assembler_and_linker]] == Configuring the compiler, assembler and linker Each binary to be produced is associated with a set of compiler and linker settings, which include command-line arguments as well as macro definitions. These settings can be applied to all binaries, an individual binary, or selectively to a group of binaries based on some criteria. === Example: Settings that apply to all binaries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cpp/groovy/build.gradle[tag=all-binaries] ---- Each binary is associated with a particular link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain], allowing settings to be targeted based on this value. It is easy to apply settings to all binaries of a particular type: === Example: Settings that apply to all shared libraries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/c/groovy/build.gradle[tag=all-shared-libraries] ---- Furthermore, it is possible to specify settings that apply to all binaries produced for a particular `executable` or `library` component: === Example: Settings that apply to all binaries produced for the 'main' executable component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/assembler/groovy/build.gradle[tag=assembler-args] ---- The example above will apply the supplied configuration to all `executable` binaries built. Similarly, settings can be specified to target binaries for a component that are of a particular type: e.g. all shared libraries for the main library component. === Example: Settings that apply only to shared libraries produced for the 'main' library component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cpp-lib/groovy/build.gradle[tag=args] ---- [[native_binaries:windows-resources]] == Windows Resources When using the link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.VisualCpp.html[VisualCpp] tool chain, Gradle is able to compile Window Resource (`rc`) files and link them into a native binary. This functionality is provided by the `'windows-resources'` plugin. === Example: The 'windows-resources' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/windows-resources/groovy/build.gradle[tag=apply-plugin] ---- Windows resources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.rc.WindowsResourceSet.html[WindowsResourceSet], which defines a set of Windows Resource source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.rc.WindowsResourceSet.html[WindowsResourceSet] contains `.rc` source files under `src/${name}/rc`. As with other source types, you can configure the location of the windows resources that should be included in the binary. === Example: Configuring the location of Windows resource sources [source.multi-language-sample,groovy,indent=0] .build-resource-only-dll.gradle ---- include::{snippetsPath}/native-binaries/windows-resources/groovy/build-resource-only-dll.gradle[tag=windows-resource-set] ---- You are able to construct a resource-only library by providing Windows Resource sources with no other language sources, and configure the linker as appropriate: === Example: Building a resource-only dll [source.multi-language-sample,groovy] .build-resource-only-dll.gradle ---- include::{snippetsPath}/native-binaries/windows-resources/groovy/build-resource-only-dll.gradle[tag=resource-only-library] ---- The example above also demonstrates the mechanism of passing extra command-line arguments to the resource compiler. The `rcCompiler` extension is of type link:{javadocPath}/org/gradle/nativeplatform/PreprocessingTool.html[PreprocessingTool]. [[sec:library_dependencies]] == Library Dependencies Dependencies for native components are binary libraries that export header files. The header files are used during compilation, with the compiled binary dependency being used during linking and execution. Header files should be organized into subdirectories to prevent clashes of commonly named headers. For instance, if your `mylib` project has a `logging.h` header, it will make it less likely the wrong header is used if you include it as `""mylib/logging.h""` instead of `""logging.h""`. [[sec:dependencies_within_the_same_project]] === Dependencies within the same project A set of sources may depend on header files provided by another binary component within the same project. A common example is a native executable component that uses functions provided by a separate native library component. Such a library dependency can be added to a source set associated with the `executable` component: === Example: Providing a library dependency to the source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippetsPath}/native-binaries/cpp/groovy/build.gradle[tag=source-library] ---- Alternatively, a library dependency can be provided directly to the `NativeExecutableBinarySpec` for the `executable`. === Example: Providing a library dependency to the binary [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/custom-layout/groovy/build.gradle[tag=binary-library] ---- [[sec:project_dependencies]] === Project Dependencies For a component produced in a different Gradle project, the notation is similar. === Example: Declaring project dependencies [source.multi-language-sample,groovy] .lib/build.gradle ---- include::{snippetsPath}/native-binaries/multi-project/groovy/lib/build.gradle[] ---- [source.multi-language-sample,groovy] .exe/build.gradle ---- include::{snippetsPath}/native-binaries/multi-project/groovy/exe/build.gradle[] ---- [[native_binaries:preCompiledHeaders]] == Precompiled Headers Precompiled headers are a performance optimization that reduces the cost of compiling widely used headers multiple times. This feature _precompiles_ a header such that the compiled object file can be reused when compiling each source file rather than recompiling the header each time. This support is available for C, C+\\+, Objective-C, and Objective-C++ builds. To configure a precompiled header, first a header file needs to be defined that includes all of the headers that should be precompiled. It must be specified as the first included header in every source file where the precompiled header should be used. It is assumed that this header file, and any headers it contains, make use of header guards so that they can be included in an idempotent manner. If header guards are not used in a header file, it is possible the header could be compiled more than once and could potentially lead to a broken build. === Example: Creating a precompiled header file [source.multi-language-sample,c] .src/hello/headers/pch.h ---- include::{snippetsPath}/native-binaries/pre-compiled-headers/groovy/src/hello/headers/pch.h[] ---- === Example: Including a precompiled header file in a source file [source.multi-language-sample,cpp] .src/hello/cpp/hello.cpp ---- include::{snippetsPath}/native-binaries/pre-compiled-headers/groovy/src/hello/cpp/hello.cpp[] ---- Precompiled headers are specified on a source set. Only one precompiled header file can be specified on a given source set and will be applied to all source files that declare it as the first include. If a source files does not include this header file as the first header, the file will be compiled in the normal manner (without making use of the precompiled header object file). The string provided should be the same as that which is used in the ""#include"" directive in the source files. === Example: Configuring a precompiled header [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/pre-compiled-headers/groovy/build.gradle[tag=libraries] ---- A precompiled header must be included in the same way for all files that use it. Usually, this means the header file should exist in the source set ""headers"" directory or in a directory included on the compiler include path. [[native_binaries:variants]] == Native Binary Variants For each executable or library defined, Gradle is able to build a number of different native binary variants. Examples of different variants include debug vs release binaries, 32-bit vs 64-bit binaries, and binaries produced with different custom preprocessor flags. Binaries produced by Gradle can be differentiated on <<#native_binaries:build_type,build type>>, <<#native_binaries:platform,platform>>, and <<#native_binaries:flavor,flavor>>. For each of these 'variant dimensions', it is possible to specify a set of available values as well as target each component at one, some or all of these. For example, a plugin may define a range of support platforms, but you may choose to only target Windows-x86 for a particular component. [[native_binaries:build_type]] === Build types A `build type` determines various non-functional aspects of a binary, such as whether debug information is included, or what optimisation level the binary is compiled with. Typical build types are 'debug' and 'release', but a project is free to define any set of build types. === Example: Defining build types [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/variants/groovy/build.gradle[tag=build-types] ---- If no build types are defined in a project, then a single, default build type called 'debug' is added. For a build type, a Gradle project will typically define a set of compiler/linker flags per tool chain. === Example: Configuring debug binaries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/variants/groovy/build.gradle[tag=build-type-config] ---- [NOTE] ==== At this stage, it is completely up to the build script to configure the relevant compiler/linker flags for each build type. Future versions of Gradle will automatically include the appropriate debug flags for any 'debug' build type, and may be aware of various levels of optimisation as well. ==== [[native_binaries:platform]] === Platform An executable or library can be built to run on different operating systems and cpu architectures, with a variant being produced for each platform. Gradle defines each OS/architecture combination as a link:{groovyDslPath}/org.gradle.nativeplatform.platform.NativePlatform.html[NativePlatform], and a project may define any number of platforms. If no platforms are defined in a project, then a single, default platform 'current' is added. [NOTE] ==== Presently, a `Platform` consists of a defined operating system and architecture. As we continue to develop the native binary support in Gradle, the concept of Platform will be extended to include things like C-runtime version, Windows SDK, ABI, etc. Sophisticated builds may use the extensibility of Gradle to apply additional attributes to each platform, which can then be queried to specify particular includes, preprocessor macros or compiler arguments for a native binary. ==== === Example: Defining platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/variants/groovy/build.gradle[tag=platforms] ---- For a given variant, Gradle will attempt to find a link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain] that is able to build for the target platform. Available tool chains are searched in the order defined. See the <<#native_binaries:tool_chain,tool chains>> section below for more details. [[native_binaries:flavor]] === Flavor Each component can have a set of named `flavors`, and a separate binary variant can be produced for each flavor. While the `build type` and `target platform` variant dimensions have a defined meaning in Gradle, each project is free to define any number of flavors and apply meaning to them in any way. An example of component flavors might differentiate between 'demo', 'paid' and 'enterprise' editions of the component, where the same set of sources is used to produce binaries with different functions. === Example: Defining flavors [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/flavors/groovy/build.gradle[tag=flavors] ---- In the example above, a library is defined with a 'english' and 'french' flavor. When compiling the 'french' variant, a separate macro is defined which leads to a different binary being produced. If no flavor is defined for a component, then a single default flavor named 'default' is used. [[sec:selecting_the_build_types_platforms_and_flavors_for_a_component]] === Selecting the build types, platforms and flavors for a component For a default component, Gradle will attempt to create a native binary variant for each and every combination of `buildType` and `flavor` defined for the project. It is possible to override this on a per-component basis, by specifying the set of `targetBuildTypes` and/or `targetFlavors`. By default, Gradle will build for the default platform, see <<#native_binaries:platform,above>>, unless specified explicitly on a per-component basis by specifying a set of `targetPlatforms`. === Example: Targeting a component at particular platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/variants/groovy/build.gradle[tag=target-platforms] ---- Here you can see that the link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetPlatform(java.lang.String)[TargetedNativeComponent.targetPlatform(java.lang.String)] method is used to specify a platform that the `NativeExecutableSpec` named `main` should be built for. A similar mechanism exists for selecting link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetBuildTypes(java.lang.String++[]++)[TargetedNativeComponent.targetBuildTypes(java.lang.String...)] and link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetFlavors(java.lang.String++[]++)[TargetedNativeComponent.targetFlavors(java.lang.String...)]. [[sec:building_all_possible_variants]] === Building all possible variants When a set of build types, target platforms, and flavors is defined for a component, a link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] model element is created for every possible combination of these. However, in many cases it is not possible to build a particular variant, perhaps because no tool chain is available to build for a particular platform. If a binary variant cannot be built for any reason, then the link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] associated with that variant will not be `buildable`. It is possible to use this property to create a task to generate all possible variants on a particular machine. === Example: Building all possible variants [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/tool-chains/groovy/build.gradle[tag=buildable] ---- [[native_binaries:tool_chain]] == Tool chains A single build may utilize different tool chains to build variants for different platforms. To this end, the core 'native-binary' plugins will attempt to locate and make available supported tool chains. However, the set of tool chains for a project may also be explicitly defined, allowing additional cross-compilers to be configured as well as allowing the install directories to be specified. [[sec:defining_tool_chains]] === Defining tool chains The supported tool chain types are: * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Gcc.html[Gcc] * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Clang.html[Clang] * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.VisualCpp.html[VisualCpp] === Example: Defining tool chains [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/tool-chains/groovy/build.gradle[tag=toolChains] ---- Each tool chain implementation allows for a certain degree of configuration (see the API documentation for more details). [[sec:using_tool_chains]] === Using tool chains It is not necessary or possible to specify the tool chain that should be used to build. For a given variant, Gradle will attempt to locate a link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain] that is able to build for the target platform. Available tool chains are searched in the order defined. [NOTE] ==== When a platform does not define an architecture or operating system, the default target of the tool chain is assumed. So if a platform does not define a value for `operatingSystem`, Gradle will find the first available tool chain that can build for the specified `architecture`. ==== The core Gradle tool chains are able to target the following architectures out of the box. In each case, the tool chain will target the current operating system. See the next section for information on cross-compiling for other operating systems. [cols=""a,a"", options=""header""] |=== | Tool Chain | Architectures | GCC | x86, x86_64 | Clang | x86, x86_64 | Visual C++ | x86, x86_64, ia-64 |=== So for GCC running on linux, the supported target platforms are 'linux/x86' and 'linux/x86_64'. For GCC running on Windows via Cygwin, platforms 'windows/x86' and 'windows/x86_64' are supported. (The Cygwin POSIX runtime is not yet modelled as part of the platform, but will be in the future.) If no target platforms are defined for a project, then all binaries are built to target a default platform named 'current'. This default platform does not specify any `architecture` or `operatingSystem` value, hence using the default values of the first available tool chain. Gradle provides a _hook_ that allows the build author to control the exact set of arguments passed to a tool chain executable. This enables the build author to work around any limitations in Gradle, or assumptions that Gradle makes. The arguments hook should be seen as a 'last-resort' mechanism, with preference given to truly modelling the underlying domain. === Example: Reconfigure tool arguments [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/tool-chains/groovy/build.gradle[tag=withArguments] ---- [[sec:crosscompiling_with_gcc]] === Cross-compiling with GCC Cross-compiling is possible with the link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Gcc.html[Gcc] and link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Clang.html[Clang] tool chains, by adding support for additional target platforms. This is done by specifying a target platform for a toolchain. For each target platform a custom configuration can be specified. === Example: Defining target platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/target-platforms/groovy/build.gradle[tag=targetplatforms] ---- [[native_binaries:visual_studio]] == Visual Studio IDE integration Gradle has the ability to generate Visual Studio project and solution files for the native components defined in your build. This ability is added by the `visual-studio` plugin. For a multi-project build, all projects with native components (and the root project) should have this plugin applied. When the `visual-studio` plugin is applied to the root project, a task named `visualStudio` is created, which will generate a Visual Studio solution file containing all components in the build. This solution will include a Visual Studio project for each component, as well as configuring each component to build using Gradle. A task named `openVisualStudio` is also created by the `visual-studio` plugin when the project is the root project. This task generates the Visual Studio solution and then opens the solution in Visual Studio. This means you can simply run `gradlew openVisualStudio` from the root project to generate and open the Visual Studio solution in one convenient step. The content of the generated visual studio files can be modified via API hooks, provided by the `visualStudio` extension. Take a look at the 'visual-studio' sample, or see link:{groovyDslPath}/org.gradle.ide.visualstudio.VisualStudioExtension.html#org.gradle.ide.visualstudio.VisualStudioExtension:projects[VisualStudioExtension.getProjects()] and link:{groovyDslPath}/org.gradle.ide.visualstudio.VisualStudioRootExtension.html#org.gradle.ide.visualstudio.VisualStudioRootExtension:solution[VisualStudioRootExtension.getSolution()] in the API documentation for more details. [[native_binaries:cunit]] == CUnit support The Gradle `cunit` plugin provides support for compiling and executing CUnit tests in your native-binary project. For each link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] and link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] defined in your project, Gradle will create a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component, named `${component.name}Test`. [[sec:cunit_sources]] === CUnit sources Gradle will create a link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet] named 'cunit' for each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component in the project. This source set should contain the cunit test files for the component under test. Source files can be located in the conventional location (`src/${component.name}Test/cunit`) or can be configured like any other source set. Gradle initialises the CUnit test registry and executes the tests, utilising some generated CUnit launcher sources. Gradle will expect and call a function with the signature `void gradle_cunit_register()` that you can use to configure the actual CUnit suites and tests to execute. === Example: Registering CUnit tests [source.multi-language-sample,c] .suite_operators.c ---- include::{snippetsPath}/native-binaries/cunit/groovy/src/operatorsTest/c/suite_operators.c[] ---- [NOTE] ==== Due to this mechanism, your CUnit sources may not contain a `main` method since this will clash with the method provided by Gradle. ==== [[sec:building_cunit_executables]] === Building CUnit executables A link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component has an associated link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] or link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] component. For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] configured for the main component, a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec] will be configured on the test suite component. These test suite binaries can be configured in a similar way to any other binary instance: === Example: Configuring CUnit tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cunit/groovy/build.gradle[tag=configure-test-binary] ---- [NOTE] ==== Both the CUnit sources provided by your project and the generated launcher require the core CUnit headers and libraries. Presently, this library dependency must be provided by your project for each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec]. ==== [[sec:running_cunit_tests]] === Running CUnit tests For each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec], Gradle will create a task to execute this binary, which will run all of the registered CUnit tests. Test results will be found in the `__${build.dir}__/test-results` directory. === Example: Running CUnit tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cunit/groovy/build.gradle[tag=complete-example] ---- .Output of `gradle -q runOperatorsTestFailingCUnitExe` ---- > gradle -q runOperatorsTestFailingCUnitExe include::{snippetsPath}/native-binaries/cunit/tests/completeCUnitExample.out[] ---- [NOTE] ==== The current support for CUnit is quite rudimentary. Plans for future integration include: * Allow tests to be declared with Javadoc-style annotations. * Improved HTML reporting, similar to that available for JUnit. * Real-time feedback for test execution. * Support for additional test frameworks. ==== [[native_binaries:google_test]] == GoogleTest support The Gradle `google-test` plugin provides support for compiling and executing GoogleTest tests in your native-binary project. For each link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] and link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] defined in your project, Gradle will create a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component, named `${component.name}Test`. [[sec:googletest_sources]] === GoogleTest sources Gradle will create a link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet] named 'cpp' for each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component in the project. This source set should contain the GoogleTest test files for the component under test. Source files can be located in the conventional location (`src/${component.name}Test/cpp`) or can be configured like any other source set. [[sec:building_googletest_executables]] === Building GoogleTest executables A link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component has an associated link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] or link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] component. For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] configured for the main component, a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec] will be configured on the test suite component. These test suite binaries can be configured in a similar way to any other binary instance: === Example: Registering GoogleTest tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/google-test/groovy/build.gradle[tag=configure-test-binary] ---- [NOTE] ==== The GoogleTest sources provided by your project require the core GoogleTest headers and libraries. Presently, this library dependency must be provided by your project for each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec]. ==== [[sec:running_googletest_tests]] === Running GoogleTest tests For each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec], Gradle will create a task to execute this binary, which will run all of the registered GoogleTest tests. Test results will be found in the `__${build.dir}__/test-results` directory. [NOTE] ==== The current support for GoogleTest is quite rudimentary. Plans for future integration include: * Improved HTML reporting, similar to that available for JUnit. * Real-time feedback for test execution. * Support for additional test frameworks. ==== ",12172,False,2319.5383084087757,median "// Automatically generated by 'openshift-apidocs-gen'. Do not edit. :_content-type: ASSEMBLY [id=""machineset-machine-openshift-io-v1beta1""] = MachineSet [machine.openshift.io/v1beta1] ifdef::product-title[] include::modules/common-attributes.adoc[] endif::[] toc::[] Description:: + -- MachineSet ensures that a specified number of machines replicas are running at any given time. -- Type:: `object` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `metadata` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta_v2[`ObjectMeta_v2`] | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `spec` | `object` | MachineSetSpec defines the desired state of MachineSet | `status` | `object` | MachineSetStatus defines the observed state of MachineSet |=== === .spec Description:: + -- MachineSetSpec defines the desired state of MachineSet -- Type:: `object` Required:: - `selector` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `deletePolicy` | `string` | DeletePolicy defines the policy used to identify nodes to delete when downscaling. Defaults to ""Random"". Valid values are ""Random, ""Newest"", ""Oldest"" | `minReadySeconds` | `integer` | MinReadySeconds is the minimum number of seconds for which a newly created machine should be ready. Defaults to 0 (machine will be considered available as soon as it is ready) | `replicas` | `integer` | Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. | `selector` | `object` | Selector is a label query over machines that should match the replica count. Label keys and values that must match in order to be controlled by this MachineSet. It must match the machine template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors | `template` | `object` | Template is the object that describes the machine that will be created if insufficient replicas are detected. |=== === .spec.selector Description:: + -- Selector is a label query over machines that should match the replica count. Label keys and values that must match in order to be controlled by this MachineSet. It must match the machine template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `matchExpressions` | `array` | matchExpressions is a list of label selector requirements. The requirements are ANDed. | `matchExpressions[]` | `object` | A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. | `matchLabels` | `object (string)` | matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is ""key"", the operator is ""In"", and the values array contains only ""value"". The requirements are ANDed. |=== === .spec.selector.matchExpressions Description:: + -- matchExpressions is a list of label selector requirements. The requirements are ANDed. -- Type:: `array` === .spec.selector.matchExpressions[] Description:: + -- A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. -- Type:: `object` Required:: - `key` - `operator` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `key` | `string` | key is the label key that the selector applies to. | `operator` | `string` | operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. | `values` | `array (string)` | values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch. |=== === .spec.template Description:: + -- Template is the object that describes the machine that will be created if insufficient replicas are detected. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `metadata` | `object` | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `spec` | `object` | Specification of the desired behavior of the machine. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status |=== === .spec.template.metadata Description:: + -- Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `annotations` | `object (string)` | Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations | `generateName` | `string` | GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. If this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header). Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency | `labels` | `object (string)` | Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels | `name` | `string` | Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names | `namespace` | `string` | Namespace defines the space within each name must be unique. An empty namespace is equivalent to the ""default"" namespace, but ""default"" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty. Must be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces | `ownerReferences` | `array` | List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. | `ownerReferences[]` | `object` | OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. |=== === .spec.template.metadata.ownerReferences Description:: + -- List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. -- Type:: `array` === .spec.template.metadata.ownerReferences[] Description:: + -- OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. -- Type:: `object` Required:: - `apiVersion` - `kind` - `name` - `uid` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | API version of the referent. | `blockOwnerDeletion` | `boolean` | If true, AND if the owner has the ""foregroundDeletion"" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. Defaults to false. To set this field, a user needs ""delete"" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. | `controller` | `boolean` | If true, this reference points to the managing controller. | `kind` | `string` | Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `name` | `string` | Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names | `uid` | `string` | UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids |=== === .spec.template.spec Description:: + -- Specification of the desired behavior of the machine. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `metadata` | `object` | ObjectMeta will autopopulate the Node created. Use this to indicate what labels, annotations, name prefix, etc., should be used when creating the Node. | `providerID` | `string` | ProviderID is the identification ID of the machine provided by the provider. This field must match the provider ID as seen on the node object corresponding to this machine. This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a generic out-of-tree provider for autoscaler, this field is required by autoscaler to be able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver and then a comparison is done to find out unregistered machines and are marked for delete. This field will be set by the actuators and consumed by higher level entities like autoscaler that will be interfacing with cluster-api as generic provider. | `providerSpec` | `object` | ProviderSpec details Provider-specific configuration to use during node creation. | `taints` | `array` | The list of the taints to be applied to the corresponding Node in additive manner. This list will not overwrite any other taints added to the Node on an ongoing basis by other entities. These taints should be actively reconciled e.g. if you ask the machine controller to apply a taint and then manually remove the taint the machine controller will put it back) but not have the machine controller remove any taints | `taints[]` | `object` | The node this Taint is attached to has the ""effect"" on any pod that does not tolerate the Taint. |=== === .spec.template.spec.metadata Description:: + -- ObjectMeta will autopopulate the Node created. Use this to indicate what labels, annotations, name prefix, etc., should be used when creating the Node. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `annotations` | `object (string)` | Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations | `generateName` | `string` | GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. If this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header). Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency | `labels` | `object (string)` | Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels | `name` | `string` | Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names | `namespace` | `string` | Namespace defines the space within each name must be unique. An empty namespace is equivalent to the ""default"" namespace, but ""default"" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty. Must be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces | `ownerReferences` | `array` | List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. | `ownerReferences[]` | `object` | OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. |=== === .spec.template.spec.metadata.ownerReferences Description:: + -- List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. -- Type:: `array` === .spec.template.spec.metadata.ownerReferences[] Description:: + -- OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. -- Type:: `object` Required:: - `apiVersion` - `kind` - `name` - `uid` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | API version of the referent. | `blockOwnerDeletion` | `boolean` | If true, AND if the owner has the ""foregroundDeletion"" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. Defaults to false. To set this field, a user needs ""delete"" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned. | `controller` | `boolean` | If true, this reference points to the managing controller. | `kind` | `string` | Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `name` | `string` | Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names | `uid` | `string` | UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids |=== === .spec.template.spec.providerSpec Description:: + -- ProviderSpec details Provider-specific configuration to use during node creation. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `value` | `` | Value is an inlined, serialized representation of the resource configuration. It is recommended that providers maintain their own versioned API types that should be serialized/deserialized from this field, akin to component config. |=== === .spec.template.spec.taints Description:: + -- The list of the taints to be applied to the corresponding Node in additive manner. This list will not overwrite any other taints added to the Node on an ongoing basis by other entities. These taints should be actively reconciled e.g. if you ask the machine controller to apply a taint and then manually remove the taint the machine controller will put it back) but not have the machine controller remove any taints -- Type:: `array` === .spec.template.spec.taints[] Description:: + -- The node this Taint is attached to has the ""effect"" on any pod that does not tolerate the Taint. -- Type:: `object` Required:: - `effect` - `key` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `effect` | `string` | Required. The effect of the taint on pods that do not tolerate the taint. Valid effects are NoSchedule, PreferNoSchedule and NoExecute. | `key` | `string` | Required. The taint key to be applied to a node. | `timeAdded` | `string` | TimeAdded represents the time at which the taint was added. It is only written for NoExecute taints. | `value` | `string` | The taint value corresponding to the taint key. |=== === .status Description:: + -- MachineSetStatus defines the observed state of MachineSet -- Type:: `object` Required:: - `replicas` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `availableReplicas` | `integer` | The number of available replicas (ready for at least minReadySeconds) for this MachineSet. | `errorMessage` | `string` | | `errorReason` | `string` | In the event that there is a terminal problem reconciling the replicas, both ErrorReason and ErrorMessage will be set. ErrorReason will be populated with a succinct value suitable for machine interpretation, while ErrorMessage will contain a more verbose string suitable for logging and human consumption. These fields should not be set for transitive errors that a controller faces that are expected to be fixed automatically over time (like service outages), but instead indicate that something is fundamentally wrong with the MachineTemplate's spec or the configuration of the machine controller, and that manual intervention is required. Examples of terminal errors would be invalid combinations of settings in the spec, values that are unsupported by the machine controller, or the responsible machine controller itself being critically misconfigured. Any transient errors that occur during the reconciliation of Machines can be added as events to the MachineSet object and/or logged in the controller's output. | `fullyLabeledReplicas` | `integer` | The number of replicas that have labels matching the labels of the machine template of the MachineSet. | `observedGeneration` | `integer` | ObservedGeneration reflects the generation of the most recently observed MachineSet. | `readyReplicas` | `integer` | The number of ready replicas for this MachineSet. A machine is considered ready when the node has been created and is ""Ready"". | `replicas` | `integer` | Replicas is the most recently observed number of replicas. |=== == API endpoints The following API endpoints are available: * `/apis/machine.openshift.io/v1beta1/machinesets` - `GET`: list objects of kind MachineSet * `/apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets` - `DELETE`: delete collection of MachineSet - `GET`: list objects of kind MachineSet - `POST`: create a MachineSet * `/apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}` - `DELETE`: delete a MachineSet - `GET`: read the specified MachineSet - `PATCH`: partially update the specified MachineSet - `PUT`: replace the specified MachineSet * `/apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}/scale` - `GET`: read scale of the specified MachineSet - `PATCH`: partially update scale of the specified MachineSet - `PUT`: replace scale of the specified MachineSet * `/apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}/status` - `GET`: read status of the specified MachineSet - `PATCH`: partially update status of the specified MachineSet - `PUT`: replace status of the specified MachineSet === /apis/machine.openshift.io/v1beta1/machinesets .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: list objects of kind MachineSet .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.openshift.machine.v1beta1.MachineSetList[`MachineSetList`] schema | 401 - Unauthorized | Empty |=== === /apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status_v2[`Status_v2`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list objects of kind MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.openshift.machine.v1beta1.MachineSetList[`MachineSetList`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 201 - Created | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 202 - Accepted | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 401 - Unauthorized | Empty |=== === /apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the MachineSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions_v2[`DeleteOptions_v2`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status_v2[`Status_v2`] schema | 202 - Accepted | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status_v2[`Status_v2`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 201 - Created | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 401 - Unauthorized | Empty |=== === /apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}/scale .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the MachineSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read scale of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.autoscaling.v1.Scale_v2[`Scale_v2`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update scale of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.autoscaling.v1.Scale_v2[`Scale_v2`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace scale of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.api.autoscaling.v1.Scale_v2[`Scale_v2`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.autoscaling.v1.Scale_v2[`Scale_v2`] schema | 201 - Created | xref:../objects/index.adoc#io.k8s.api.autoscaling.v1.Scale_v2[`Scale_v2`] schema | 401 - Unauthorized | Empty |=== === /apis/machine.openshift.io/v1beta1/namespaces/{namespace}/machinesets/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the MachineSet | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified MachineSet .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 201 - Created | xref:../machine_apis/machineset-machine-openshift-io-v1beta1.adoc#machineset-machine-openshift-io-v1beta1[`MachineSet`] schema | 401 - Unauthorized | Empty |=== ",12197,False,2478.9994534466696,median "#include #include #include #include #include #include using namespace std::chrono_literals; namespace nano { // Test disabled because it's failing intermittently. // PR in which it got disabled: https://github.com/nanocurrency/nano-node/pull/3512 // Issue for investigating it: https://github.com/nanocurrency/nano-node/issues/3522 TEST (active_transactions, DISABLED_confirm_active) { nano::system system; nano::node_flags node_flags; node_flags.disable_request_loop = true; auto & node1 = *system.add_node (node_flags); auto send = nano::send_block_builder () .previous (nano::dev::genesis->hash ()) .destination (nano::public_key ()) .balance (nano::dev::constants.genesis_amount - 100) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); ASSERT_EQ (nano::process_result::progress, node1.process (*send).code); nano::node_config node_config2 (nano::get_available_port (), system.logging); node_config2.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; nano::node_flags node_flags2; // The rep crawler would otherwise request confirmations in order to find representatives node_flags2.disable_rep_crawler = true; auto & node2 = *system.add_node (node_config2, node_flags2); system.deadline_set (5s); // Let node2 know about the block while (node2.active.empty ()) { node1.network.flood_block (send, nano::buffer_drop_policy::no_limiter_drop); ASSERT_NO_ERROR (system.poll ()); } // Save election to check request count afterwards auto election = node2.active.election (send->qualified_root ()); ASSERT_NE (nullptr, election); // Add key to node1 system.wallet (0)->insert_adhoc (nano::dev::genesis_key.prv); // Add representative to disabled rep crawler auto peers (node2.network.random_set (1)); ASSERT_FALSE (peers.empty ()); { nano::lock_guard guard (node2.rep_crawler.probable_reps_mutex); node2.rep_crawler.probable_reps.emplace (nano::dev::genesis_key.pub, nano::dev::constants.genesis_amount, *peers.begin ()); } ASSERT_TIMELY (5s, election->votes ().size () != 1); // Votes were inserted (except for the null account) auto confirm_req_count (election->confirmation_request_count.load ()); // At least one confirmation request ASSERT_GT (confirm_req_count, 0u); ASSERT_FALSE (election->confirmed ()); // Cannot be confirmed without final vote node1.confirmation_height_processor.add (send); // Confirm block for node1 for final vote generation ASSERT_TIMELY (5s, node1.ledger.block_confirmed (node1.store.tx_begin_read (), send->hash ())); node1.history.erase (send->root ()); // Have to erase existing non-final vote for final vote generation (at runtime it should be replaced with automatically generated final vote from election) // Waiting for final confirmation ASSERT_TIMELY (10s, node2.ledger.cache.cemented_count == 2 && node2.active.empty ()); // At least one more confirmation request ASSERT_GT (election->confirmation_request_count, confirm_req_count); // Blocks were cleared (except for the null account) ASSERT_EQ (1, election->blocks ().size ()); } } namespace nano { TEST (active_transactions, confirm_frontier) { nano::system system; nano::node_flags node_flags; node_flags.disable_request_loop = true; // Voting node auto & node1 = *system.add_node (node_flags); nano::node_flags node_flags2; // The rep crawler would otherwise request confirmations in order to find representatives node_flags2.disable_rep_crawler = true; auto & node2 = *system.add_node (node_flags2); // Add key to node1 system.wallet (0)->insert_adhoc (nano::dev::genesis_key.prv); // Add representative to disabled rep crawler auto peers (node2.network.random_set (1)); ASSERT_FALSE (peers.empty ()); { nano::lock_guard guard (node2.rep_crawler.probable_reps_mutex); node2.rep_crawler.probable_reps.emplace (nano::dev::genesis_key.pub, nano::dev::constants.genesis_amount, *peers.begin ()); } nano::state_block_builder builder; auto send = builder .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 100) .link (nano::public_key ()) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); auto send_copy = builder.make_block ().from (*send).build_shared (); ASSERT_EQ (nano::process_result::progress, node1.process (*send).code); node1.confirmation_height_processor.add (send); ASSERT_TIMELY (5s, node1.ledger.block_confirmed (node1.store.tx_begin_read (), send->hash ())); ASSERT_EQ (nano::process_result::progress, node2.process (*send_copy).code); ASSERT_TIMELY (5s, !node2.active.empty ()); // Save election to check request count afterwards auto election2 = node2.active.election (send->qualified_root ()); ASSERT_NE (nullptr, election2); ASSERT_TIMELY (5s, node2.ledger.cache.cemented_count == 2 && node2.active.empty ()); ASSERT_GT (election2->confirmation_request_count, 0u); } } TEST (active_transactions, keep_local) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.enable_voting = false; node_config.active_elections_size = 2; //bound to 2, wont drop wallet created transactions, but good to test dropping remote // Disable frontier confirmation to allow the test to finish before node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (node_config); auto & wallet (*system.wallet (0)); //key 1/2 will be managed by the wallet nano::keypair key1, key2, key3, key4, key5, key6; wallet.insert_adhoc (nano::dev::genesis_key.prv); auto send1 (wallet.send_action (nano::dev::genesis_key.pub, key1.pub, node.config.receive_minimum.number ())); auto send2 (wallet.send_action (nano::dev::genesis_key.pub, key2.pub, node.config.receive_minimum.number ())); auto send3 (wallet.send_action (nano::dev::genesis_key.pub, key3.pub, node.config.receive_minimum.number ())); auto send4 (wallet.send_action (nano::dev::genesis_key.pub, key4.pub, node.config.receive_minimum.number ())); auto send5 (wallet.send_action (nano::dev::genesis_key.pub, key5.pub, node.config.receive_minimum.number ())); auto send6 (wallet.send_action (nano::dev::genesis_key.pub, key6.pub, node.config.receive_minimum.number ())); // should not drop wallet created transactions ASSERT_TIMELY (5s, node.active.size () == 1); for (auto const & block : { send1, send2, send3, send4, send5, send6 }) { ASSERT_TIMELY (1s, node.active.election (block->qualified_root ())); auto election = node.active.election (block->qualified_root ()); ASSERT_NE (nullptr, election); election->force_confirm (); } ASSERT_TIMELY (5s, node.active.empty ()); nano::state_block_builder builder; auto open1 = builder.make_block () .account (key1.pub) .previous (0) .representative (key1.pub) .balance (node.config.receive_minimum.number ()) .link (send1->hash ()) .sign (key1.prv, key1.pub) .work (*system.work.generate (key1.pub)) .build_shared (); auto open2 = builder.make_block () .account (key2.pub) .previous (0) .representative (key2.pub) .balance (node.config.receive_minimum.number ()) .link (send2->hash ()) .sign (key2.prv, key2.pub) .work (*system.work.generate (key2.pub)) .build_shared (); auto open3 = builder.make_block () .account (key3.pub) .previous (0) .representative (key3.pub) .balance (node.config.receive_minimum.number ()) .link (send3->hash ()) .sign (key3.prv, key3.pub) .work (*system.work.generate (key3.pub)) .build_shared (); node.process_active (open1); node.process_active (open2); node.process_active (open3); node.block_processor.flush (); // bound elections, should drop after one loop ASSERT_TIMELY (1s, node.active.size () == node_config.active_elections_size); ASSERT_EQ (1, node.scheduler.size ()); } TEST (active_transactions, inactive_votes_cache) { nano::system system (1); auto & node = *system.nodes[0]; nano::block_hash latest (node.latest (nano::dev::genesis_key.pub)); nano::keypair key; auto send = nano::send_block_builder () .previous (latest) .destination (key.pub) .balance (nano::dev::constants.genesis_amount - 100) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); auto vote (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, std::vector (1, send->hash ()))); node.vote_processor.vote (vote, std::make_shared (node)); ASSERT_TIMELY (5s, node.active.inactive_votes_cache_size () == 1); node.process_active (send); node.block_processor.flush (); ASSERT_TIMELY (5s, node.ledger.block_confirmed (node.store.tx_begin_read (), send->hash ())); ASSERT_EQ (1, node.stats.count (nano::stat::type::election, nano::stat::detail::vote_cached)); } TEST (active_transactions, inactive_votes_cache_non_final) { nano::system system (1); auto & node = *system.nodes[0]; nano::block_hash latest (node.latest (nano::dev::genesis_key.pub)); nano::keypair key; auto send = nano::send_block_builder () .previous (latest) .destination (key.pub) .balance (nano::dev::constants.genesis_amount - 100) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); auto vote (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, 0, std::vector (1, send->hash ()))); // Non-final vote node.vote_processor.vote (vote, std::make_shared (node)); ASSERT_TIMELY (5s, node.active.inactive_votes_cache_size () == 1); node.process_active (send); node.block_processor.flush (); ASSERT_TIMELY (5s, node.stats.count (nano::stat::type::election, nano::stat::detail::vote_cached) == 1); auto election = node.active.election (send->qualified_root ()); ASSERT_NE (nullptr, election); ASSERT_FALSE (election->confirmed ()); ASSERT_EQ (nano::dev::constants.genesis_amount - 100, election->tally ().begin ()->first); } TEST (active_transactions, inactive_votes_cache_fork) { nano::system system (1); auto & node = *system.nodes[0]; nano::block_hash latest (node.latest (nano::dev::genesis_key.pub)); nano::keypair key; nano::send_block_builder builder; auto send1 = builder.make_block () .previous (latest) .destination (key.pub) .balance (nano::dev::constants.genesis_amount - 100) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); auto send2 = builder.make_block () .previous (latest) .destination (key.pub) .balance (nano::dev::constants.genesis_amount - 200) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); auto vote (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, std::vector (1, send1->hash ()))); node.vote_processor.vote (vote, std::make_shared (node)); auto channel1 (node.network.udp_channels.create (node.network.endpoint ())); ASSERT_TIMELY (5s, node.active.inactive_votes_cache_size () == 1); node.network.inbound (nano::publish{ nano::dev::network_params.network, send2 }, channel1); node.block_processor.flush (); ASSERT_NE (nullptr, node.block (send2->hash ())); node.scheduler.flush (); // Start election, otherwise conflicting block won't be inserted into election node.network.inbound (nano::publish{ nano::dev::network_params.network, send1 }, channel1); node.block_processor.flush (); bool confirmed (false); system.deadline_set (5s); while (!confirmed) { auto transaction (node.store.tx_begin_read ()); confirmed = node.block (send1->hash ()) != nullptr && node.ledger.block_confirmed (transaction, send1->hash ()) && node.active.empty (); ASSERT_NO_ERROR (system.poll ()); } ASSERT_EQ (1, node.stats.count (nano::stat::type::election, nano::stat::detail::vote_cached)); } TEST (active_transactions, inactive_votes_cache_existing_vote) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (node_config); nano::block_hash latest (node.latest (nano::dev::genesis_key.pub)); nano::keypair key; nano::block_builder builder; auto send = builder.send () .previous (latest) .destination (key.pub) .balance (nano::dev::constants.genesis_amount - 100 * nano::Gxrb_ratio) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); auto open = builder.state () .account (key.pub) .previous (0) .representative (key.pub) .balance (100 * nano::Gxrb_ratio) .link (send->hash ()) .sign (key.prv, key.pub) .work (*system.work.generate (key.pub)) .build_shared (); node.process_active (send); node.block_processor.add (open); node.block_processor.flush (); ASSERT_TIMELY (5s, node.active.size () == 1); auto election (node.active.election (send->qualified_root ())); ASSERT_NE (nullptr, election); ASSERT_GT (node.weight (key.pub), node.minimum_principal_weight ()); // Insert vote auto vote1 (std::make_shared (key.pub, key.prv, nano::vote::timestamp_min * 1, std::vector (1, send->hash ()))); node.vote_processor.vote (vote1, std::make_shared (node)); ASSERT_TIMELY (5s, election->votes ().size () == 2); ASSERT_EQ (1, node.stats.count (nano::stat::type::election, nano::stat::detail::vote_new)); auto last_vote1 (election->votes ()[key.pub]); ASSERT_EQ (send->hash (), last_vote1.hash); ASSERT_EQ (nano::vote::timestamp_min * 1, last_vote1.timestamp); // Attempt to change vote with inactive_votes_cache nano::unique_lock active_lock (node.active.mutex); node.active.add_inactive_votes_cache (active_lock, send->hash (), key.pub, 0); active_lock.unlock (); auto cache (node.active.find_inactive_votes_cache (send->hash ())); active_lock.lock (); ASSERT_EQ (1, cache.voters.size ()); election->insert_inactive_votes_cache (cache); // Check that election data is not changed ASSERT_EQ (2, election->votes ().size ()); auto last_vote2 (election->votes ()[key.pub]); ASSERT_EQ (last_vote1.hash, last_vote2.hash); ASSERT_EQ (last_vote1.timestamp, last_vote2.timestamp); ASSERT_EQ (last_vote1.time, last_vote2.time); ASSERT_EQ (0, node.stats.count (nano::stat::type::election, nano::stat::detail::vote_cached)); } TEST (active_transactions, inactive_votes_cache_multiple_votes) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (node_config); nano::block_hash latest (node.latest (nano::dev::genesis_key.pub)); nano::keypair key1; nano::block_builder builder; auto send1 = builder.send () .previous (latest) .destination (key1.pub) .balance (nano::dev::constants.genesis_amount - 100 * nano::Gxrb_ratio) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); auto send2 = builder.send () .previous (send1->hash ()) .destination (key1.pub) .balance (100 * nano::Gxrb_ratio) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send1->hash ())) .build_shared (); auto open = builder.state () .account (key1.pub) .previous (0) .representative (key1.pub) .balance (100 * nano::Gxrb_ratio) .link (send1->hash ()) .sign (key1.prv, key1.pub) .work (*system.work.generate (key1.pub)) .build_shared (); node.block_processor.add (send1); node.block_processor.add (send2); node.block_processor.add (open); node.block_processor.flush (); // Process votes auto vote1 (std::make_shared (key1.pub, key1.prv, 0, std::vector (1, send1->hash ()))); node.vote_processor.vote (vote1, std::make_shared (node)); auto vote2 (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, 0, std::vector (1, send1->hash ()))); node.vote_processor.vote (vote2, std::make_shared (node)); ASSERT_TIMELY (5s, node.active.find_inactive_votes_cache (send1->hash ()).voters.size () == 2); ASSERT_EQ (1, node.active.inactive_votes_cache_size ()); node.scheduler.activate (nano::dev::genesis_key.pub, node.store.tx_begin_read ()); node.scheduler.flush (); auto election = node.active.election (send1->qualified_root ()); ASSERT_NE (nullptr, election); ASSERT_EQ (3, election->votes ().size ()); // 2 votes and 1 default not_an_acount ASSERT_EQ (2, node.stats.count (nano::stat::type::election, nano::stat::detail::vote_cached)); } TEST (active_transactions, inactive_votes_cache_election_start) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (node_config); nano::block_hash latest (node.latest (nano::dev::genesis_key.pub)); nano::keypair key1, key2; nano::send_block_builder send_block_builder; nano::state_block_builder state_block_builder; auto send1 = send_block_builder.make_block () .previous (latest) .destination (key1.pub) .balance (nano::dev::constants.genesis_amount - 5000 * nano::Gxrb_ratio) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); auto send2 = send_block_builder.make_block () .previous (send1->hash ()) .destination (key2.pub) .balance (nano::dev::constants.genesis_amount - 10000 * nano::Gxrb_ratio) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send1->hash ())) .build_shared (); auto open1 = state_block_builder.make_block () .account (key1.pub) .previous (0) .representative (key1.pub) .balance (5000 * nano::Gxrb_ratio) .link (send1->hash ()) .sign (key1.prv, key1.pub) .work (*system.work.generate (key1.pub)) .build_shared (); auto open2 = state_block_builder.make_block () .account (key2.pub) .previous (0) .representative (key2.pub) .balance (5000 * nano::Gxrb_ratio) .link (send2->hash ()) .sign (key2.prv, key2.pub) .work (*system.work.generate (key2.pub)) .build_shared (); node.block_processor.add (send1); node.block_processor.add (send2); node.block_processor.add (open1); node.block_processor.add (open2); node.block_processor.flush (); ASSERT_TIMELY (5s, 5 == node.ledger.cache.block_count); ASSERT_TRUE (node.active.empty ()); ASSERT_EQ (1, node.ledger.cache.cemented_count); // These blocks will be processed later auto send3 = send_block_builder.make_block () .previous (send2->hash ()) .destination (nano::keypair ().pub) .balance (send2->balance ().number () - 1) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send2->hash ())) .build_shared (); auto send4 = send_block_builder.make_block () .previous (send3->hash ()) .destination (nano::keypair ().pub) .balance (send3->balance ().number () - 1) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send3->hash ())) .build_shared (); // Inactive votes std::vector hashes{ open1->hash (), open2->hash (), send4->hash () }; auto vote1 (std::make_shared (key1.pub, key1.prv, 0, hashes)); node.vote_processor.vote (vote1, std::make_shared (node)); ASSERT_TIMELY (5s, node.active.inactive_votes_cache_size () == 3); ASSERT_TRUE (node.active.empty ()); ASSERT_EQ (1, node.ledger.cache.cemented_count); // 2 votes are required to start election (dev network) auto vote2 (std::make_shared (key2.pub, key2.prv, 0, hashes)); node.vote_processor.vote (vote2, std::make_shared (node)); // Only open1 & open2 blocks elections should start (send4 is missing previous block in ledger) ASSERT_TIMELY (5s, 2 == node.active.size ()); // Confirm elections with weight quorum auto vote0 (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, hashes)); // Final vote for confirmation node.vote_processor.vote (vote0, std::make_shared (node)); ASSERT_TIMELY (5s, node.active.empty ()); ASSERT_TIMELY (5s, 5 == node.ledger.cache.cemented_count); // A late block arrival also checks the inactive votes cache ASSERT_TRUE (node.active.empty ()); auto send4_cache (node.active.find_inactive_votes_cache (send4->hash ())); ASSERT_EQ (3, send4_cache.voters.size ()); ASSERT_TRUE (send4_cache.status.bootstrap_started); ASSERT_TRUE (send4_cache.status.confirmed); ASSERT_TRUE (send4_cache.status.election_started); // already marked even though the block does not exist node.process_active (send3); node.block_processor.flush (); // An election is started for send6 but does not confirm ASSERT_TIMELY (5s, 1 == node.active.size ()); node.vote_processor.flush (); ASSERT_FALSE (node.block_confirmed_or_being_confirmed (node.store.tx_begin_read (), send3->hash ())); // send7 cannot be voted on but an election should be started from inactive votes ASSERT_FALSE (node.ledger.dependents_confirmed (node.store.tx_begin_read (), *send4)); node.process_active (send4); node.block_processor.flush (); ASSERT_TIMELY (5s, 7 == node.ledger.cache.cemented_count); } namespace nano { TEST (active_transactions, vote_replays) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.enable_voting = false; node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (node_config); nano::keypair key; nano::state_block_builder builder; auto send1 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - nano::Gxrb_ratio) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); ASSERT_NE (nullptr, send1); auto open1 = builder.make_block () .account (key.pub) .previous (0) .representative (key.pub) .balance (nano::Gxrb_ratio) .link (send1->hash ()) .sign (key.prv, key.pub) .work (*system.work.generate (key.pub)) .build_shared (); ASSERT_NE (nullptr, open1); node.process_active (send1); node.process_active (open1); nano::blocks_confirm (node, { send1, open1 }); ASSERT_EQ (2, node.active.size ()); // First vote is not a replay and confirms the election, second vote should be a replay since the election has confirmed but not yet removed auto vote_send1 (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, send1)); ASSERT_EQ (nano::vote_code::vote, node.active.vote (vote_send1)); ASSERT_EQ (2, node.active.size ()); ASSERT_EQ (nano::vote_code::replay, node.active.vote (vote_send1)); // Wait until the election is removed, at which point the vote is still a replay since it's been recently confirmed ASSERT_TIMELY (3s, node.active.size () == 1); ASSERT_EQ (nano::vote_code::replay, node.active.vote (vote_send1)); // Open new account auto vote_open1 (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, open1)); ASSERT_EQ (nano::vote_code::vote, node.active.vote (vote_open1)); ASSERT_EQ (nano::vote_code::replay, node.active.vote (vote_open1)); ASSERT_TIMELY (3s, node.active.empty ()); ASSERT_EQ (nano::vote_code::replay, node.active.vote (vote_open1)); ASSERT_EQ (nano::Gxrb_ratio, node.ledger.weight (key.pub)); auto send2 = builder.make_block () .account (key.pub) .previous (open1->hash ()) .representative (key.pub) .balance (nano::Gxrb_ratio - 1) .link (key.pub) .sign (key.prv, key.pub) .work (*system.work.generate (open1->hash ())) .build_shared (); ASSERT_NE (nullptr, send2); node.process_active (send2); nano::blocks_confirm (node, { send2 }); ASSERT_EQ (1, node.active.size ()); auto vote1_send2 (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, send2)); auto vote2_send2 (std::make_shared (key.pub, key.prv, 0, send2)); ASSERT_EQ (nano::vote_code::vote, node.active.vote (vote2_send2)); ASSERT_EQ (1, node.active.size ()); ASSERT_EQ (nano::vote_code::replay, node.active.vote (vote2_send2)); ASSERT_EQ (1, node.active.size ()); ASSERT_EQ (nano::vote_code::vote, node.active.vote (vote1_send2)); ASSERT_EQ (1, node.active.size ()); ASSERT_EQ (nano::vote_code::replay, node.active.vote (vote1_send2)); ASSERT_TIMELY (3s, node.active.empty ()); ASSERT_EQ (0, node.active.size ()); ASSERT_EQ (nano::vote_code::replay, node.active.vote (vote1_send2)); ASSERT_EQ (nano::vote_code::replay, node.active.vote (vote2_send2)); // Removing blocks as recently confirmed makes every vote indeterminate { nano::lock_guard guard (node.active.mutex); node.active.recently_confirmed.clear (); } ASSERT_EQ (nano::vote_code::indeterminate, node.active.vote (vote_send1)); ASSERT_EQ (nano::vote_code::indeterminate, node.active.vote (vote_open1)); ASSERT_EQ (nano::vote_code::indeterminate, node.active.vote (vote1_send2)); ASSERT_EQ (nano::vote_code::indeterminate, node.active.vote (vote2_send2)); } } // Tests that blocks are correctly cleared from the duplicate filter for unconfirmed elections TEST (active_transactions, dropped_cleanup) { nano::system system; nano::node_flags flags; flags.disable_request_loop = true; auto & node (*system.add_node (flags)); // Add to network filter to ensure proper cleanup after the election is dropped std::vector block_bytes; { nano::vectorstream stream (block_bytes); nano::dev::genesis->serialize (stream); } ASSERT_FALSE (node.network.publish_filter.apply (block_bytes.data (), block_bytes.size ())); ASSERT_TRUE (node.network.publish_filter.apply (block_bytes.data (), block_bytes.size ())); node.block_confirm (nano::dev::genesis); node.scheduler.flush (); auto election = node.active.election (nano::dev::genesis->qualified_root ()); ASSERT_NE (nullptr, election); // Not yet removed ASSERT_TRUE (node.network.publish_filter.apply (block_bytes.data (), block_bytes.size ())); ASSERT_EQ (1, node.active.blocks.count (nano::dev::genesis->hash ())); // Now simulate dropping the election ASSERT_FALSE (election->confirmed ()); node.active.erase (*nano::dev::genesis); // The filter must have been cleared ASSERT_FALSE (node.network.publish_filter.apply (block_bytes.data (), block_bytes.size ())); // An election was recently dropped ASSERT_EQ (1, node.stats.count (nano::stat::type::election, nano::stat::detail::election_drop_all)); // Block cleared from active ASSERT_EQ (0, node.active.blocks.count (nano::dev::genesis->hash ())); // Repeat test for a confirmed election ASSERT_TRUE (node.network.publish_filter.apply (block_bytes.data (), block_bytes.size ())); node.block_confirm (nano::dev::genesis); node.scheduler.flush (); election = node.active.election (nano::dev::genesis->qualified_root ()); ASSERT_NE (nullptr, election); election->force_confirm (); ASSERT_TRUE (election->confirmed ()); node.active.erase (*nano::dev::genesis); // The filter should not have been cleared ASSERT_TRUE (node.network.publish_filter.apply (block_bytes.data (), block_bytes.size ())); // Not dropped ASSERT_EQ (1, node.stats.count (nano::stat::type::election, nano::stat::detail::election_drop_all)); // Block cleared from active ASSERT_EQ (0, node.active.blocks.count (nano::dev::genesis->hash ())); } TEST (active_transactions, republish_winner) { nano::system system; nano::node_config node_config{ nano::get_available_port (), system.logging }; node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node1 = *system.add_node (node_config); node_config.peering_port = nano::get_available_port (); auto & node2 = *system.add_node (node_config); nano::keypair key; nano::state_block_builder builder; auto send1 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - nano::Gxrb_ratio) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); node1.process_active (send1); node1.block_processor.flush (); ASSERT_TIMELY (3s, node2.stats.count (nano::stat::type::message, nano::stat::detail::publish, nano::stat::dir::in) == 1); // Several forks for (auto i (0); i < 5; i++) { auto fork = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 1 - i) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); node1.process_active (fork); } node1.block_processor.flush (); ASSERT_TIMELY (3s, !node1.active.empty ()); ASSERT_EQ (1, node2.stats.count (nano::stat::type::message, nano::stat::detail::publish, nano::stat::dir::in)); // Process new fork with vote to change winner auto fork = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 2 * nano::Gxrb_ratio) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); node1.process_active (fork); node1.block_processor.flush (); auto election = node1.active.election (fork->qualified_root ()); ASSERT_NE (nullptr, election); auto vote = std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, std::vector{ fork->hash () }); node1.vote_processor.vote (vote, std::make_shared (node1)); node1.vote_processor.flush (); node1.block_processor.flush (); ASSERT_TIMELY (3s, election->confirmed ()); ASSERT_EQ (fork->hash (), election->status.winner->hash ()); ASSERT_TIMELY (3s, node2.block_confirmed (fork->hash ())); } TEST (active_transactions, fork_filter_cleanup) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node1 (*system.add_node (node_config)); nano::keypair key; nano::state_block_builder builder; auto send1 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - nano::Gxrb_ratio) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); std::vector block_bytes; { nano::vectorstream stream (block_bytes); send1->serialize (stream); } // Generate 10 forks to prevent new block insertion to election for (auto i (0); i < 10; i++) { auto fork = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 1 - i) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); node1.process_active (fork); node1.block_processor.flush (); node1.scheduler.flush (); } ASSERT_EQ (1, node1.active.size ()); // Process correct block node_config.peering_port = nano::get_available_port (); auto & node2 (*system.add_node (node_config)); node2.network.flood_block (send1); ASSERT_TIMELY (3s, node1.stats.count (nano::stat::type::message, nano::stat::detail::publish, nano::stat::dir::in) > 0); node1.block_processor.flush (); std::this_thread::sleep_for (50ms); // Block is erased from the duplicate filter ASSERT_FALSE (node1.network.publish_filter.apply (block_bytes.data (), block_bytes.size ())); auto election (node1.active.election (send1->qualified_root ())); ASSERT_NE (nullptr, election); ASSERT_EQ (10, election->blocks ().size ()); } TEST (active_transactions, fork_replacement_tally) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node1 (*system.add_node (node_config)); size_t reps_count = 20; size_t const max_blocks = 10; std::vector keys (reps_count); auto latest (nano::dev::genesis->hash ()); auto balance (nano::dev::constants.genesis_amount); auto amount (node1.minimum_principal_weight ()); nano::state_block_builder builder; // Create 20 representatives & confirm blocks for (auto i (0); i < reps_count; i++) { balance -= amount + i; auto send = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (latest) .representative (nano::dev::genesis_key.pub) .balance (balance) .link (keys[i].pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); node1.process_active (send); latest = send->hash (); auto open = builder.make_block () .account (keys[i].pub) .previous (0) .representative (keys[i].pub) .balance (amount + i) .link (send->hash ()) .sign (keys[i].prv, keys[i].pub) .work (*system.work.generate (keys[i].pub)) .build_shared (); node1.process_active (open); // Confirmation auto vote (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, std::vector{ send->hash (), open->hash () })); node1.vote_processor.vote (vote, std::make_shared (node1)); } node1.block_processor.flush (); ASSERT_TIMELY (5s, node1.ledger.cache.cemented_count == 1 + 2 * reps_count); nano::keypair key; auto send_last = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (latest) .representative (nano::dev::genesis_key.pub) .balance (balance - 2 * nano::Gxrb_ratio) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); // Forks without votes for (auto i (0); i < reps_count; i++) { auto fork = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (latest) .representative (nano::dev::genesis_key.pub) .balance (balance - nano::Gxrb_ratio - i) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); node1.process_active (fork); } node1.block_processor.flush (); ASSERT_TIMELY (3s, !node1.active.empty ()); // Check overflow of blocks auto election (node1.active.election (send_last->qualified_root ())); ASSERT_NE (nullptr, election); ASSERT_EQ (max_blocks, election->blocks ().size ()); // Generate forks with votes to prevent new block insertion to election for (auto i (0); i < reps_count; i++) { auto fork = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (latest) .representative (nano::dev::genesis_key.pub) .balance (balance - 1 - i) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (latest)) .build_shared (); auto vote (std::make_shared (keys[i].pub, keys[i].prv, 0, std::vector{ fork->hash () })); node1.vote_processor.vote (vote, std::make_shared (node1)); node1.vote_processor.flush (); node1.process_active (fork); } node1.block_processor.flush (); // Check overflow of blocks ASSERT_EQ (max_blocks, election->blocks ().size ()); // Check that only max weight blocks remains (and start winner) auto votes1 (election->votes ()); ASSERT_EQ (max_blocks, votes1.size ()); for (auto i (max_blocks + 1); i < reps_count; i++) { ASSERT_TRUE (votes1.find (keys[i].pub) != votes1.end ()); } // Process correct block node_config.peering_port = nano::get_available_port (); auto & node2 (*system.add_node (node_config)); node2.network.flood_block (send_last); ASSERT_TIMELY (3s, node1.stats.count (nano::stat::type::message, nano::stat::detail::publish, nano::stat::dir::in) > 0); node1.block_processor.flush (); std::this_thread::sleep_for (50ms); // Correct block without votes is ignored auto blocks1 (election->blocks ()); ASSERT_EQ (max_blocks, blocks1.size ()); ASSERT_FALSE (blocks1.find (send_last->hash ()) != blocks1.end ()); // Process vote for correct block & replace existing lowest tally block auto vote (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, 0, std::vector{ send_last->hash () })); node1.vote_processor.vote (vote, std::make_shared (node1)); node1.vote_processor.flush (); node2.network.flood_block (send_last); ASSERT_TIMELY (3s, node1.stats.count (nano::stat::type::message, nano::stat::detail::publish, nano::stat::dir::in) > 1); node1.block_processor.flush (); std::this_thread::sleep_for (50ms); auto blocks2 (election->blocks ()); ASSERT_EQ (max_blocks, blocks2.size ()); ASSERT_TRUE (blocks2.find (send_last->hash ()) != blocks2.end ()); auto votes2 (election->votes ()); ASSERT_EQ (max_blocks, votes2.size ()); for (auto i (max_blocks + 2); i < reps_count; i++) { ASSERT_TRUE (votes2.find (keys[i].pub) != votes2.end ()); } ASSERT_FALSE (votes2.find (keys[max_blocks].pub) != votes2.end ()); ASSERT_FALSE (votes2.find (keys[max_blocks + 1].pub) != votes2.end ()); ASSERT_TRUE (votes2.find (nano::dev::genesis_key.pub) != votes2.end ()); } namespace nano { // Blocks that won an election must always be seen as confirming or cemented TEST (active_transactions, confirmation_consistency) { nano::system system; nano::node_config node_config (nano::get_available_port (), system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (node_config); system.wallet (0)->insert_adhoc (nano::dev::genesis_key.prv); for (unsigned i = 0; i < 10; ++i) { auto block (system.wallet (0)->send_action (nano::dev::genesis_key.pub, nano::public_key (), node.config.receive_minimum.number ())); ASSERT_NE (nullptr, block); system.deadline_set (5s); while (!node.ledger.block_confirmed (node.store.tx_begin_read (), block->hash ())) { node.scheduler.activate (nano::dev::genesis_key.pub, node.store.tx_begin_read ()); ASSERT_NO_ERROR (system.poll (5ms)); } ASSERT_NO_ERROR (system.poll_until_true (1s, [&node, &block, i] { nano::lock_guard guard (node.active.mutex); EXPECT_EQ (i + 1, node.active.recently_confirmed.size ()); EXPECT_EQ (block->qualified_root (), node.active.recently_confirmed.back ().first); return i + 1 == node.active.recently_cemented.size (); // done after a callback })); } } } TEST (active_transactions, confirm_new) { nano::system system (1); auto & node1 = *system.nodes[0]; auto send = nano::send_block_builder () .previous (nano::dev::genesis->hash ()) .destination (nano::public_key ()) .balance (nano::dev::constants.genesis_amount - 100) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); node1.process_active (send); node1.block_processor.flush (); node1.scheduler.flush (); ASSERT_EQ (1, node1.active.size ()); auto & node2 = *system.add_node (); // Add key to node2 system.wallet (1)->insert_adhoc (nano::dev::genesis_key.prv); // Let node2 know about the block ASSERT_TIMELY (5s, node2.block (send->hash ())); // Wait confirmation ASSERT_TIMELY (5s, node1.ledger.cache.cemented_count == 2 && node2.ledger.cache.cemented_count == 2); } // Ensures votes are tallied on election::publish even if no vote is inserted through inactive_votes_cache TEST (active_transactions, conflicting_block_vote_existing_election) { nano::system system; nano::node_flags node_flags; node_flags.disable_request_loop = true; auto & node = *system.add_node (node_flags); nano::keypair key; nano::state_block_builder builder; auto send = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 100) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); auto fork = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 200) .link (key.pub) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); auto vote_fork (std::make_shared (nano::dev::genesis_key.pub, nano::dev::genesis_key.prv, nano::vote::timestamp_max, fork)); ASSERT_EQ (nano::process_result::progress, node.process_local (send).code); node.scheduler.flush (); ASSERT_EQ (1, node.active.size ()); // Vote for conflicting block, but the block does not yet exist in the ledger node.active.vote (vote_fork); // Block now gets processed ASSERT_EQ (nano::process_result::fork, node.process_local (fork).code); // Election must be confirmed auto election (node.active.election (fork->qualified_root ())); ASSERT_NE (nullptr, election); ASSERT_TIMELY (3s, election->confirmed ()); } TEST (active_transactions, activate_account_chain) { nano::system system; nano::node_flags flags; nano::node_config config (nano::get_available_port (), system.logging); config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (config, flags); nano::keypair key; nano::state_block_builder builder; auto send = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .link (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 1) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build (); auto send2 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (send->hash ()) .representative (nano::dev::genesis_key.pub) .link (key.pub) .balance (nano::dev::constants.genesis_amount - 2) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send->hash ())) .build (); auto send3 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (send2->hash ()) .representative (nano::dev::genesis_key.pub) .link (key.pub) .balance (nano::dev::constants.genesis_amount - 3) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send2->hash ())) .build (); auto open = builder.make_block () .account (key.pub) .previous (0) .representative (key.pub) .link (send2->hash ()) .balance (1) .sign (key.prv, key.pub) .work (*system.work.generate (key.pub)) .build (); auto receive = builder.make_block () .account (key.pub) .previous (open->hash ()) .representative (key.pub) .link (send3->hash ()) .balance (2) .sign (key.prv, key.pub) .work (*system.work.generate (open->hash ())) .build (); ASSERT_EQ (nano::process_result::progress, node.process (*send).code); ASSERT_EQ (nano::process_result::progress, node.process (*send2).code); ASSERT_EQ (nano::process_result::progress, node.process (*send3).code); ASSERT_EQ (nano::process_result::progress, node.process (*open).code); ASSERT_EQ (nano::process_result::progress, node.process (*receive).code); node.scheduler.activate (nano::dev::genesis_key.pub, node.store.tx_begin_read ()); node.scheduler.flush (); auto election1 = node.active.election (send->qualified_root ()); ASSERT_EQ (1, node.active.size ()); ASSERT_EQ (1, election1->blocks ().count (send->hash ())); node.scheduler.activate (nano::dev::genesis_key.pub, node.store.tx_begin_read ()); auto election2 = node.active.election (send->qualified_root ()); ASSERT_EQ (election2, election1); election1->force_confirm (); ASSERT_TIMELY (3s, node.block_confirmed (send->hash ())); // On cementing, the next election is started ASSERT_TIMELY (3s, node.active.active (send2->qualified_root ())); node.scheduler.activate (nano::dev::genesis_key.pub, node.store.tx_begin_read ()); auto election3 = node.active.election (send2->qualified_root ()); ASSERT_NE (nullptr, election3); ASSERT_EQ (1, election3->blocks ().count (send2->hash ())); election3->force_confirm (); ASSERT_TIMELY (3s, node.block_confirmed (send2->hash ())); // On cementing, the next election is started ASSERT_TIMELY (3s, node.active.active (open->qualified_root ())); ASSERT_TIMELY (3s, node.active.active (send3->qualified_root ())); node.scheduler.activate (nano::dev::genesis_key.pub, node.store.tx_begin_read ()); auto election4 = node.active.election (send3->qualified_root ()); ASSERT_NE (nullptr, election4); ASSERT_EQ (1, election4->blocks ().count (send3->hash ())); node.scheduler.activate (key.pub, node.store.tx_begin_read ()); auto election5 = node.active.election (open->qualified_root ()); ASSERT_NE (nullptr, election5); ASSERT_EQ (1, election5->blocks ().count (open->hash ())); election5->force_confirm (); ASSERT_TIMELY (3s, node.block_confirmed (open->hash ())); // Until send3 is also confirmed, the receive block should not activate std::this_thread::sleep_for (200ms); node.scheduler.activate (key.pub, node.store.tx_begin_read ()); election4->force_confirm (); ASSERT_TIMELY (3s, node.block_confirmed (send3->hash ())); ASSERT_TIMELY (3s, node.active.active (receive->qualified_root ())); } TEST (active_transactions, activate_inactive) { nano::system system; nano::node_flags flags; nano::node_config config (nano::get_available_port (), system.logging); config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (config, flags); nano::keypair key; nano::state_block_builder builder; auto send = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .link (key.pub) .balance (nano::dev::constants.genesis_amount - 1) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); auto send2 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (send->hash ()) .representative (nano::dev::genesis_key.pub) .link (nano::keypair ().pub) .balance (nano::dev::constants.genesis_amount - 2) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send->hash ())) .build_shared (); auto open = builder.make_block () .account (key.pub) .previous (0) .representative (key.pub) .link (send->hash ()) .balance (1) .sign (key.prv, key.pub) .work (*system.work.generate (key.pub)) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*send).code); ASSERT_EQ (nano::process_result::progress, node.process (*send2).code); ASSERT_EQ (nano::process_result::progress, node.process (*open).code); node.block_confirm (send2); auto election = node.active.election (send2->qualified_root ()); ASSERT_NE (nullptr, election); election->force_confirm (); ASSERT_TIMELY (3s, !node.confirmation_height_processor.is_processing_added_block (send2->hash ())); ASSERT_TRUE (node.block_confirmed (send2->hash ())); ASSERT_TRUE (node.block_confirmed (send->hash ())); ASSERT_EQ (1, node.stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::inactive_conf_height, nano::stat::dir::out)); ASSERT_EQ (1, node.stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::active_quorum, nano::stat::dir::out)); ASSERT_EQ (0, node.stats.count (nano::stat::type::confirmation_observer, nano::stat::detail::active_conf_height, nano::stat::dir::out)); // The first block was not active so no activation takes place ASSERT_FALSE (node.active.active (open->qualified_root ()) || node.block_confirmed_or_being_confirmed (node.store.tx_begin_read (), open->hash ())); } namespace nano { TEST (active_transactions, pessimistic_elections) { nano::system system; nano::node_flags flags; nano::node_config config (nano::get_available_port (), system.logging); config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node = *system.add_node (config, flags); nano::keypair key; nano::state_block_builder builder; auto send = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .link (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 1) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*send).code); auto send2 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (send->hash ()) .representative (nano::dev::genesis_key.pub) .link (key.pub) .balance (nano::dev::constants.genesis_amount - 2) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send->hash ())) .build (); ASSERT_EQ (nano::process_result::progress, node.process (*send2).code); auto open = builder.make_block () .account (key.pub) .previous (0) .representative (key.pub) .link (send2->hash ()) .balance (1) .sign (key.prv, key.pub) .work (*system.work.generate (key.pub)) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*open).code); // This should only cement the first block in genesis account uint64_t election_count = 0; // Make dummy election with winner. { nano::election election1 ( node, send, [] (auto const &) {}, [] (auto const &) {}, nano::election_behavior::normal); nano::election election2 ( node, open, [] (auto const &) {}, [] (auto const &) {}, nano::election_behavior::normal); node.active.add_expired_optimistic_election (election1); node.active.add_expired_optimistic_election (election2); } node.active.confirm_expired_frontiers_pessimistically (node.store.tx_begin_read (), 100, election_count); ASSERT_EQ (1, election_count); ASSERT_EQ (2, node.active.expired_optimistic_election_infos.size ()); ASSERT_EQ (2, node.active.expired_optimistic_election_infos.size ()); auto election_started_it = node.active.expired_optimistic_election_infos.get ().begin (); ASSERT_EQ (election_started_it->account, nano::dev::genesis->account ()); ASSERT_EQ (election_started_it->election_started, true); ASSERT_EQ ((++election_started_it)->election_started, false); // No new elections should get started yet node.active.confirm_expired_frontiers_pessimistically (node.store.tx_begin_read (), 100, election_count); ASSERT_EQ (1, election_count); ASSERT_EQ (2, node.active.expired_optimistic_election_infos.size ()); ASSERT_EQ (node.active.expired_optimistic_election_infos_size, node.active.expired_optimistic_election_infos.size ()); ASSERT_EQ (1, node.active.size ()); auto election = node.active.election (send->qualified_root ()); ASSERT_NE (nullptr, election); election->force_confirm (); ASSERT_TIMELY (3s, node.block_confirmed (send->hash ()) && !node.confirmation_height_processor.is_processing_added_block (send->hash ())); nano::confirmation_height_info genesis_confirmation_height_info; nano::confirmation_height_info key1_confirmation_height_info; { auto transaction = node.store.tx_begin_read (); node.store.confirmation_height.get (transaction, nano::dev::genesis->account (), genesis_confirmation_height_info); ASSERT_EQ (2, genesis_confirmation_height_info.height); node.store.confirmation_height.get (transaction, key.pub, key1_confirmation_height_info); ASSERT_EQ (0, key1_confirmation_height_info.height); } // Activation of cemented frontier successor should get started after the first pessimistic block is confirmed ASSERT_TIMELY (10s, node.active.active (send2->qualified_root ())); node.active.confirm_expired_frontiers_pessimistically (node.store.tx_begin_read (), 100, election_count); ASSERT_EQ (1, election_count); ASSERT_EQ (2, node.active.expired_optimistic_election_infos.size ()); // Confirm it election = node.active.election (send2->qualified_root ()); ASSERT_NE (nullptr, election); election->force_confirm (); ASSERT_TIMELY (3s, node.block_confirmed (send2->hash ())); { auto transaction = node.store.tx_begin_read (); node.store.confirmation_height.get (transaction, nano::dev::genesis->account (), genesis_confirmation_height_info); ASSERT_EQ (3, genesis_confirmation_height_info.height); node.store.confirmation_height.get (transaction, key.pub, key1_confirmation_height_info); ASSERT_EQ (0, key1_confirmation_height_info.height); } // Wait until activation of destination account is done. ASSERT_TIMELY (10s, node.active.active (open->qualified_root ())); // Election count should not increase, but the elections should be marked as started for that account afterwards ASSERT_EQ (election_started_it->election_started, false); node.active.confirm_expired_frontiers_pessimistically (node.store.tx_begin_read (), 100, election_count); ASSERT_EQ (1, election_count); ASSERT_EQ (2, node.active.expired_optimistic_election_infos.size ()); node.active.confirm_expired_frontiers_pessimistically (node.store.tx_begin_read (), 100, election_count); election = node.active.election (open->qualified_root ()); ASSERT_NE (nullptr, election); election->force_confirm (); ASSERT_TIMELY (3s, node.block_confirmed (open->hash ())); { auto transaction = node.store.tx_begin_read (); node.store.confirmation_height.get (transaction, nano::dev::genesis->account (), genesis_confirmation_height_info); ASSERT_EQ (3, genesis_confirmation_height_info.height); node.store.confirmation_height.get (transaction, key.pub, key1_confirmation_height_info); ASSERT_EQ (1, key1_confirmation_height_info.height); } // Sanity check that calling it again on a fully cemented chain has no adverse effects. node.active.confirm_expired_frontiers_pessimistically (node.store.tx_begin_read (), 100, election_count); ASSERT_EQ (1, election_count); ASSERT_EQ (2, node.active.expired_optimistic_election_infos.size ()); } } TEST (active_transactions, list_active) { nano::system system (1); auto & node = *system.nodes[0]; nano::keypair key; nano::state_block_builder builder; auto send = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .link (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - 1) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*send).code); auto send2 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (send->hash ()) .representative (nano::dev::genesis_key.pub) .link (key.pub) .balance (nano::dev::constants.genesis_amount - 2) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send->hash ())) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*send2).code); auto open = builder.make_block () .account (key.pub) .previous (0) .representative (key.pub) .link (send2->hash ()) .balance (1) .sign (key.prv, key.pub) .work (*system.work.generate (key.pub)) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*open).code); nano::blocks_confirm (node, { send, send2, open }); ASSERT_EQ (3, node.active.size ()); ASSERT_EQ (1, node.active.list_active (1).size ()); ASSERT_EQ (2, node.active.list_active (2).size ()); ASSERT_EQ (3, node.active.list_active (3).size ()); ASSERT_EQ (3, node.active.list_active (4).size ()); ASSERT_EQ (3, node.active.list_active (99999).size ()); ASSERT_EQ (3, node.active.list_active ().size ()); auto active = node.active.list_active (); } TEST (active_transactions, vacancy) { nano::system system; nano::node_config config{ nano::get_available_port (), system.logging }; config.active_elections_size = 1; auto & node = *system.add_node (config); nano::state_block_builder builder; auto send = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .link (nano::dev::genesis_key.pub) .balance (nano::dev::constants.genesis_amount - nano::Gxrb_ratio) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); std::atomic updated = false; node.active.vacancy_update = [&updated] () { updated = true; }; ASSERT_EQ (nano::process_result::progress, node.process (*send).code); ASSERT_EQ (1, node.active.vacancy ()); ASSERT_EQ (0, node.active.size ()); node.scheduler.activate (nano::dev::genesis_key.pub, node.store.tx_begin_read ()); ASSERT_TIMELY (1s, updated); updated = false; ASSERT_EQ (0, node.active.vacancy ()); ASSERT_EQ (1, node.active.size ()); auto election1 = node.active.election (send->qualified_root ()); ASSERT_NE (nullptr, election1); election1->force_confirm (); ASSERT_TIMELY (1s, updated); ASSERT_EQ (1, node.active.vacancy ()); ASSERT_EQ (0, node.active.size ()); } // Ensure transactions in excess of capacity are removed in fifo order TEST (active_transactions, fifo) { nano::system system; nano::node_config config{ nano::get_available_port (), system.logging }; config.active_elections_size = 1; auto & node = *system.add_node (config); nano::keypair key0; nano::keypair key1; nano::state_block_builder builder; // Construct two pending entries that can be received simultaneously auto send0 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (nano::dev::genesis->hash ()) .representative (nano::dev::genesis_key.pub) .link (key0.pub) .balance (nano::dev::constants.genesis_amount - 1) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (nano::dev::genesis->hash ())) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*send0).code); nano::blocks_confirm (node, { send0 }, true); ASSERT_TIMELY (1s, node.block_confirmed (send0->hash ())); ASSERT_TIMELY (1s, node.active.empty ()); auto send1 = builder.make_block () .account (nano::dev::genesis_key.pub) .previous (send0->hash ()) .representative (nano::dev::genesis_key.pub) .link (key1.pub) .balance (nano::dev::constants.genesis_amount - 2) .sign (nano::dev::genesis_key.prv, nano::dev::genesis_key.pub) .work (*system.work.generate (send0->hash ())) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*send1).code); nano::blocks_confirm (node, { send1 }, true); ASSERT_TIMELY (1s, node.block_confirmed (send1->hash ())); ASSERT_TIMELY (1s, node.active.empty ()); auto receive0 = builder.make_block () .account (key0.pub) .previous (0) .representative (nano::dev::genesis_key.pub) .link (send0->hash ()) .balance (1) .sign (key0.prv, key0.pub) .work (*system.work.generate (key0.pub)) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*receive0).code); auto receive1 = builder.make_block () .account (key1.pub) .previous (0) .representative (nano::dev::genesis_key.pub) .link (send1->hash ()) .balance (1) .sign (key1.prv, key1.pub) .work (*system.work.generate (key1.pub)) .build_shared (); ASSERT_EQ (nano::process_result::progress, node.process (*receive1).code); node.scheduler.manual (receive0); // Ensure first transaction becomes active ASSERT_TIMELY (1s, node.active.election (receive0->qualified_root ()) != nullptr); node.scheduler.manual (receive1); // Ensure second transaction becomes active ASSERT_TIMELY (1s, node.active.election (receive1->qualified_root ()) != nullptr); // Ensure excess transactions get trimmed ASSERT_TIMELY (1s, node.active.size () == 1); // Ensure overflow stats have been incremented ASSERT_EQ (1, node.stats.count (nano::stat::type::election, nano::stat::detail::election_drop_overflow)); // Ensure the surviving transaction is the least recently inserted ASSERT_TIMELY (1s, node.active.election (receive1->qualified_root ()) != nullptr); } ",16339,True,3836.819205433614,median "// Copyright (c) 2017-2018, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include ""device_ledger.hpp"" #include ""log.hpp"" #include ""ringct/rctOps.h"" #include ""cryptonote_basic/account.h"" #include ""cryptonote_basic/subaddress_index.h"" #include #include namespace hw { namespace ledger { #ifdef WITH_DEVICE_LEDGER #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY ""device.ledger"" /* ===================================================================== */ /* === Debug ==== */ /* ===================================================================== */ #ifdef WIN32 static char *pcsc_stringify_error(LONG rv) { static __thread char out[20]; sprintf_s(out, sizeof(out), ""0x%08lX"", rv); return out; } #endif void set_apdu_verbose(bool verbose) { apdu_verbose = verbose; } #define TRACKD MTRACE(""hw"") #define ASSERT_RV(rv) CHECK_AND_ASSERT_THROW_MES((rv)==SCARD_S_SUCCESS, ""Fail SCard API : ("" << (rv) << "") ""<< pcsc_stringify_error(rv)<<"" Device=""<id<<"", hCard=""<buffer_send[0], this->buffer_send[1], this->buffer_send[2], this->buffer_send[3], this->buffer_send[4] ); const size_t len = strlen(strbuffer); buffer_to_str(strbuffer+len, sizeof(strbuffer)-len, (char*)(this->buffer_send+5), this->length_send-5); MDEBUG( ""CMD :"" << strbuffer); } } void device_ledger::logRESP() { if (apdu_verbose) { char strbuffer[1024]; snprintf(strbuffer, sizeof(strbuffer), ""%.02x%.02x "", this->buffer_recv[this->length_recv-2], this->buffer_recv[this->length_recv-1] ); const size_t len = strlen(strbuffer); buffer_to_str(strbuffer+len, sizeof(strbuffer)-len, (char*)(this->buffer_recv), this->length_recv-2); MDEBUG( ""RESP :"" << strbuffer); } } /* -------------------------------------------------------------- */ device_ledger::device_ledger() { this->id = device_id++; this->hCard = 0; this->hContext = 0; this->reset_buffer(); this->mode = NONE; this->has_view_key = false; MDEBUG( ""Device ""<id <<"" Created""); } device_ledger::~device_ledger() { this->release(); MDEBUG( ""Device ""<id <<"" Destroyed""); } /* ======================================================================= */ /* LOCKER */ /* ======================================================================= */ //automatic lock one more level on device ensuring the current thread is allowed to use it #define AUTO_LOCK_CMD() \\ /* lock both mutexes without deadlock*/ \\ boost::lock(device_locker, command_locker); \\ /* make sure both already-locked mutexes are unlocked at the end of scope */ \\ boost::lock_guard lock1(device_locker, boost::adopt_lock); \\ boost::lock_guard lock2(command_locker, boost::adopt_lock) //lock the device for a long sequence void device_ledger::lock(void) { MDEBUG( ""Ask for LOCKING for device ""<name << "" in thread ""); device_locker.lock(); MDEBUG( ""Device ""<name << "" LOCKed""); } //lock the device for a long sequence bool device_ledger::try_lock(void) { MDEBUG( ""Ask for LOCKING(try) for device ""<name << "" in thread ""); bool r = device_locker.try_lock(); if (r) { MDEBUG( ""Device ""<name << "" LOCKed(try)""); } else { MDEBUG( ""Device ""<name << "" not LOCKed(try)""); } return r; } //lock the device for a long sequence void device_ledger::unlock(void) { try { MDEBUG( ""Ask for UNLOCKING for device ""<name << "" in thread ""); } catch (...) { } device_locker.unlock(); MDEBUG( ""Device ""<name << "" UNLOCKed""); } /* ======================================================================= */ /* MISC */ /* ======================================================================= */ int device_ledger::set_command_header(BYTE ins, BYTE p1, BYTE p2) { reset_buffer(); int offset = 0; this->buffer_send[0] = 0x00; this->buffer_send[1] = ins; this->buffer_send[2] = p1; this->buffer_send[3] = p2; this->buffer_send[4] = 0x00; return 5; } int device_ledger::set_command_header_noopt(BYTE ins, BYTE p1, BYTE p2) { int offset = set_command_header(ins, p1, p2); //options this->buffer_send[offset++] = 0; this->buffer_send[4] = offset - 5; return offset; } void device_ledger::send_simple(BYTE ins, BYTE p1) { this->length_send = set_command_header_noopt(ins, p1); this->exchange(); } bool device_ledger::reset() { send_simple(INS_RESET); return true; } unsigned int device_ledger::exchange(unsigned int ok, unsigned int mask) { LONG rv; unsigned int sw; ASSERT_T0(this->length_send <= BUFFER_SEND_SIZE); logCMD(); this->length_recv = BUFFER_RECV_SIZE; rv = SCardTransmit(this->hCard, SCARD_PCI_T0, this->buffer_send, this->length_send, NULL, this->buffer_recv, &this->length_recv); ASSERT_RV(rv); ASSERT_T0(this->length_recv >= 2); ASSERT_T0(this->length_recv <= BUFFER_RECV_SIZE); logRESP(); sw = (this->buffer_recv[this->length_recv-2]<<8) | this->buffer_recv[this->length_recv-1]; ASSERT_SW(sw,ok,msk); return sw; } void device_ledger::reset_buffer() { this->length_send = 0; memset(this->buffer_send, 0, BUFFER_SEND_SIZE); this->length_recv = 0; memset(this->buffer_recv, 0, BUFFER_RECV_SIZE); } /* ======================================================================= */ /* SETUP/TEARDOWN */ /* ======================================================================= */ bool device_ledger::set_name(const std::string & name) { this->name = name; return true; } const std::string device_ledger::get_name() const { if (this->full_name.empty() || (this->hCard == 0)) { return std::string(""name).append("">""); } return this->full_name; } bool device_ledger::init(void) { #ifdef DEBUG_HWDEVICE this->controle_device = &hw::get_device(""default""); #endif LONG rv; this->release(); rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM,0,0, &this->hContext); ASSERT_RV(rv); MDEBUG( ""Device ""<id <<"" SCardContext created: hContext=""<hContext); this->hCard = 0; return true; } bool device_ledger::release() { this->disconnect(); if (this->hContext) { SCardReleaseContext(this->hContext); MDEBUG( ""Device ""<id <<"" SCardContext released: hContext=""<hContext); this->hContext = 0; this->full_name.clear(); } return true; } bool device_ledger::connect(void) { BYTE pbAtr[MAX_ATR_SIZE]; LPSTR mszReaders; DWORD dwReaders; LONG rv; DWORD dwState, dwProtocol, dwAtrLen, dwReaderLen; this->disconnect(); #ifdef SCARD_AUTOALLOCATE dwReaders = SCARD_AUTOALLOCATE; rv = SCardListReaders(this->hContext, NULL, (LPSTR)&mszReaders, &dwReaders); #else dwReaders = 0; rv = SCardListReaders(this->hContext, NULL, NULL, &dwReaders); if (rv != SCARD_S_SUCCESS) return false; mszReaders = (LPSTR)calloc(dwReaders, sizeof(char)); rv = SCardListReaders(this->hContext, NULL, mszReaders, &dwReaders); #endif if (rv == SCARD_S_SUCCESS) { char* p; const char* prefix = this->name.c_str(); p = mszReaders; MDEBUG( ""Looking for "" << std::string(prefix)); while (*p) { MDEBUG( ""Device Found: "" << std::string(p)); if ((strncmp(prefix, p, strlen(prefix))==0)) { MDEBUG( ""Device Match: "" << std::string(p)); if ((rv = SCardConnect(this->hContext, p, SCARD_SHARE_EXCLUSIVE, SCARD_PROTOCOL_T0, &this->hCard, &dwProtocol))!=SCARD_S_SUCCESS) { break; } MDEBUG( ""Device ""<id <<"" Connected: hCard=""<hCard); dwAtrLen = sizeof(pbAtr); if ((rv = SCardStatus(this->hCard, NULL, &dwReaderLen, &dwState, &dwProtocol, pbAtr, &dwAtrLen))!=SCARD_S_SUCCESS) { break; } MDEBUG( ""Device ""<id <<"" Status OK""); rv = SCARD_S_SUCCESS ; this->full_name = std::string(p); break; } p += strlen(p) +1; } } if (rv == SCARD_S_SUCCESS && mszReaders) { #ifdef SCARD_AUTOALLOCATE SCardFreeMemory(this->hContext, mszReaders); #else free(mszReaders); #endif mszReaders = NULL; } if (rv != SCARD_S_SUCCESS) { if ( hCard) { SCardDisconnect(this->hCard, SCARD_UNPOWER_CARD); MDEBUG( ""Device ""<id <<"" disconnected: hCard=""<hCard); this->hCard = 0; } } ASSERT_RV(rv); this->reset(); #ifdef DEBUG_HWDEVICE cryptonote::account_public_address pubkey; this->get_public_address(pubkey); #endif crypto::secret_key vkey; crypto::secret_key skey; this->get_secret_keys(vkey,skey); return rv==SCARD_S_SUCCESS; } bool device_ledger::disconnect() { if (this->hCard) { SCardDisconnect(this->hCard, SCARD_UNPOWER_CARD); MDEBUG( ""Device ""<id <<"" disconnected: hCard=""<hCard); this->hCard = 0; } return true; } bool device_ledger::set_mode(device_mode mode) { AUTO_LOCK_CMD(); int offset; switch(mode) { case TRANSACTION_CREATE_REAL: case TRANSACTION_CREATE_FAKE: offset = set_command_header_noopt(INS_SET_SIGNATURE_MODE, 1); //account this->buffer_send[offset] = mode; offset += 1; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); this->mode = mode; break; case TRANSACTION_PARSE: case NONE: this->mode = mode; break; default: CHECK_AND_ASSERT_THROW_MES(false, "" device_ledger::set_mode(unsigned int mode): invalid mode: ""<buffer_recv, 32); memmove(pubkey.m_spend_public_key.data, this->buffer_recv+32, 32); return true; } bool device_ledger::get_secret_keys(crypto::secret_key &vkey , crypto::secret_key &skey) { AUTO_LOCK_CMD(); //secret key are represented as fake key on the wallet side memset(vkey.data, 0x00, 32); memset(skey.data, 0xFF, 32); //spcialkey, normal conf handled in decrypt send_simple(INS_GET_KEY, 0x02); //View key is retrievied, if allowed, to speed up blockchain parsing memmove(this->viewkey.data, this->buffer_recv+0, 32); if (is_fake_view_key(this->viewkey)) { MDEBUG(""Have Not view key""); this->has_view_key = false; } else { MDEBUG(""Have view key""); this->has_view_key = true; } #ifdef DEBUG_HWDEVICE memmove(dbg_viewkey.data, this->buffer_recv+0, 32); memmove(dbg_spendkey.data, this->buffer_recv+32, 32); #endif return true; } bool device_ledger::generate_chacha_key(const cryptonote::account_keys &keys, crypto::chacha_key &key) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE crypto::chacha_key key_x; cryptonote::account_keys keys_x = hw::ledger::decrypt(keys); this->controle_device->generate_chacha_key(keys_x, key_x); #endif send_simple(INS_GET_CHACHA8_PREKEY); char prekey[200]; memmove(prekey, &this->buffer_recv[0], 200); crypto::generate_chacha_key_prehashed(&prekey[0], sizeof(prekey), key); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""generate_chacha_key_prehashed"", ""key"", (char*)key_x.data(), (char*)key.data()); #endif return true; } /* ======================================================================= */ /* SUB ADDRESS */ /* ======================================================================= */ bool device_ledger::derive_subaddress_public_key(const crypto::public_key &pub, const crypto::key_derivation &derivation, const std::size_t output_index, crypto::public_key &derived_pub){ AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::public_key pub_x = pub; crypto::key_derivation derivation_x; if ((this->mode == TRANSACTION_PARSE) && has_view_key) { derivation_x = derivation; } else { derivation_x = hw::ledger::decrypt(derivation); } const std::size_t output_index_x = output_index; crypto::public_key derived_pub_x; hw::ledger::log_hexbuffer(""derive_subaddress_public_key: [[IN]] pub "", pub_x.data, 32); hw::ledger::log_hexbuffer(""derive_subaddress_public_key: [[IN]] derivation"", derivation_x.data, 32); hw::ledger::log_message (""derive_subaddress_public_key: [[IN]] index "", std::to_string((int)output_index_x)); this->controle_device->derive_subaddress_public_key(pub_x, derivation_x,output_index_x,derived_pub_x); hw::ledger::log_hexbuffer(""derive_subaddress_public_key: [[OUT]] derived_pub"", derived_pub_x.data, 32); #endif if ((this->mode == TRANSACTION_PARSE) && has_view_key) { //If we are in TRANSACTION_PARSE, the given derivation has been retrieved uncrypted (wihtout the help //of the device), so continue that way. MDEBUG( ""derive_subaddress_public_key : PARSE mode with known viewkey""); crypto::derive_subaddress_public_key(pub, derivation, output_index,derived_pub); } else { int offset = set_command_header_noopt(INS_DERIVE_SUBADDRESS_PUBLIC_KEY); //pub memmove(this->buffer_send+offset, pub.data, 32); offset += 32; //derivation memmove(this->buffer_send+offset, derivation.data, 32); offset += 32; //index this->buffer_send[offset+0] = output_index>>24; this->buffer_send[offset+1] = output_index>>16; this->buffer_send[offset+2] = output_index>>8; this->buffer_send[offset+3] = output_index>>0; offset += 4; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(derived_pub.data, &this->buffer_recv[0], 32); } #ifdef DEBUG_HWDEVICE hw::ledger::check32(""derive_subaddress_public_key"", ""derived_pub"", derived_pub_x.data, derived_pub.data); #endif return true; } crypto::public_key device_ledger::get_subaddress_spend_public_key(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) { AUTO_LOCK_CMD(); crypto::public_key D; #ifdef DEBUG_HWDEVICE const cryptonote::account_keys keys_x = hw::ledger::decrypt(keys); const cryptonote::subaddress_index index_x = index; crypto::public_key D_x; hw::ledger::log_hexbuffer(""get_subaddress_spend_public_key: [[IN]] keys.m_view_secret_key "", keys_x.m_view_secret_key.data,32); hw::ledger::log_hexbuffer(""get_subaddress_spend_public_key: [[IN]] keys.m_spend_secret_key"", keys_x.m_spend_secret_key.data,32); hw::ledger::log_message (""get_subaddress_spend_public_key: [[IN]] index "", std::to_string(index_x.major)+"".""+std::to_string(index_x.minor)); D_x = this->controle_device->get_subaddress_spend_public_key(keys_x, index_x); hw::ledger::log_hexbuffer(""get_subaddress_spend_public_key: [[OUT]] derivation "", D_x.data, 32); #endif if (index.is_zero()) { D = keys.m_account_address.m_spend_public_key; } else { int offset = set_command_header_noopt(INS_GET_SUBADDRESS_SPEND_PUBLIC_KEY); //index static_assert(sizeof(cryptonote::subaddress_index) == 8, ""cryptonote::subaddress_index shall be 8 bytes length""); memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index)); offset +=8 ; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(D.data, &this->buffer_recv[0], 32); } #ifdef DEBUG_HWDEVICE hw::ledger::check32(""get_subaddress_spend_public_key"", ""D"", D_x.data, D.data); #endif return D; } std::vector device_ledger::get_subaddress_spend_public_keys(const cryptonote::account_keys &keys, uint32_t account, uint32_t begin, uint32_t end) { std::vector pkeys; cryptonote::subaddress_index index = {account, begin}; crypto::public_key D; for (uint32_t idx = begin; idx < end; ++idx) { index.minor = idx; D = this->get_subaddress_spend_public_key(keys, index); pkeys.push_back(D); } return pkeys; } cryptonote::account_public_address device_ledger::get_subaddress(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) { AUTO_LOCK_CMD(); cryptonote::account_public_address address; #ifdef DEBUG_HWDEVICE const cryptonote::account_keys keys_x = hw::ledger::decrypt(keys); const cryptonote::subaddress_index index_x = index; cryptonote::account_public_address address_x; hw::ledger::log_hexbuffer(""get_subaddress: [[IN]] keys.m_view_secret_key "", keys_x.m_view_secret_key.data, 32); hw::ledger::log_hexbuffer(""get_subaddress: [[IN]] keys.m_view_public_key"", keys_x.m_account_address.m_view_public_key.data, 32); hw::ledger::log_hexbuffer(""get_subaddress: [[IN]] keys.m_view_secret_key "", keys_x.m_view_secret_key.data, 32); hw::ledger::log_hexbuffer(""get_subaddress: [[IN]] keys.m_spend_public_key"", keys_x.m_account_address.m_spend_public_key.data, 32); hw::ledger::log_message (""get_subaddress: [[IN]] index "", std::to_string(index_x.major)+"".""+std::to_string(index_x.minor)); address_x = this->controle_device->get_subaddress(keys_x, index_x); hw::ledger::log_hexbuffer(""get_subaddress: [[OUT]] keys.m_view_public_key "", address_x.m_view_public_key.data, 32); hw::ledger::log_hexbuffer(""get_subaddress: [[OUT]] keys.m_spend_public_key"", address_x.m_spend_public_key.data, 32); #endif if (index.is_zero()) { address = keys.m_account_address; } else { int offset = set_command_header_noopt(INS_GET_SUBADDRESS); //index static_assert(sizeof(cryptonote::subaddress_index) == 8, ""cryptonote::subaddress_index shall be 8 bytes length""); memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index)); offset +=8 ; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(address.m_view_public_key.data, &this->buffer_recv[0], 32); memmove(address.m_spend_public_key.data, &this->buffer_recv[32], 32); } #ifdef DEBUG_HWDEVICE hw::ledger::check32(""get_subaddress"", ""address.m_view_public_key.data"", address_x.m_view_public_key.data, address.m_view_public_key.data); hw::ledger::check32(""get_subaddress"", ""address.m_spend_public_key.data"", address_x.m_spend_public_key.data, address.m_spend_public_key.data); #endif return address; } crypto::secret_key device_ledger::get_subaddress_secret_key(const crypto::secret_key &sec, const cryptonote::subaddress_index &index) { AUTO_LOCK_CMD(); crypto::secret_key sub_sec; #ifdef DEBUG_HWDEVICE const crypto::secret_key sec_x = hw::ledger::decrypt(sec); const cryptonote::subaddress_index index_x = index; crypto::secret_key sub_sec_x; hw::ledger::log_message (""get_subaddress_secret_key: [[IN]] index "", std::to_string(index.major)+"".""+std::to_string(index.minor)); hw::ledger::log_hexbuffer(""get_subaddress_secret_key: [[IN]] sec "", sec_x.data, 32); sub_sec_x = this->controle_device->get_subaddress_secret_key(sec_x, index_x); hw::ledger::log_hexbuffer(""get_subaddress_secret_key: [[OUT]] sub_sec"", sub_sec_x.data, 32); #endif int offset = set_command_header_noopt(INS_GET_SUBADDRESS_SECRET_KEY); //sec memmove(this->buffer_send+offset, sec.data, 32); offset += 32; //index static_assert(sizeof(cryptonote::subaddress_index) == 8, ""cryptonote::subaddress_index shall be 8 bytes length""); memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index)); offset +=8 ; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(sub_sec.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE crypto::secret_key sub_sec_clear = hw::ledger::decrypt(sub_sec); hw::ledger::check32(""get_subaddress_secret_key"", ""sub_sec"", sub_sec_x.data, sub_sec_clear.data); #endif return sub_sec; } /* ======================================================================= */ /* DERIVATION & KEY */ /* ======================================================================= */ bool device_ledger::verify_keys(const crypto::secret_key &secret_key, const crypto::public_key &public_key) { AUTO_LOCK_CMD(); int offset, sw; offset = set_command_header_noopt(INS_VERIFY_KEY); //sec memmove(this->buffer_send+offset, secret_key.data, 32); offset += 32; //pub memmove(this->buffer_send+offset, public_key.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); uint32_t verified = this->buffer_recv[0] << 24 | this->buffer_recv[1] << 16 | this->buffer_recv[2] << 8 | this->buffer_recv[3] << 0 ; return verified == 1; } bool device_ledger::scalarmultKey(rct::key & aP, const rct::key &P, const rct::key &a) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const rct::key P_x = P; const rct::key a_x = hw::ledger::decrypt(a); rct::key aP_x; hw::ledger::log_hexbuffer(""scalarmultKey: [[IN]] P "", (char*)P_x.bytes, 32); hw::ledger::log_hexbuffer(""scalarmultKey: [[IN]] a "", (char*)a_x.bytes, 32); this->controle_device->scalarmultKey(aP_x, P_x, a_x); hw::ledger::log_hexbuffer(""scalarmultKey: [[OUT]] aP"", (char*)aP_x.bytes, 32); #endif int offset = set_command_header_noopt(INS_SECRET_SCAL_MUL_KEY); //pub memmove(this->buffer_send+offset, P.bytes, 32); offset += 32; //sec memmove(this->buffer_send+offset, a.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(aP.bytes, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""scalarmultKey"", ""mulkey"", (char*)aP_x.bytes, (char*)aP.bytes); #endif return true; } bool device_ledger::scalarmultBase(rct::key &aG, const rct::key &a) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const rct::key a_x = hw::ledger::decrypt(a); rct::key aG_x; hw::ledger::log_hexbuffer(""scalarmultKey: [[IN]] a "", (char*)a_x.bytes, 32); this->controle_device->scalarmultBase(aG_x, a_x); hw::ledger::log_hexbuffer(""scalarmultKey: [[OUT]] aG"", (char*)aG_x.bytes, 32); #endif int offset = set_command_header_noopt(INS_SECRET_SCAL_MUL_BASE); //sec memmove(this->buffer_send+offset, a.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(aG.bytes, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""scalarmultBase"", ""mulkey"", (char*)aG_x.bytes, (char*)aG.bytes); #endif return true; } bool device_ledger::sc_secret_add( crypto::secret_key &r, const crypto::secret_key &a, const crypto::secret_key &b) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::secret_key a_x = hw::ledger::decrypt(a); const crypto::secret_key b_x = hw::ledger::decrypt(b); crypto::secret_key r_x; this->controle_device->sc_secret_add(r_x, a_x, b_x); #endif int offset = set_command_header_noopt(INS_SECRET_KEY_ADD); //sec key memmove(this->buffer_send+offset, a.data, 32); offset += 32; //sec key memmove(this->buffer_send+offset, b.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(r.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE crypto::secret_key r_clear = hw::ledger::decrypt(r); hw::ledger::check32(""sc_secret_add"", ""r"", r_x.data, r_clear.data); #endif return true; } crypto::secret_key device_ledger::generate_keys(crypto::public_key &pub, crypto::secret_key &sec, const crypto::secret_key& recovery_key, bool recover) { AUTO_LOCK_CMD(); if (recover) { throw std::runtime_error(""device generate key does not support recover""); } #ifdef DEBUG_HWDEVICE bool recover_x = recover; const crypto::secret_key recovery_key_x = recovery_key; crypto::public_key pub_x; crypto::secret_key sec_x; #endif send_simple(INS_GENERATE_KEYPAIR); //pub key memmove(pub.data, &this->buffer_recv[0], 32); memmove(sec.data, &this->buffer_recv[32], 32); #ifdef DEBUG_HWDEVICE crypto::secret_key sec_clear = hw::ledger::decrypt(sec); sec_x = sec_clear; crypto::secret_key_to_public_key(sec_x,pub_x); hw::ledger::check32(""generate_keys"", ""pub"", pub_x.data, pub.data); #endif return sec; } bool device_ledger::generate_key_derivation(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_derivation &derivation) { AUTO_LOCK_CMD(); bool r = false; #ifdef DEBUG_HWDEVICE const crypto::public_key pub_x = pub; const crypto::secret_key sec_x = hw::ledger::decrypt(sec); crypto::key_derivation derivation_x; hw::ledger::log_hexbuffer(""generate_key_derivation: [[IN]] pub "", pub_x.data, 32); hw::ledger::log_hexbuffer(""generate_key_derivation: [[IN]] sec "", sec_x.data, 32); this->controle_device->generate_key_derivation(pub_x, sec_x, derivation_x); hw::ledger::log_hexbuffer(""generate_key_derivation: [[OUT]] derivation"", derivation_x.data, 32); #endif if ((this->mode == TRANSACTION_PARSE) && has_view_key) { //A derivation is resquested in PASRE mode and we have the view key, //so do that wihtout the device and return the derivation unencrypted. MDEBUG( ""generate_key_derivation : PARSE mode with known viewkey""); //Note derivation in PARSE mode can only happen with viewkey, so assert it! assert(is_fake_view_key(sec)); r = crypto::generate_key_derivation(pub, this->viewkey, derivation); } else { int offset = set_command_header_noopt(INS_GEN_KEY_DERIVATION); //pub memmove(this->buffer_send+offset, pub.data, 32); offset += 32; //sec memmove(this->buffer_send+offset, sec.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //derivattion data memmove(derivation.data, &this->buffer_recv[0], 32); r = true; } #ifdef DEBUG_HWDEVICE crypto::key_derivation derivation_clear ; if ((this->mode == TRANSACTION_PARSE) && has_view_key) { derivation_clear = derivation; }else { derivation_clear = hw::ledger::decrypt(derivation); } hw::ledger::check32(""generate_key_derivation"", ""derivation"", derivation_x.data, derivation_clear.data); #endif return r; } bool device_ledger::conceal_derivation(crypto::key_derivation &derivation, const crypto::public_key &tx_pub_key, const std::vector &additional_tx_pub_keys, const crypto::key_derivation &main_derivation, const std::vector &additional_derivations) { const crypto::public_key *pkey=NULL; if (derivation == main_derivation) { pkey = &tx_pub_key; MDEBUG(""conceal derivation with main tx pub key""); } else { for(size_t n=0; n < additional_derivations.size();++n) { if(derivation == additional_derivations[n]) { pkey = &additional_tx_pub_keys[n]; MDEBUG(""conceal derivation with additionnal tx pub key""); break; } } } ASSERT_X(pkey, ""Mismatched derivation on scan info""); return this->generate_key_derivation(*pkey, crypto::null_skey, derivation); } bool device_ledger::derivation_to_scalar(const crypto::key_derivation &derivation, const size_t output_index, crypto::ec_scalar &res) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation); const size_t output_index_x = output_index; crypto::ec_scalar res_x; hw::ledger::log_hexbuffer(""derivation_to_scalar: [[IN]] derivation "", derivation_x.data, 32); hw::ledger::log_message (""derivation_to_scalar: [[IN]] output_index "", std::to_string(output_index_x)); this->controle_device->derivation_to_scalar(derivation_x, output_index_x, res_x); hw::ledger::log_hexbuffer(""derivation_to_scalar: [[OUT]] res "", res_x.data, 32); #endif int offset = set_command_header_noopt(INS_DERIVATION_TO_SCALAR); //derivattion memmove(this->buffer_send+offset, derivation.data, 32); offset += 32; //index this->buffer_send[offset+0] = output_index>>24; this->buffer_send[offset+1] = output_index>>16; this->buffer_send[offset+2] = output_index>>8; this->buffer_send[offset+3] = output_index>>0; offset += 4; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //derivattion data memmove(res.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE crypto::ec_scalar res_clear = hw::ledger::decrypt(res); hw::ledger::check32(""derivation_to_scalar"", ""res"", res_x.data, res_clear.data); #endif return true; } bool device_ledger::derive_secret_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::secret_key &sec, crypto::secret_key &derived_sec) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation); const std::size_t output_index_x = output_index; const crypto::secret_key sec_x = hw::ledger::decrypt(sec); crypto::secret_key derived_sec_x; hw::ledger::log_hexbuffer(""derive_secret_key: [[IN]] derivation "", derivation_x.data, 32); hw::ledger::log_message (""derive_secret_key: [[IN]] index "", std::to_string(output_index_x)); hw::ledger::log_hexbuffer(""derive_secret_key: [[IN]] sec "", sec_x.data, 32); this->controle_device->derive_secret_key(derivation_x, output_index_x, sec_x, derived_sec_x); hw::ledger::log_hexbuffer(""derive_secret_key: [[OUT]] derived_sec"", derived_sec_x.data, 32); #endif int offset = set_command_header_noopt(INS_DERIVE_SECRET_KEY); //derivation memmove(this->buffer_send+offset, derivation.data, 32); offset += 32; //index this->buffer_send[offset+0] = output_index>>24; this->buffer_send[offset+1] = output_index>>16; this->buffer_send[offset+2] = output_index>>8; this->buffer_send[offset+3] = output_index>>0; offset += 4; //sec memmove(this->buffer_send+offset, sec.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(derived_sec.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE crypto::secret_key derived_sec_clear = hw::ledger::decrypt(derived_sec); hw::ledger::check32(""derive_secret_key"", ""derived_sec"", derived_sec_x.data, derived_sec_clear.data); #endif return true; } bool device_ledger::derive_public_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::public_key &pub, crypto::public_key &derived_pub){ AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation); const std::size_t output_index_x = output_index; const crypto::public_key pub_x = pub; crypto::public_key derived_pub_x; hw::ledger::log_hexbuffer(""derive_public_key: [[IN]] derivation "", derivation_x.data, 32); hw::ledger::log_message (""derive_public_key: [[IN]] output_index"", std::to_string(output_index_x)); hw::ledger::log_hexbuffer(""derive_public_key: [[IN]] pub "", pub_x.data, 32); this->controle_device->derive_public_key(derivation_x, output_index_x, pub_x, derived_pub_x); hw::ledger::log_hexbuffer(""derive_public_key: [[OUT]] derived_pub "", derived_pub_x.data, 32); #endif int offset = set_command_header_noopt(INS_DERIVE_PUBLIC_KEY); //derivation memmove(this->buffer_send+offset, derivation.data, 32); offset += 32; //index this->buffer_send[offset+0] = output_index>>24; this->buffer_send[offset+1] = output_index>>16; this->buffer_send[offset+2] = output_index>>8; this->buffer_send[offset+3] = output_index>>0; offset += 4; //pub memmove(this->buffer_send+offset, pub.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(derived_pub.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""derive_public_key"", ""derived_pub"", derived_pub_x.data, derived_pub.data); #endif return true; } bool device_ledger::secret_key_to_public_key(const crypto::secret_key &sec, crypto::public_key &pub) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::secret_key sec_x = hw::ledger::decrypt(sec); crypto::public_key pub_x; hw::ledger::log_hexbuffer(""secret_key_to_public_key: [[IN]] sec "", sec_x.data, 32); bool rc = this->controle_device->secret_key_to_public_key(sec_x, pub_x); hw::ledger::log_hexbuffer(""secret_key_to_public_key: [[OUT]] pub"", pub_x.data, 32); if (!rc){ hw::ledger::log_message(""secret_key_to_public_key"", ""secret_key rejected""); } #endif int offset = set_command_header_noopt(INS_SECRET_KEY_TO_PUBLIC_KEY); //sec key memmove(this->buffer_send+offset, sec.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(pub.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""secret_key_to_public_key"", ""pub"", pub_x.data, pub.data); #endif return true; } bool device_ledger::generate_key_image(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_image &image){ AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::public_key pub_x = pub; const crypto::secret_key sec_x = hw::ledger::decrypt(sec); crypto::key_image image_x; hw::ledger::log_hexbuffer(""generate_key_image: [[IN]] pub "", pub_x.data, 32); hw::ledger::log_hexbuffer(""generate_key_image: [[IN]] sec "", sec_x.data, 32); this->controle_device->generate_key_image(pub_x, sec_x, image_x); hw::ledger::log_hexbuffer(""generate_key_image: [[OUT]] image "", image_x.data, 32); #endif int offset = set_command_header_noopt(INS_GEN_KEY_IMAGE); //pub memmove(this->buffer_send+offset, pub.data, 32); offset += 32; //sec memmove(this->buffer_send+offset, sec.data, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pub key memmove(image.data, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""generate_key_image"", ""image"", image_x.data, image.data); #endif return true; } /* ======================================================================= */ /* TRANSACTION */ /* ======================================================================= */ bool device_ledger::open_tx(crypto::secret_key &tx_key) { AUTO_LOCK_CMD(); key_map.clear(); int offset = set_command_header_noopt(INS_OPEN_TX, 0x01); //account this->buffer_send[offset+0] = 0x00; this->buffer_send[offset+1] = 0x00; this->buffer_send[offset+2] = 0x00; this->buffer_send[offset+3] = 0x00; offset += 4; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(tx_key.data, &this->buffer_recv[32], 32); return true; } bool device_ledger::encrypt_payment_id(crypto::hash8 &payment_id, const crypto::public_key &public_key, const crypto::secret_key &secret_key) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const crypto::public_key public_key_x = public_key; const crypto::secret_key secret_key_x = hw::ledger::decrypt(secret_key); crypto::hash8 payment_id_x = payment_id; this->controle_device->encrypt_payment_id(payment_id_x, public_key_x, secret_key_x); #endif int offset = set_command_header_noopt(INS_STEALTH); //pub memmove(&this->buffer_send[offset], public_key.data, 32); offset += 32; //sec memmove(&this->buffer_send[offset], secret_key.data, 32); offset += 32; //id memmove(&this->buffer_send[offset], payment_id.data, 8); offset += 8; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(payment_id.data, &this->buffer_recv[0], 8); #ifdef DEBUG_HWDEVICE hw::ledger::check8(""stealth"", ""payment_id"", payment_id_x.data, payment_id.data); #endif return true; } bool device_ledger::add_output_key_mapping(const crypto::public_key &Aout, const crypto::public_key &Bout, const bool is_subaddress, const size_t real_output_index, const rct::key &amount_key, const crypto::public_key &out_eph_public_key) { AUTO_LOCK_CMD(); key_map.add(ABPkeys(rct::pk2rct(Aout),rct::pk2rct(Bout), is_subaddress, real_output_index, rct::pk2rct(out_eph_public_key), amount_key)); return true; } bool device_ledger::ecdhEncode(rct::ecdhTuple & unmasked, const rct::key & AKout) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const rct::key AKout_x = hw::ledger::decrypt(AKout); rct::ecdhTuple unmasked_x = unmasked; this->controle_device->ecdhEncode(unmasked_x, AKout_x); #endif int offset = set_command_header_noopt(INS_BLIND); // AKout memmove(this->buffer_send+offset, AKout.bytes, 32); offset += 32; //mask k memmove(this->buffer_send+offset, unmasked.mask.bytes, 32); offset += 32; //value v memmove(this->buffer_send+offset, unmasked.amount.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(unmasked.amount.bytes, &this->buffer_recv[0], 32); memmove(unmasked.mask.bytes, &this->buffer_recv[32], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""ecdhEncode"", ""amount"", (char*)unmasked_x.amount.bytes, (char*)unmasked.amount.bytes); hw::ledger::check32(""ecdhEncode"", ""mask"", (char*)unmasked_x.mask.bytes, (char*)unmasked.mask.bytes); hw::ledger::log_hexbuffer(""Blind AKV input"", (char*)&this->buffer_recv[64], 3*32); #endif return true; } bool device_ledger::ecdhDecode(rct::ecdhTuple & masked, const rct::key & AKout) { AUTO_LOCK_CMD(); #ifdef DEBUG_HWDEVICE const rct::key AKout_x = hw::ledger::decrypt(AKout); rct::ecdhTuple masked_x = masked; this->controle_device->ecdhDecode(masked_x, AKout_x); #endif int offset = set_command_header_noopt(INS_UNBLIND); // AKout memmove(this->buffer_send+offset, AKout.bytes, 32); offset += 32; //mask k memmove(this->buffer_send+offset, masked.mask.bytes, 32); offset += 32; //value v memmove(this->buffer_send+offset, masked.amount.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(masked.amount.bytes, &this->buffer_recv[0], 32); memmove(masked.mask.bytes, &this->buffer_recv[32], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""ecdhDecode"", ""amount"", (char*)masked_x.amount.bytes, (char*)masked.amount.bytes); hw::ledger::check32(""ecdhDecode"", ""mask"", (char*)masked_x.mask.bytes,(char*) masked.mask.bytes); #endif return true; } bool device_ledger::mlsag_prehash(const std::string &blob, size_t inputs_size, size_t outputs_size, const rct::keyV &hashes, const rct::ctkeyV &outPk, rct::key &prehash) { AUTO_LOCK_CMD(); unsigned int data_offset, C_offset, kv_offset, i; const char *data; #ifdef DEBUG_HWDEVICE const std::string blob_x = blob; size_t inputs_size_x = inputs_size; size_t outputs_size_x = outputs_size; const rct::keyV hashes_x = hashes; const rct::ctkeyV outPk_x = outPk; rct::key prehash_x; this->controle_device->mlsag_prehash(blob_x, inputs_size_x, outputs_size_x, hashes_x, outPk_x, prehash_x); if (inputs_size) { log_message(""mlsag_prehash"", (std::string(""inputs_size not null: "") + std::to_string(inputs_size)).c_str()); } this->key_map.log(); #endif data = blob.data(); // ====== u8 type, varint txnfee ====== int offset = set_command_header(INS_VALIDATE, 0x01, 0x01); //options this->buffer_send[offset] = (inputs_size == 0)?0x00:0x80; offset += 1; //type uint8_t type = data[0]; this->buffer_send[offset] = data[0]; offset += 1; //txnfee data_offset = 1; while (data[data_offset]&0x80) { this->buffer_send[offset] = data[data_offset]; offset += 1; data_offset += 1; } this->buffer_send[offset] = data[data_offset]; offset += 1; data_offset += 1; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //pseudoOuts if ((type == rct::RCTTypeSimple) || (type == rct::RCTTypeSimpleBulletproof)) { for ( i = 0; i < inputs_size; i++) { offset = set_command_header(INS_VALIDATE, 0x01, i+2); //options this->buffer_send[offset] = (i==inputs_size-1)? 0x00:0x80; offset += 1; //pseudoOut memmove(this->buffer_send+offset, data+data_offset,32); offset += 32; data_offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); } } // ====== Aout, Bout, AKout, C, v, k ====== kv_offset = data_offset; C_offset = kv_offset+ (32*2)*outputs_size; for ( i = 0; i < outputs_size; i++) { ABPkeys outKeys; bool found; found = this->key_map.find(outPk[i].dest, outKeys); if (!found) { log_hexbuffer(""Pout not found"", (char*)outPk[i].dest.bytes, 32); CHECK_AND_ASSERT_THROW_MES(found, ""Pout not found""); } offset = set_command_header(INS_VALIDATE, 0x02, i+1); //options this->buffer_send[offset] = (i==outputs_size-1)? 0x00:0x80 ; offset += 1; if (found) { //is_subaddress this->buffer_send[offset] = outKeys.is_subaddress; offset++; //Aout memmove(this->buffer_send+offset, outKeys.Aout.bytes, 32); offset+=32; //Bout memmove(this->buffer_send+offset, outKeys.Bout.bytes, 32); offset+=32; //AKout memmove(this->buffer_send+offset, outKeys.AKout.bytes, 32); offset+=32; } else { // dummy: is_subaddress Aout Bout AKout offset += 1+32*3; } //C memmove(this->buffer_send+offset, data+C_offset,32); offset += 32; C_offset += 32; //k memmove(this->buffer_send+offset, data+kv_offset,32); offset += 32; //v kv_offset += 32; memmove(this->buffer_send+offset, data+kv_offset,32); offset += 32; kv_offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); #ifdef DEBUG_HWDEVICE hw::ledger::log_hexbuffer(""Prehash AKV input"", (char*)&this->buffer_recv[64], 3*32); #endif } // ====== C[], message, proof====== C_offset = kv_offset; for (i = 0; i < outputs_size; i++) { offset = set_command_header(INS_VALIDATE, 0x03, i+1); //options this->buffer_send[offset] = 0x80 ; offset += 1; //C memmove(this->buffer_send+offset, data+C_offset,32); offset += 32; C_offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); } offset = set_command_header_noopt(INS_VALIDATE, 0x03, i+1); //message memmove(this->buffer_send+offset, hashes[0].bytes,32); offset += 32; //proof memmove(this->buffer_send+offset, hashes[2].bytes,32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(prehash.bytes, this->buffer_recv, 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""mlsag_prehash"", ""prehash"", (char*)prehash_x.bytes, (char*)prehash.bytes); #endif return true; } bool device_ledger::mlsag_prepare(const rct::key &H, const rct::key &xx, rct::key &a, rct::key &aG, rct::key &aHP, rct::key &II) { AUTO_LOCK_CMD(); unsigned char options; #ifdef DEBUG_HWDEVICE const rct::key H_x = H; const rct::key xx_x = hw::ledger::decrypt(xx); rct::key a_x; rct::key aG_x; rct::key aHP_x; rct::key II_x; #endif int offset = set_command_header_noopt(INS_MLSAG, 0x01); //value H memmove(this->buffer_send+offset, H.bytes, 32); offset += 32; //mask xin memmove(this->buffer_send+offset, xx.bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); memmove(a.bytes, &this->buffer_recv[32*0], 32); memmove(aG.bytes, &this->buffer_recv[32*1], 32); memmove(aHP.bytes, &this->buffer_recv[32*2], 32); memmove(II.bytes, &this->buffer_recv[32*3], 32); #ifdef DEBUG_HWDEVICE a_x = hw::ledger::decrypt(a); rct::scalarmultBase(aG_x, a_x); rct::scalarmultKey(aHP_x, H_x, a_x); rct::scalarmultKey(II_x, H_x, xx_x); hw::ledger::check32(""mlsag_prepare"", ""AG"", (char*)aG_x.bytes, (char*)aG.bytes); hw::ledger::check32(""mlsag_prepare"", ""aHP"", (char*)aHP_x.bytes, (char*)aHP.bytes); hw::ledger::check32(""mlsag_prepare"", ""II"", (char*)II_x.bytes, (char*)II.bytes); #endif return true; } bool device_ledger::mlsag_prepare(rct::key &a, rct::key &aG) { AUTO_LOCK_CMD(); unsigned char options; #ifdef DEBUG_HWDEVICE rct::key a_x; rct::key aG_x; #endif send_simple(INS_MLSAG, 0x01); memmove(a.bytes, &this->buffer_recv[32*0], 32); memmove(aG.bytes, &this->buffer_recv[32*1], 32); #ifdef DEBUG_HWDEVICE a_x = hw::ledger::decrypt(a); rct::scalarmultBase(aG_x, a_x); hw::ledger::check32(""mlsag_prepare"", ""AG"", (char*)aG_x.bytes, (char*)aG.bytes); #endif return true; } bool device_ledger::mlsag_hash(const rct::keyV &long_message, rct::key &c) { AUTO_LOCK_CMD(); unsigned char options; size_t cnt; #ifdef DEBUG_HWDEVICE const rct::keyV long_message_x = long_message; rct::key c_x; this->controle_device->mlsag_hash(long_message_x, c_x); #endif cnt = long_message.size(); for (size_t i = 0; ibuffer_send[offset] = (i==(cnt-1))?0x00:0x80; //last offset += 1; //msg part memmove(this->buffer_send+offset, long_message[i].bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); } memmove(c.bytes, &this->buffer_recv[0], 32); #ifdef DEBUG_HWDEVICE hw::ledger::check32(""mlsag_hash"", ""c"", (char*)c_x.bytes, (char*)c.bytes); #endif return true; } bool device_ledger::mlsag_sign(const rct::key &c, const rct::keyV &xx, const rct::keyV &alpha, const size_t rows, const size_t dsRows, rct::keyV &ss) { AUTO_LOCK_CMD(); CHECK_AND_ASSERT_THROW_MES(dsRows<=rows, ""dsRows greater than rows""); CHECK_AND_ASSERT_THROW_MES(xx.size() == rows, ""xx size does not match rows""); CHECK_AND_ASSERT_THROW_MES(alpha.size() == rows, ""alpha size does not match rows""); CHECK_AND_ASSERT_THROW_MES(ss.size() == rows, ""ss size does not match rows""); #ifdef DEBUG_HWDEVICE const rct::key c_x = c; const rct::keyV xx_x = hw::ledger::decrypt(xx); const rct::keyV alpha_x = hw::ledger::decrypt(alpha); const int rows_x = rows; const int dsRows_x = dsRows; rct::keyV ss_x(ss.size()); this->controle_device->mlsag_sign(c_x, xx_x, alpha_x, rows_x, dsRows_x, ss_x); #endif for (size_t j = 0; j < dsRows; j++) { int offset = set_command_header(INS_MLSAG, 0x03, j+1); //options this->buffer_send[offset] = 0x00; if (j==(dsRows-1)) { this->buffer_send[offset] |= 0x80; //last } offset += 1; //xx memmove(this->buffer_send+offset, xx[j].bytes, 32); offset += 32; //alpa memmove(this->buffer_send+offset, alpha[j].bytes, 32); offset += 32; this->buffer_send[4] = offset-5; this->length_send = offset; this->exchange(); //ss memmove(ss[j].bytes, &this->buffer_recv[0], 32); } for (size_t j = dsRows; j < rows; j++) { sc_mulsub(ss[j].bytes, c.bytes, xx[j].bytes, alpha[j].bytes); } #ifdef DEBUG_HWDEVICE for (size_t j = 0; j < rows; j++) { hw::ledger::check32(""mlsag_sign"", ""ss[""+std::to_string(j)+""]"", (char*)ss_x[j].bytes, (char*)ss[j].bytes); } #endif return true; } bool device_ledger::close_tx() { AUTO_LOCK_CMD(); send_simple(INS_CLOSE_TX); return true; } /* ---------------------------------------------------------- */ static device_ledger *legder_device = NULL; void register_all(std::map> ®istry) { if (!legder_device) { legder_device = new device_ledger(); legder_device->set_name(""Ledger""); } registry.insert(std::make_pair(""Ledger"", std::unique_ptr(legder_device))); } #else //WITH_DEVICE_LEDGER void register_all(std::map> ®istry) { } #endif //WITH_DEVICE_LEDGER } } ",16136,True,3257.033876055521,median "== Raspicam commands `raspistill`, `raspivid` and `raspiyuv` are command line tools for using the camera module. === Enabling the Camera Before using any of the _Raspicam_ applications, the camera must be enabled. ==== On the desktop Select `Preferences` and `Raspberry Pi Configuration` from the desktop menu: a window will appear. Select the `Interfaces` tab, then click on the `enable camera` option. Click `OK`. You will need to reboot for the changes to take effect. ==== With the command line Open the `raspi-config` tool from the terminal: [,bash] ---- sudo raspi-config ---- Select `Interfacing Options` then `Camera` and press `Enter`. Choose `Yes` then `Ok`. Go to `Finish` and you'll be prompted to reboot. To test that the system is installed and working, try the following command: [,bash] ---- raspistill -v -o test.jpg ---- The display should show a five-second preview from the camera and then take a picture, saved to the file `test.jpg`, whilst displaying various informational messages. === `raspistill` `raspistill` is the command line tool for capturing still photographs with a Raspberry Pi camera module. ==== Basic usage of raspistill With a camera module xref:camera.adoc#camera-modules[connected and enabled], enter the following command in the terminal to take a picture: [,bash] ---- raspistill -o cam.jpg ---- image::images/cam.jpg[Upside-down photo] In this example the camera has been positioned upside-down. If the camera is placed in this position, the image must be flipped to appear the right way up. ==== Vertical flip and horizontal flip With the camera placed upside-down, the image must be rotated 180° to be displayed correctly. The way to correct for this is to apply both a vertical and a horizontal flip by passing in the `-vf` and `-hf` flags: [,bash] ---- raspistill -vf -hf -o cam2.jpg ---- image::images/cam2.jpg[Vertical and horizontal flipped photo] Now the photo has been captured correctly. ==== Resolution The camera module takes pictures at a resolution of `2592 x 1944` which is 5,038,848 pixels or 5 megapixels. ==== File size A photo taken with the camera module will be around 2.4MB. This is about 425 photos per GB. Taking 1 photo per minute would take up 1GB in about 7 hours. This is a rate of about 144MB per hour or 3.3GB per day. ==== Bash script You can create a Bash script which takes a picture with the camera. To create a script, open up your editor of choice and write the following example code: [,bash] ---- #!/bin/bash DATE=$(date +""%Y-%m-%d_%H%M"") raspistill -vf -hf -o /home/pi/camera/$DATE.jpg ---- This script will take a picture and name the file with a timestamp. You'll also need to make sure the path exists by creating the `camera` folder: [,bash] ---- mkdir camera ---- Say we saved it as `camera.sh`, we would first make the file executable: [,bash] ---- chmod +x camera.sh ---- Then run with: [,bash] ---- ./camera.sh ---- ==== More options For a full list of possible options, run `raspistill` with no arguments. To scroll, redirect stderr to stdout and pipe the output to `less`: [,bash] ---- raspistill 2>&1 | less ---- Use the arrow keys to scroll and type `q` to exit. === `raspivid` `raspivid` is the command line tool for capturing video with a Raspberry Pi camera module. ==== Basic usage of raspivid With a camera module xref:camera.adoc#camera-modules[connected and enabled], record a video using the following command: [,bash] ---- raspivid -o vid.h264 ---- Remember to use `-hf` and `-vf` to flip the image if required, like with xref:camera.adoc#raspistill[raspistill] This will save a 5 second video file to the path given here as `vid.h264` (default length of time). ==== Specify length of video To specify the length of the video taken, pass in the `-t` flag with a number of milliseconds. For example: [,bash] ---- raspivid -o video.h264 -t 10000 ---- This will record 10 seconds of video. ==== More options For a full list of possible options, run `raspivid` with no arguments, or pipe this command through `less` and scroll through: [,bash] ---- raspivid 2>&1 | less ---- Use the arrow keys to scroll and type `q` to exit. ==== MP4 Video Format The Pi captures video as a raw H264 video stream. Many media players will refuse to play it, or play it at an incorrect speed, unless it is ""wrapped"" in a suitable container format like MP4. The easiest way to obtain an MP4 file from the raspivid command is using MP4Box. Install MP4Box with this command: [,bash] ---- sudo apt install -y gpac ---- Capture your raw video with raspivid and wrap it in an MP4 container like this: [,bash] ---- # Capture 30 seconds of raw video at 640x480 and 150kB/s bit rate into a pivideo.h264 file: raspivid -t 30000 -w 640 -h 480 -fps 25 -b 1200000 -p 0,0,640,480 -o pivideo.h264 # Wrap the raw video with an MP4 container: MP4Box -add pivideo.h264 pivideo.mp4 # Remove the source raw file, leaving the remaining pivideo.mp4 file to play rm pivideo.h264 ---- Alternatively, wrap MP4 around your existing raspivid output, like this: [,bash] ---- MP4Box -add video.h264 video.mp4 ---- === `raspiyuv` `raspiyuv` has the same set of features as `raspistill` but instead of outputting standard image files such as ``.jpg``s, it generates YUV420 or RGB888 image files from the output of the camera ISP. In most cases using `raspistill` is the best option for standard image capture, but using YUV can be of benefit in certain circumstances. For example if you just need a uncompressed black and white image for computer vision applications, you can simply use the Y channel of a YUV capture. There are some specific points about the YUV420 files that are required in order to use them correctly. Line stride (or pitch) is a multiple of 32, and each plane of YUV is a multiple of 16 in height. This can mean there may be extra pixels at the end of lines, or gaps between planes, depending on the resolution of the captured image. These gaps are unused. === Troubleshooting If the Camera Module isn't working correctly, there are number of things to try: * Is the ribbon cable attached to the Camera Serial Interface (CSI), not the Display Serial Interface (DSI)? The ribbon connector will fit into either port. The Camera port is located near the HDMI connector. * Are the ribbon connectors all firmly seated, and are they the right way round? They must be straight in their sockets. * Is the Camera Module connector, between the smaller black Camera Module itself and the PCB, firmly attached? Sometimes this connection can come loose during transit or when putting the Camera Module in a case. Using a fingernail, flip up the connector on the PCB, then reconnect it with gentle pressure. It engages with a very slight click. Don't force it; if it doesn't engage, it's probably slightly misaligned. * Have `sudo apt update` and `sudo apt full-upgrade` been run? * Has `raspi-config` been run and the Camera Module enabled? * Is your power supply sufficient? The Camera Module adds about 200-250mA to the power requirements of your Raspberry Pi. If things are still not working, try the following: * `Error : raspistill/raspivid command not found`. This probably means your update/upgrade failed in some way. Try it again. * `Error : ENOMEM`. The Camera Module is not starting up. Check all connections again. * `Error : ENOSPC`. The Camera Module is probably running out of GPU memory. Check `config.txt` in the /boot/ folder. The `gpu_mem` option should be at least 128. Alternatively, use the Memory Split option in the Advanced section of `raspi-config` to set this. * If you've checked all the above issues and the Camera Module is still not working, try posting on our forums for more help. === Command Line Options ==== Preview window ---- --preview, -p Preview window settings <'x,y,w,h'> ---- Allows the user to define the size of the preview window and its location on the screen. Note this will be superimposed over the top of any other windows/graphics. ---- --fullscreen, -f Fullscreen preview mode ---- Forces the preview window to use the whole screen. Note that the aspect ratio of the incoming image will be retained, so there may be bars on some edges. ---- --nopreview, -n Do not display a preview window ---- Disables the preview window completely. Note that even though the preview is disabled, the camera will still be producing frames, so will be using power. ---- --opacity, -op Set preview window opacity ---- Sets the opacity of the preview windows. 0 = invisible, 255 = fully opaque. ==== Camera control options ---- --sharpness, -sh Set image sharpness (-100 - 100) ---- Sets the sharpness of the image. 0 is the default. ---- --contrast, -co Set image contrast (-100 - 100) ---- Sets the contrast of the image. 0 is the default. ---- --brightness, -br Set image brightness (0 - 100) ---- Sets the brightness of the image. 50 is the default. 0 is black, 100 is white. ---- --saturation, -sa Set image saturation (-100 - 100) ---- Sets the colour saturation of the image. 0 is the default. ---- --ISO, -ISO Set capture ISO (100 - 800) ---- Sets the ISO to be used for captures. ---- --vstab, -vs Turn on video stabilisation ---- In video mode only, turns on video stabilisation. ---- --ev, -ev Set EV compensation (-10 - 10) ---- Sets the EV compensation of the image. Default is 0. ---- --exposure, -ex Set exposure mode ---- Possible options are: * auto: use automatic exposure mode * night: select setting for night shooting * nightpreview: * backlight: select setting for backlit subject * spotlight: * sports: select setting for sports (fast shutter etc.) * snow: select setting optimised for snowy scenery * beach: select setting optimised for beach * verylong: select setting for long exposures * fixedfps: constrain fps to a fixed value * antishake: antishake mode * fireworks: select setting optimised for fireworks Note that not all of these settings may be implemented, depending on camera tuning. ---- --flicker, -fli Set flicker avoidance mode ---- Set a mode to compensate for lights flickering at the mains frequency, which can be seen as a dark horizontal band across an image. Flicker avoidance locks the exposure time to a multiple of the mains flicker frequency (8.33ms for 60Hz, or 10ms for 50Hz). This means that images can be noisier as the control algorithm has to increase the gain instead of exposure time should it wish for an intermediate exposure value. `auto` can be confused by external factors, therefore it is preferable to leave this setting off unless actually required. Possible options are: * off: turn off flicker avoidance * auto: automatically detect mains frequency * 50hz: set avoidance at 50Hz * 60hz: set avoidance at 60Hz ---- --awb, -awb Set Automatic White Balance (AWB) mode ---- Modes for which colour temperature ranges (K) are available have these settings in brackets. * off: turn off white balance calculation * auto: automatic mode (default) * sun: sunny mode (between 5000K and 6500K) * cloud: cloudy mode (between 6500K and 12000K) * shade: shade mode * tungsten: tungsten lighting mode (between 2500K and 3500K) * fluorescent: fluorescent lighting mode (between 2500K and 4500K) * incandescent: incandescent lighting mode * flash: flash mode * horizon: horizon mode * greyworld: Use this on the NoIR camera to fix incorrect AWB results due to the lack of the IR filter. Note that not all of these settings may be implemented, depending on camera type. ---- --imxfx, -ifx Set image effect ---- Set an effect to be applied to the image: * none: no effect (default) * negative: invert the image colours * solarise: solarise the image * posterise: posterise the image * whiteboard: whiteboard effect * blackboard: blackboard effect * sketch: sketch effect * denoise: denoise the image * emboss: emboss the image * oilpaint: oil paint effect * hatch: hatch sketch effect * gpen: graphite sketch effect * pastel: pastel effect * watercolour: watercolour effect * film: film grain effect * blur: blur the image * saturation: colour saturate the image * colourswap: not fully implemented * washedout: not fully implemented * colourpoint: not fully implemented * colourbalance: not fully implemented * cartoon: not fully implemented Note that not all of these settings may be available in all circumstances. ---- --colfx, -cfx Set colour effect ---- The supplied U and V parameters (range 0 - 255) are applied to the U and Y channels of the image. For example, --colfx 128:128 should result in a monochrome image. ---- --metering, -mm Set metering mode ---- Specify the metering mode used for the preview and capture: * average: average the whole frame for metering * spot: spot metering * backlit: assume a backlit image * matrix: matrix metering ---- --rotation, -rot Set image rotation (0 - 359) ---- Sets the rotation of the image in the viewfinder and resulting image. This can take any value from 0 upwards, but due to hardware constraints only 0, 90, 180, and 270 degree rotations are supported. ---- --hflip, -hf Set horizontal flip ---- Flips the preview and saved image horizontally. ---- --vflip, -vf Set vertical flip ---- Flips the preview and saved image vertically. ---- --roi, -roi Set sensor region of interest ---- Allows the specification of the area of the sensor to be used as the source for the preview and capture. This is defined as x,y for the top-left corner, and a width and height, with all values in normalised coordinates (0.0 - 1.0). So, to set a ROI at halfway across and down the sensor, and a width and height of a quarter of the sensor, use: ---- -roi 0.5,0.5,0.25,0.25 ---- ---- --shutter, -ss Set shutter speed/time ---- Sets the shutter open time to the specified value (in microseconds). Shutter speed limits are as follows: [cols="",^""] |=== | Camera Version | Max (microseconds) | V1 (OV5647) | 6000000 (i.e. 6s) | V2 (IMX219) | 10000000 (i.e. 10s) | HQ (IMX477) | 200000000 (i.e. 200s) |=== Using values above these maximums will result in undefined behaviour. ---- --drc, -drc Enable/disable dynamic range compression ---- DRC changes the images by increasing the range of dark areas, and decreasing the brighter areas. This can improve the image in low light areas. * off * low * med * high By default, DRC is off. ---- --stats, -st Use stills capture frame for image statistics ---- Force recomputation of statistics on stills capture pass. Digital gain and AWB are recomputed based on the actual capture frame statistics, rather than the preceding preview frame. ---- --awbgains, -awbg ---- Sets blue and red gains (as floating point numbers) to be applied when `-awb off` is set e.g. -awbg 1.5,1.2 ---- --analoggain, -ag ---- Sets the analog gain value directly on the sensor (floating point value from 1.0 to 8.0 for the OV5647 sensor on Camera Module V1, and 1.0 to 12.0 for the IMX219 sensor on Camera Module V2 and the IMX447 on the HQ Camera). ---- --digitalgain, -dg ---- Sets the digital gain value applied by the ISP (floating point value from 1.0 to 64.0, but values over about 4.0 will produce overexposed images) ---- --mode, -md ---- Sets a specified sensor mode, disabling the automatic selection. Possible values depend on the version of the Camera Module being used: Version 1.x (OV5647) |=== | Mode | Size | Aspect Ratio | Frame rates | FOV | Binning | 0 | automatic selection | | | | | 1 | 1920x1080 | 16:9 | 1-30fps | Partial | None | 2 | 2592x1944 | 4:3 | 1-15fps | Full | None | 3 | 2592x1944 | 4:3 | 0.1666-1fps | Full | None | 4 | 1296x972 | 4:3 | 1-42fps | Full | 2x2 | 5 | 1296x730 | 16:9 | 1-49fps | Full | 2x2 | 6 | 640x480 | 4:3 | 42.1-60fps | Full | 2x2 plus skip | 7 | 640x480 | 4:3 | 60.1-90fps | Full | 2x2 plus skip |=== Version 2.x (IMX219) |=== | Mode | Size | Aspect Ratio | Frame rates | FOV | Binning | 0 | automatic selection | | | | | 1 | 1920x1080 | 16:9 | 0.1-30fps | Partial | None | 2 | 3280x2464 | 4:3 | 0.1-15fps | Full | None | 3 | 3280x2464 | 4:3 | 0.1-15fps | Full | None | 4 | 1640x1232 | 4:3 | 0.1-40fps | Full | 2x2 | 5 | 1640x922 | 16:9 | 0.1-40fps | Full | 2x2 | 6 | 1280x720 | 16:9 | 40-90fps | Partial | 2x2 | 7 | 640x480 | 4:3 | 40-200fps^1^ | Partial | 2x2 |=== ^1^For frame rates over 120fps, it is necessary to turn off automatic exposure and gain control using `-ex off`. Doing so should achieve the higher frame rates, but exposure time and gains will need to be set to fixed values supplied by the user. HQ Camera |=== | Mode | Size | Aspect Ratio | Frame rates | FOV | Binning/Scaling | 0 | automatic selection | | | | | 1 | 2028x1080 | 169:90 | 0.1-50fps | Partial | 2x2 binned | 2 | 2028x1520 | 4:3 | 0.1-50fps | Full | 2x2 binned | 3 | 4056x3040 | 4:3 | 0.005-10fps | Full | None | 4 | 1332x990 | 74:55 | 50.1-120fps | Partial | 2x2 binned |=== ---- --camselect, -cs ---- Selects which camera to use on a multi-camera system. Use 0 or 1. ---- --annotate, -a Enable/set annotate flags or text ---- Adds some text and/or metadata to the picture. Metadata is indicated using a bitmask notation, so add them together to show multiple parameters. For example, 12 will show time(4) and date(8), since 4+8=12. Text may include date/time placeholders by using the '%' character, as used by http://man7.org/linux/man-pages/man3/strftime.3.html[strftime]. |=== | Value | Meaning | Example Output | -a 4 | Time | 20:09:33 | -a 8 | Date | 10/28/15 | -a 12 | 4+8=12 Show the date(4) and time(8) | 20:09:33 10/28/15 | -a 16 | Shutter Settings | | -a 32 | CAF Settings | | -a 64 | Gain Settings | | -a 128 | Lens Settings | | -a 256 | Motion Settings | | -a 512 | Frame Number | | -a 1024 | Black Background | | -a ""ABC %Y-%m-%d %X"" | Show some text | ABC %Y-%m-%d %X | -a 4 -a ""ABC %Y-%m-%d %X"" | Show custom http://man7.org/linux/man-pages/man3/strftime.3.html[formatted] date/time | ABC 2015-10-28 20:09:33 | -a 8 -a ""ABC %Y-%m-%d %X"" | Show custom http://man7.org/linux/man-pages/man3/strftime.3.html[formatted] date/time | ABC 2015-10-28 20:09:33 |=== ---- --annotateex, -ae Set extra annotation parameters ---- Specifies annotation size, text colour, and background colour. Colours are in hex YUV format. Size ranges from 6 - 160; default is 32. Asking for an invalid size should give you the default. |=== | Example | Explanation | -ae 32,0xff,0x808000 -a ""Annotation text"" | gives size 32 white text on black background | -ae 10,0x00,0x8080FF -a ""Annotation text"" | gives size 10 black text on white background |=== ---- --stereo, -3d ---- Select the specified stereo imaging mode; `sbs` selects side-by-side mode, `tb` selects top/bottom mode; `off` turns off stereo mode (the default). ---- --decimate, -dec ---- Halves the width and height of the stereo image. ---- --3dswap, -3dswap ---- Swaps the camera order used in stereoscopic imaging; NOTE: currently not working. ---- --settings, -set ---- Retrieves the current camera settings and writes them to stdout. === Application-specific Settings ==== `raspistill` ---- --width, -w Set image width --height, -h Set image height --quality, -q Set JPEG quality <0 to 100> ---- Quality 100 is almost completely uncompressed. 75 is a good all-round value. ---- --raw, -r Add raw Bayer data to JPEG metadata ---- This option inserts the raw Bayer data from the camera into the JPEG metadata. ---- --output, -o Output filename ---- Specifies the output filename. If not specified, no file is saved. If the filename is '-', then all output is sent to stdout. ---- --latest, -l Link latest frame to filename ---- Makes a file system link under this name to the latest frame. ---- --verbose, -v Output verbose information during run ---- Outputs debugging/information messages during the program run. ---- --timeout, -t Time before the camera takes picture and shuts down ---- The program will run for the specified length of time, entered in milliseconds. It then takes the capture and saves it if an output is specified. If a timeout value is not specified, then it is set to 5 seconds (-t 5000). Note that low values (less than 500ms, although it can depend on other settings) may not give enough time for the camera to start up and provide enough frames for the automatic algorithms like AWB and AGC to provide accurate results. If set to 0, the preview will run indefinitely, until stopped with CTRL-C. In this case no capture is made. ---- --timelapse, -tl time-lapse mode ---- The specific value is the time between shots in milliseconds. Note that you should specify `%04d` at the point in the filename where you want a frame count number to appear. So, for example, the code below will produce a capture every 2 seconds, over a total period of 30s, named `image0001.jpg`, `image0002.jpg` and so on, through to `image0015.jpg`. ---- -t 30000 -tl 2000 -o image%04d.jpg ---- Note that the `%04d` indicates a 4-digit number, with leading zeroes added to make the required number of digits. So, for example, `%08d` would result in an 8-digit number. If a time-lapse value of 0 is entered, the application will take pictures as fast as possible. Note that there's an minimum enforced pause of 30ms between captures to ensure that exposure calculations can be made. ---- --framestart, -fs ---- Specifies the first frame number in the timelapse. Useful if you have already saved a number of frames, and want to start again at the next frame. ---- --datetime, -dt ---- Instead of a simple frame number, the timelapse file names will use a date/time value of the format `aabbccddee`, where `aa` is the month, `bb` is the day of the month, `cc` is the hour, `dd` is the minute, and `ee` is the second. ---- --timestamp, -ts ---- Instead of a simple frame number, the timelapse file names will use a single number which is the Unix timestamp, i.e. the seconds since 1970. ---- --thumb, -th Set thumbnail parameters (x:y:quality) ---- Allows specification of the thumbnail image inserted into the JPEG file. If not specified, defaults are a size of 64x48 at quality 35. if `--thumb none` is specified, no thumbnail information will be placed in the file. This reduces the file size slightly. ---- --demo, -d Run a demo mode ---- This options cycles through the range of camera options. No capture is taken, and the demo will end at the end of the timeout period, irrespective of whether all the options have been cycled. The time between cycles should be specified as a millisecond value. ---- --encoding, -e Encoding to use for output file ---- Valid options are `jpg`, `bmp`, `gif`, and `png`. Note that unaccelerated image types (GIF, PNG, BMP) will take much longer to save than jpg, which is hardware accelerated. Also note that the filename suffix is completely ignored when deciding the encoding of a file. ---- --restart, -rs ---- Sets the JPEG restart marker interval to a specific value. Can be useful for lossy transport streams because it allows a broken JPEG file to still be partially displayed. ---- --exif, -x EXIF tag to apply to captures (format as 'key=value') ---- Allows the insertion of specific EXIF tags into the JPEG image. You can have up to 32 EXIF tag entries. This is useful for tasks like adding GPS metadata. For example, to set the longitude: ---- --exif GPS.GPSLongitude=5/1,10/1,15/1 ---- would set the longitude to 5 degs, 10 minutes, 15 seconds. See EXIF documentation for more details on the range of tags available; the supported tags are as follows: ---- IFD0.< or IFD1.< ImageWidth, ImageLength, BitsPerSample, Compression, PhotometricInterpretation, ImageDescription, Make, Model, StripOffsets, Orientation, SamplesPerPixel, RowsPerString, StripByteCounts, XResolution, YResolution, PlanarConfiguration, ResolutionUnit, TransferFunction, Software, DateTime, Artist, WhitePoint, PrimaryChromaticities, JPEGInterchangeFormat, JPEGInterchangeFormatLength, YCbCrCoefficients, YCbCrSubSampling, YCbCrPositioning, ReferenceBlackWhite, Copyright> EXIF.< ExposureTime, FNumber, ExposureProgram, SpectralSensitivity, ISOSpeedRatings, OECF, ExifVersion, DateTimeOriginal, DateTimeDigitized, ComponentsConfiguration, CompressedBitsPerPixel, ShutterSpeedValue, ApertureValue, BrightnessValue, ExposureBiasValue, MaxApertureValue, SubjectDistance, MeteringMode, LightSource, Flash, FocalLength, SubjectArea, MakerNote, UserComment, SubSecTime, SubSecTimeOriginal, SubSecTimeDigitized, FlashpixVersion, ColorSpace, PixelXDimension, PixelYDimension, RelatedSoundFile, FlashEnergy, SpatialFrequencyResponse, FocalPlaneXResolution, FocalPlaneYResolution, FocalPlaneResolutionUnit, SubjectLocation, ExposureIndex, SensingMethod, FileSource, SceneType, CFAPattern, CustomRendered, ExposureMode, WhiteBalance, DigitalZoomRatio, FocalLengthIn35mmFilm, SceneCaptureType, GainControl, Contrast, Saturation, Sharpness, DeviceSettingDescription, SubjectDistanceRange, ImageUniqueID> GPS.< GPSVersionID, GPSLatitudeRef, GPSLatitude, GPSLongitudeRef, GPSLongitude, GPSAltitudeRef, GPSAltitude, GPSTimeStamp, GPSSatellites, GPSStatus, GPSMeasureMode, GPSDOP, GPSSpeedRef, GPSSpeed, GPSTrackRef, GPSTrack, GPSImgDirectionRef, GPSImgDirection, GPSMapDatum, GPSDestLatitudeRef, GPSDestLatitude, GPSDestLongitudeRef, GPSDestLongitude, GPSDestBearingRef, GPSDestBearing, GPSDestDistanceRef, GPSDestDistance, GPSProcessingMethod, GPSAreaInformation, GPSDateStamp, GPSDifferential> EINT.< InteroperabilityIndex, InteroperabilityVersion, RelatedImageFileFormat, RelatedImageWidth, RelatedImageLength> ---- Note that a small subset of these tags will be set automatically by the camera system, but will be overridden by any EXIF options on the command line. Setting `--exif none` will prevent any EXIF information being stored in the file. This reduces the file size slightly. ---- --gpsdexif, -gps ---- Applies real-time EXIF information from any attached GPS dongle (using GSPD) to the image; requires `libgps.so` to be installed. ---- --fullpreview, -fp Full preview mode ---- This runs the preview window using the full resolution capture mode. Maximum frames per second in this mode is 15fps, and the preview will have the same field of view as the capture. Captures should happen more quickly, as no mode change should be required. This feature is currently under development. ---- --keypress, -k Keypress mode ---- The camera is run for the requested time (`-t`), and a capture can be initiated throughout that time by pressing the Enter key. Pressing X then Enter will exit the application before the timeout is reached. If the timeout is set to 0, the camera will run indefinitely until the user presses X then Enter. Using the verbose option (`-v`) will display a prompt asking for user input, otherwise no prompt is displayed. ---- --signal, -s Signal mode ---- The camera is run for the requested time (`-t`), and a capture can be initiated throughout that time by sending a `USR1` signal to the camera process. This can be done using the `kill` command. You can find the camera process ID using the `pgrep raspistill` command. `kill -USR1 ` ---- --burst, -bm ---- Sets burst capture mode. This prevents the camera from returning to preview mode in between captures, meaning that captures can be taken closer together. ==== `raspivid` ---- --width, -w Set image width ---- Width of resulting video. This should be between 64 and 1920. ---- --height, -h Set image height ---- Height of resulting video. This should be between 64 and 1080. ---- --bitrate, -b Set bitrate ---- Use bits per second, so 10Mbits/s would be `-b 10000000`. For H264, 1080p30 a high quality bitrate would be 15Mbits/s or more. Maximum bitrate is 25Mbits/s (`-b 25000000`), but much over 17Mbits/s won't show noticeable improvement at 1080p30. ---- --output, -o Output filename ---- Specify the output filename. If not specified, no file is saved. If the filename is '-', then all output is sent to stdout. To connect to a remote IPv4 host, use `tcp` or `udp` followed by the required IP Address. e.g. `tcp://192.168.1.2:1234` or `udp://192.168.1.2:1234`. To listen on a TCP port (IPv4) and wait for an incoming connection use `--listen (-l)` option, e.g. `raspivid -l -o tcp://0.0.0.0:3333` will bind to all network interfaces, `raspivid -l -o tcp://192.168.1.1:3333` will bind to a local IPv4. ---- --listen, -l ---- When using a network connection as the data sink, this option will make the system wait for a connection from the remote system before sending data. ---- --verbose, -v Output verbose information during run ---- Outputs debugging/information messages during the program run. ---- --timeout, -t Time before the camera takes picture and shuts down ---- The total length of time that the program will run for. If not specified, the default is 5000ms (5 seconds). If set to 0, the application will run indefinitely until stopped with Ctrl-C. ---- --demo, -d Run a demo mode ---- This options cycles through the range of camera options. No recording is done, and the demo will end at the end of the timeout period, irrespective of whether all the options have been cycled. The time between cycles should be specified as a millisecond value. ---- --framerate, -fps Specify the frames per second to record ---- At present, the minimum frame rate allowed is 2fps, and the maximum is 30fps. This is likely to change in the future. ---- --penc, -e Display preview image after encoding ---- Switch on an option to display the preview after compression. This will show any compression artefacts in the preview window. In normal operation, the preview will show the camera output prior to being compressed. This option is not guaranteed to work in future releases. ---- --intra, -g Specify the intra refresh period (key frame rate/GoP) ---- Sets the intra refresh period (GoP) rate for the recorded video. H264 video uses a complete frame (I-frame) every intra refresh period, from which subsequent frames are based. This option specifies the number of frames between each I-frame. Larger numbers here will reduce the size of the resulting video, and smaller numbers make the stream less error-prone. ---- --qp, -qp Set quantisation parameter ---- Sets the initial quantisation parameter for the stream. Varies from approximately 10 to 40, and will greatly affect the quality of the recording. Higher values reduce quality and decrease file size. Combine this setting with a bitrate of 0 to set a completely variable bitrate. ---- --profile, -pf Specify H264 profile to use for encoding ---- Sets the H264 profile to be used for the encoding. Options are: * baseline * main * high ---- --level, -lev ---- Specifies the H264 encoder level to use for encoding. Options are `4`, `4.1`, and `4.2`. ---- --irefresh, -if ---- Sets the H264 intra-refresh type. Possible options are `cyclic`, `adaptive`, `both`, and `cyclicrows`. ---- --inline, -ih Insert PPS, SPS headers ---- Forces the stream to include PPS and SPS headers on every I-frame. Needed for certain streaming cases e.g. Apple HLS. These headers are small, so don't greatly increase the file size. ---- --spstimings, -stm ---- Insert timing information into the SPS block. ---- --timed, -td Do timed switches between capture and pause ---- This options allows the video capture to be paused and restarted at particular time intervals. Two values are required: the on time and the off time. On time is the amount of time the video is captured, and off time is the amount it is paused. The total time of the recording is defined by the `timeout` option. Note that the recording may take slightly over the timeout setting depending on the on and off times. For example: ---- raspivid -o test.h264 -t 25000 -timed 2500,5000 ---- will record for a period of 25 seconds. The recording will be over a timeframe consisting of 2500ms (2.5s) segments with 5000ms (5s) gaps, repeating over the 20s. So the entire recording will actually be only 10s long, since 4 segments of 2.5s = 10s separated by 5s gaps. So: 2.5 record -- 5 pause - 2.5 record -- 5 pause - 2.5 record -- 5 pause -- 2.5 record gives a total recording period of 25s, but only 10s of actual recorded footage. ---- --keypress, -k Toggle between record and pause on Enter keypress ---- On each press of the Enter key, the recording will be paused or restarted. Pressing X then Enter will stop recording and close the application. Note that the timeout value will be used to signal the end of recording, but is only checked after each Enter keypress; so if the system is waiting for a keypress, even if the timeout has expired, it will still wait for the keypress before exiting. ---- --signal, -s Toggle between record and pause according to SIGUSR1 ---- Sending a `USR1` signal to the `raspivid` process will toggle between recording and paused. This can be done using the `kill` command, as below. You can find the `raspivid` process ID using `pgrep raspivid`. `kill -USR1 ` Note that the timeout value will be used to indicate the end of recording, but is only checked after each receipt of the `SIGUSR1` signal; so if the system is waiting for a signal, even if the timeout has expired, it will still wait for the signal before exiting. ---- --split, -sp ---- When in a signal or keypress mode, each time recording is restarted, a new file is created. ---- --circular, -c ---- Select circular buffer mode. All encoded data is stored in a circular buffer until a trigger is activated, then the buffer is saved. ---- --vectors, -x ---- Turns on output of motion vectors from the H264 encoder to the specified file name. ---- --flush, -fl ---- Forces a flush of output data buffers as soon as video data is written. This bypasses any OS caching of written data, and can decrease latency. ---- --save-pts, -pts ---- Saves timestamp information to the specified file. Useful as an input file to `mkvmerge`. ---- --codec, -cd ---- Specifies the encoder codec to use. Options are `H264` and `MJPEG`. H264 can encode up to 1080p, whereas MJPEG can encode up to the sensor size, but at decreased framerates due to the higher processing and storage requirements. ---- --initial, -i Define initial state on startup ---- Define whether the camera will start paused or will immediately start recording. Options are `record` or `pause`. Note that if you are using a simple timeout, and `initial` is set to `pause`, no output will be recorded. ---- --segment, -sg Segment the stream into multiple files ---- Rather than creating a single file, the file is split into segments of approximately the number of milliseconds specified. In order to provide different filenames, you should add `%04d` or similar at the point in the filename where you want a segment count number to appear e.g: ---- --segment 3000 -o video%04d.h264 ---- will produce video clips of approximately 3000ms (3s) long, named `video0001.h264`, `video0002.h264` etc. The clips should be seamless (no frame drops between clips), but the accuracy of each clip length will depend on the intraframe period, as the segments will always start on an I-frame. They will therefore always be equal or longer to the specified period. The most recent version of Raspivid will also allow the file name to be time-based, rather than using a segment number. For example: ---- --segment 3000 -o video_%c.h264 ---- will produce file names formatted like so: `video_Fri Jul 20 16:23:48 2018.h264` There are http://man7.org/linux/man-pages/man3/strftime.3.html[many different formatting options] available. Note than the `%d` and `%u` options are not available, as they are used for the segment number formatting, and that some combinations may produce invalid file names. ---- --wrap, -wr Set the maximum value for segment number ---- When outputting segments, this is the maximum the segment number can reach before it's reset to 1, giving the ability to keep recording segments, but overwriting the oldest one. So if set to 4, in the segment example above, the files produced will be `video0001.h264`, `video0002.h264`, `video0003.h264`, and `video0004.h264`. Once `video0004.h264` is recorded, the count will reset to 1, and `video0001.h264` will be overwritten. ---- --start, -sn Set the initial segment number ---- When outputting segments, this is the initial segment number, giving the ability to resume a previous recording from a given segment. The default value is 1. ---- --raw, -r ---- Specify the output file name for any raw data files requested. ---- --raw-format, -rf ---- Specify the raw format to be used if raw output requested. Options as `yuv`, `rgb`, and `grey`. `grey` simply saves the Y channel of the YUV image. ==== `raspiyuv` Many of the options for `raspiyuv` are the same as those for `raspistill`. This section shows the differences. Unsupported options: ---- --exif, --encoding, --thumb, --raw, --quality ---- Extra options : ---- --rgb, -rgb Save uncompressed data as RGB888 ---- This option forces the image to be saved as RGB data with 8 bits per channel, rather than YUV420. Note that the image buffers saved in `raspiyuv` are padded to a horizontal size divisible by 32, so there may be unused bytes at the end of each line. Buffers are also padded vertically to be divisible by 16, and in the YUV mode, each plane of Y,U,V is padded in this way. ---- --luma, -y ---- Only outputs the luma (Y) channel of the YUV image. This is effectively the black and white, or intensity, part of the image. ---- --bgr, -bgr ---- Saves the image data as BGR data rather than YUV. === Command Line Examples ==== Still Captures By default, captures are done at the highest resolution supported by the sensor. This can be changed using the `-w` and `-h` command line options. Take a default capture after 2s (times are specified in milliseconds) on the viewfinder, saving in `image.jpg`: [,bash] ---- raspistill -t 2000 -o image.jpg ---- Take a capture at a different resolution: [,bash] ---- raspistill -t 2000 -o image.jpg -w 640 -h 480 ---- Reduce the quality considerably to reduce file size: [,bash] ---- raspistill -t 2000 -o image.jpg -q 5 ---- Force the preview to appear at coordinate 100,100, with width 300 pixels and height 200 pixels: [,bash] ---- raspistill -t 2000 -o image.jpg -p 100,100,300,200 ---- Disable preview entirely: [,bash] ---- raspistill -t 2000 -o image.jpg -n ---- Save the image as a PNG file (lossless compression, but slower than JPEG). Note that the filename suffix is ignored when choosing the image encoding: [,bash] ---- raspistill -t 2000 -o image.png –e png ---- Add some EXIF information to the JPEG. This sets the Artist tag name to Boris, and the GPS altitude to 123.5m. Note that if setting GPS tags you should set as a minimum GPSLatitude, GPSLatitudeRef, GPSLongitude, GPSLongitudeRef, GPSAltitude, and GPSAltitudeRef: [,bash] ---- raspistill -t 2000 -o image.jpg -x IFD0.Artist=Boris -x GPS.GPSAltitude=1235/10 ---- Set an emboss image effect: [,bash] ---- raspistill -t 2000 -o image.jpg -ifx emboss ---- Set the U and V channels of the YUV image to specific values (128:128 produces a greyscale image): [,bash] ---- raspistill -t 2000 -o image.jpg -cfx 128:128 ---- Run preview for 2s, with no saved image: [,bash] ---- raspistill -t 2000 ---- Take a time-lapse picture, every 10 seconds for 10 minutes (10 minutes = 600000ms), naming the files `image_num_001_today.jpg`, `image_num_002_today.jpg` and so on, with the latest picture also available under the name `latest.jpg`: [,bash] ---- raspistill -t 600000 -tl 10000 -o image_num_%03d_today.jpg -l latest.jpg ---- Take a picture and send the image data to stdout: [,bash] ---- raspistill -t 2000 -o - ---- Take a picture and send the image data to a file: [,bash] ---- raspistill -t 2000 -o - > my_file.jpg ---- Run the camera forever, taking a picture when Enter is pressed: [,bash] ---- raspistill -t 0 -k -o my_pics%02d.jpg ---- ==== Video captures Image size and preview settings are the same as for stills capture. Default size for video recording is 1080p (1920x1080). Record a 5s clip with default settings (1080p30): [,bash] ---- raspivid -t 5000 -o video.h264 ---- Record a 5s clip at a specified bitrate (3.5Mbits/s): [,bash] ---- raspivid -t 5000 -o video.h264 -b 3500000 ---- Record a 5s clip at a specified framerate (5fps): [,bash] ---- raspivid -t 5000 -o video.h264 -f 5 ---- Encode a 5s camera stream and send the image data to stdout: [,bash] ---- raspivid -t 5000 -o - ---- Encode a 5s camera stream and send the image data to a file: [,bash] ---- raspivid -t 5000 -o - > my_file.h264 ---- === Shell Error Codes The applications described here will return a standard error code to the shell on completion. Possible error codes are: |=== | C Define | Code | Description | EX_OK | 0 | Application ran successfully | EX_USAGE | 64 | Bad command line parameter | EX_SOFTWARE | 70 | Software or camera error | | 130 | Application terminated by Ctrl-C |=== === Long Exposures The maximum exposure times of the three official Raspberry Pi cameras can be found in xref:camera.adoc#maximum-exposure-times[this table]. Due to the way the ISP works, by default asking for a long exposure can result in the capture process taking up to 7 times the exposure time, so a 200 second exposure on the HQ camera could take 1400 seconds to actually return an image. This is due to the way the camera system works out the correct exposures and gains to use in the image, using it's AGC (automatic gain control) and AWB (automatic white balance) algorithms. The system needs a few frames to calculate these numbers in order to produce a decent image. When combined with frame discards at the start of processing (in case they are corrupt), and the switching between preview and captures modes, this can result in up to 7 frames needed to produce a final image. With long exposures, that can take a long time. Fortunately, the camera parameters can be altered to reduce frame time dramatically; however this means turning off the automatic algorithms and manually providing values for the AGC. The AWB gains can usually be omitted as the legacy stack is able to reprocess the camera data to work them out (the `-st` option), though it is fine to specify them as well. Additionally, burst mode (`-bm`) with a short timeout should be requested to suppress the initial preview phase, and the exposure mode also needs disabling (`-ex off`). The following example will perform a 100 second exposure capture `raspistill -t 10 -bm -ex off -ag 1 -ss 100000000 -st -o long_exposure.jpg` === Shooting RAW using the Camera Modules The definition of raw images can vary. The usual meaning is raw Bayer data directly from the sensor, although some may regard an uncompressed image that has passed through the ISP (and has therefore been processed) as raw. For the latter, we recommend using the term _unencoded_ so as to be clear about the difference. Both options are available from the Raspberry Pi cameras. ==== Processed, Non-Lossy Images The usual output from `raspistill` is a compressed JPEG file that has passed through all the stages of image processing to produce a high-quality image. However, JPEG, being a lossy format does throw away some information that the user may want. `raspistill` has an `encoding` option that allows you to specify the output format: either `jpg`, `bmp`, `png` or `gif`. All but `jpg` are lossless, so no data is thrown away in an effort to improve compression, but do require conversion from the original YUV, and because these formats do not have hardware support they produce images slightly more slowly than JPEG. e.g. `raspistill --encoding png -o fred.png` Another option is to output completely formatted YUV420 or RGB data using the xref:camera.adoc#raspiyuv[`raspiyuv`] application. ==== Unprocessed Images For some applications, such as astrophotography, having the raw Bayer data direct from the sensor can be useful. This data will need to be post-processed to produce a useful image. `raspistill` has a raw option that will cause the Bayer data to be output. `raspistill --raw -o fred.jpg` The raw data is appended to the end of the JPEG file and will https://www.raspberrypi.com/news/processing-raw-image-files-from-a-raspberry-pi-high-quality-camera/[need to be extracted]. ",12460,True,2507.5448147805246,median "[[FTPComponent]] FTP/SFTP/FTPS Component ~~~~~~~~~~~~~~~~~~~~~~~ This component provides access to remote file systems over the FTP and SFTP protocols. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ----------------------------------------------------------------------- org.apache.camel camel-ftp x.x.xSee the documentation of the Apache Commons ----------------------------------------------------------------------- [Info] ==== More options See link:file2.html[File] for more options as all the options from link:file2.html[File] is inherited. ==== [Info] ==== Absolute paths Absolute path is *not* supported. *Camel 2.16* will translate absolute path to relative by trimming all leading slashes from `directoryname`. There'll be WARN message printed in the logs. ==== [Tip] ==== Consuming from remote FTP server Make sure you read the section titled _Default when consuming files_ further below for details related to consuming files. ==== [[FTP2-URIformat]] URI format ^^^^^^^^^^ [source,java] --------------------------------------------------------- ftp://[username@]hostname[:port]/directoryname[?options] sftp://[username@]hostname[:port]/directoryname[?options] ftps://[username@]hostname[:port]/directoryname[?options] --------------------------------------------------------- Where *directoryname* represents the underlying directory. The directory name is a relative path. Absolute path's is *not* supported. The relative path can contain nested folders, such as /inbox/us. For Camel versions before *Camel 2.16*, the directoryName *must* exist already as this component does not support the `autoCreate` option (which the file component does). The reason is that its the FTP administrator (FTP server) task to properly setup user accounts, and home directories with the right file permissions etc. For *Camel 2.16*, `autoCreate` option is supported. When consumer starts, before polling is scheduled, there's additional FTP operation performed to create the directory configured for endpoint. The default value for `autoCreate` is `true`. If no *username* is provided, then `anonymous` login is attempted using no password. + If no *port* number is provided, Camel will provide default values according to the protocol (ftp = 21, sftp = 22, ftps = 2222). You can append query options to the URI in the following format, `?option=value&option=value&...` This component uses two different libraries for the actual FTP work. FTP and FTPS uses http://commons.apache.org/net/[Apache Commons Net] while SFTP uses http://www.jcraft.com/jsch/[JCraft JSCH]. The FTPS component is only available in Camel 2.2 or newer. + FTPS (also known as FTP Secure) is an extension to FTP that adds support for the Transport Layer Security (TLS) and the Secure Sockets Layer (SSL) cryptographic protocols. [[FTP2-URIOptions]] URI Options ^^^^^^^^^^^ The options below are exclusive for the FTP component. [Info] ==== More options See link:file2.html[File] for more options as all the options from link:file2.html[File] is inherited. ==== // component options: START The FTP component has no options. // component options: END // endpoint options: START The FTP component supports 105 endpoint options which are listed below: {% raw %} [width=""100%"",cols=""2,1,1m,1m,5"",options=""header""] |======================================================================= | Name | Group | Default | Java Type | Description | host | common | | String | *Required* Hostname of the FTP server | port | common | | int | Port of the FTP server | directoryName | common | | String | The starting directory | binary | common | false | boolean | Specifies the file transfer mode BINARY or ASCII. Default is ASCII (false). | charset | common | | String | This option is used to specify the encoding of the file. You can use this on the consumer to specify the encodings of the files which allow Camel to know the charset it should load the file content in case the file content is being accessed. Likewise when writing a file you can use this option to specify which charset to write the file as well. | disconnect | common | false | boolean | Whether or not to disconnect from remote FTP server right after use. Disconnect will only disconnect the current connection to the FTP server. If you have a consumer which you want to stop then you need to stop the consumer/route instead. | doneFileName | common | | String | Producer: If provided then Camel will write a 2nd done file when the original file has been written. The done file will be empty. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders. The done file will always be written in the same folder as the original file. Consumer: If provided Camel will only consume files if a done file exists. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders.The done file is always expected in the same folder as the original file. Only $file.name and $file.name.noext is supported as dynamic placeholders. | fileName | common | | String | Use Expression such as File Language to dynamically set the filename. For consumers it's used as a filename filter. For producers it's used to evaluate the filename to write. If an expression is set it take precedence over the CamelFileName header. (Note: The header itself can also be an Expression). The expression options support both String and Expression types. If the expression is a String type it is always evaluated using the File Language. If the expression is an Expression type the specified Expression type is used - this allows you for instance to use OGNL expressions. For the consumer you can use it to filter filenames so you can for instance consume today's file using the File Language syntax: mydata-$date:now:yyyyMMdd.txt. The producers support the CamelOverruleFileName header which takes precedence over any existing CamelFileName header; the CamelOverruleFileName is a header that is used only once and makes it easier as this avoids to temporary store CamelFileName and have to restore it afterwards. | passiveMode | common | false | boolean | Sets passive mode connections. Default is active mode connections. | separator | common | UNIX | PathSeparator | Sets the path separator to be used. UNIX = Uses unix style path separator Windows = Uses windows style path separator Auto = (is default) Use existing path separator in file name | fastExistsCheck | common (advanced) | false | boolean | If set this option to be true camel-ftp will use the list file directly to check if the file exists. Since some FTP server may not support to list the file directly if the option is false camel-ftp will use the old way to list the directory and check if the file exists. This option also influences readLock=changed to control whether it performs a fast check to update file information or not. This can be used to speed up the process if the FTP server has a lot of files. | bridgeErrorHandler | consumer | false | boolean | Allows for bridging the consumer to the Camel routing Error Handler which mean any exceptions occurred while the consumer is trying to pickup incoming messages or the likes will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions that will be logged at WARN/ERROR level and ignored. | delete | consumer | false | boolean | If true the file will be deleted after it is processed successfully. | moveFailed | consumer | | String | Sets the move failure expression based on Simple language. For example to move files into a .error subdirectory use: .error. Note: When moving the files to the fail location Camel will handle the error and will not pick up the file again. | noop | consumer | false | boolean | If true the file is not moved or deleted in any way. This option is good for readonly data or for ETL type requirements. If noop=true Camel will set idempotent=true as well to avoid consuming the same files over and over again. | preMove | consumer | | String | Expression (such as File Language) used to dynamically set the filename when moving it before processing. For example to move in-progress files into the order directory set this value to order. | recursive | consumer | false | boolean | If a directory will look for files in all the sub-directories as well. | sendEmptyMessageWhenIdle | consumer | false | boolean | If the polling consumer did not poll any files you can enable this option to send an empty message (no body) instead. | streamDownload | consumer | false | boolean | Sets the download method to use when not using a local working directory. If set to true the remote files are streamed to the route as they are read. When set to false the remote files are loaded into memory before being sent into the route. | directoryMustExist | consumer (advanced) | false | boolean | Similar to startingDirectoryMustExist but this applies during polling recursive sub directories. | download | consumer (advanced) | false | boolean | Whether the FTP consumer should download the file. If this option is set to false then the message body will be null but the consumer will still trigger a Camel Exchange that has details about the file such as file name file size etc. It's just that the file will not be downloaded. | exceptionHandler | consumer (advanced) | | ExceptionHandler | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions that will be logged at WARN/ERROR level and ignored. | exchangePattern | consumer (advanced) | | ExchangePattern | Sets the exchange pattern when the consumer creates an exchange. | ignoreFileNotFoundOrPermissionError | consumer (advanced) | false | boolean | Whether to ignore when trying to download a file which does not exist or due to permission error. By default when a file does not exists or insufficient permission then an exception is thrown. Setting this option to true allows to ignore that instead. | inProgressRepository | consumer (advanced) | | String> | A pluggable in-progress repository org.apache.camel.spi.IdempotentRepository. The in-progress repository is used to account the current in progress files being consumed. By default a memory based repository is used. | localWorkDirectory | consumer (advanced) | | String | When consuming a local work directory can be used to store the remote file content directly in local files to avoid loading the content into memory. This is beneficial if you consume a very big remote file and thus can conserve memory. | onCompletionExceptionHandler | consumer (advanced) | | ExceptionHandler | To use a custom org.apache.camel.spi.ExceptionHandler to handle any thrown exceptions that happens during the file on completion process where the consumer does either a commit or rollback. The default implementation will log any exception at WARN level and ignore. | pollStrategy | consumer (advanced) | | PollingConsumerPollStrategy | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | processStrategy | consumer (advanced) | | GenericFileProcessStrategy | A pluggable org.apache.camel.component.file.GenericFileProcessStrategy allowing you to implement your own readLock option or similar. Can also be used when special conditions must be met before a file can be consumed such as a special ready file exists. If this option is set then the readLock option does not apply. | receiveBufferSize | consumer (advanced) | 32768 | int | The receive (download) buffer size Used only by FTPClient | startingDirectoryMustExist | consumer (advanced) | false | boolean | Whether the starting directory must exist. Mind that the autoCreate option is default enabled which means the starting directory is normally auto created if it doesn't exist. You can disable autoCreate and enable this to ensure the starting directory must exist. Will thrown an exception if the directory doesn't exist. | useList | consumer (advanced) | true | boolean | Whether to allow using LIST command when downloading a file. Default is true. In some use cases you may want to download a specific file and are not allowed to use the LIST command and therefore you can set this option to false. | fileExist | producer | Override | GenericFileExist | What to do if a file already exists with the same name. Override which is the default replaces the existing file. Append - adds content to the existing file. Fail - throws a GenericFileOperationException indicating that there is already an existing file. Ignore - silently ignores the problem and does not override the existing file but assumes everything is okay. Move - option requires to use the moveExisting option to be configured as well. The option eagerDeleteTargetFile can be used to control what to do if an moving the file and there exists already an existing file otherwise causing the move operation to fail. The Move option will move any existing files before writing the target file. TryRename Camel is only applicable if tempFileName option is in use. This allows to try renaming the file from the temporary name to the actual name without doing any exists check.This check may be faster on some file systems and especially FTP servers. | flatten | producer | false | boolean | Flatten is used to flatten the file name path to strip any leading paths so it's just the file name. This allows you to consume recursively into sub-directories but when you eg write the files to another directory they will be written in a single directory. Setting this to true on the producer enforces that any file name in CamelFileName header will be stripped for any leading paths. | moveExisting | producer | | String | Expression (such as File Language) used to compute file name to use when fileExist=Move is configured. To move files into a backup subdirectory just enter backup. This option only supports the following File Language tokens: file:name file:name.ext file:name.noext file:onlyname file:onlyname.noext file:ext and file:parent. Notice the file:parent is not supported by the FTP component as the FTP component can only move any existing files to a relative directory based on current dir as base. | tempFileName | producer | | String | The same as tempPrefix option but offering a more fine grained control on the naming of the temporary filename as it uses the File Language. | tempPrefix | producer | | String | This option is used to write the file using a temporary name and then after the write is complete rename it to the real name. Can be used to identify files being written and also avoid consumers (not using exclusive read locks) reading in progress files. Is often used by FTP when uploading big files. | allowNullBody | producer (advanced) | false | boolean | Used to specify if a null body is allowed during file writing. If set to true then an empty file will be created when set to false and attempting to send a null body to the file component a GenericFileWriteException of 'Cannot write null body to file.' will be thrown. If the fileExist option is set to 'Override' then the file will be truncated and if set to append the file will remain unchanged. | chmod | producer (advanced) | | String | Allows you to set chmod on the stored file. For example chmod=640. | disconnectOnBatchComplete | producer (advanced) | false | boolean | Whether or not to disconnect from remote FTP server right after a Batch upload is complete. disconnectOnBatchComplete will only disconnect the current connection to the FTP server. | eagerDeleteTargetFile | producer (advanced) | true | boolean | Whether or not to eagerly delete any existing target file. This option only applies when you use fileExists=Override and the tempFileName option as well. You can use this to disable (set it to false) deleting the target file before the temp file is written. For example you may write big files and want the target file to exists during the temp file is being written. This ensure the target file is only deleted until the very last moment just before the temp file is being renamed to the target filename. This option is also used to control whether to delete any existing files when fileExist=Move is enabled and an existing file exists. If this option copyAndDeleteOnRenameFails false then an exception will be thrown if an existing file existed if its true then the existing file is deleted before the move operation. | keepLastModified | producer (advanced) | false | boolean | Will keep the last modified timestamp from the source file (if any). Will use the Exchange.FILE_LAST_MODIFIED header to located the timestamp. This header can contain either a java.util.Date or long with the timestamp. If the timestamp exists and the option is enabled it will set this timestamp on the written file. Note: This option only applies to the file producer. You cannot use this option with any of the ftp producers. | sendNoop | producer (advanced) | true | boolean | Whether to send a noop command as a pre-write check before uploading files to the FTP server. This is enabled by default as a validation of the connection is still valid which allows to silently re-connect to be able to upload the file. However if this causes problems you can turn this option off. | activePortRange | advanced | | String | Set the client side port range in active mode. The syntax is: minPort-maxPort Both port numbers are inclusive eg 10000-19999 to include all 1xxxx ports. | autoCreate | advanced | true | boolean | Automatically create missing directories in the file's pathname. For the file consumer that means creating the starting directory. For the file producer it means the directory the files should be written to. | bufferSize | advanced | 131072 | int | Write buffer sized in bytes. | connectTimeout | advanced | 10000 | int | Sets the connect timeout for waiting for a connection to be established Used by both FTPClient and JSCH | ftpClient | advanced | | FTPClient | To use a custom instance of FTPClient | ftpClientConfig | advanced | | FTPClientConfig | To use a custom instance of FTPClientConfig to configure the FTP client the endpoint should use. | ftpClientConfigParameters | advanced | | Map | Used by FtpComponent to provide additional parameters for the FTPClientConfig | ftpClientParameters | advanced | | Map | Used by FtpComponent to provide additional parameters for the FTPClient | maximumReconnectAttempts | advanced | | int | Specifies the maximum reconnect attempts Camel performs when it tries to connect to the remote FTP server. Use 0 to disable this behavior. | reconnectDelay | advanced | | long | Delay in millis Camel will wait before performing a reconnect attempt. | siteCommand | advanced | | String | Sets optional site command(s) to be executed after successful login. Multiple site commands can be separated using a new line character (\\n). | soTimeout | advanced | 300000 | int | Sets the so timeout Used only by FTPClient | stepwise | advanced | true | boolean | Sets whether we should stepwise change directories while traversing file structures when downloading files or as well when uploading a file to a directory. You can disable this if you for example are in a situation where you cannot change directory on the FTP server due security reasons. | synchronous | advanced | false | boolean | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). | throwExceptionOnConnectFailed | advanced | false | boolean | Should an exception be thrown if connection failed (exhausted) By default exception is not thrown and a WARN is logged. You can use this to enable exception being thrown and handle the thrown exception from the org.apache.camel.spi.PollingConsumerPollStrategy rollback method. | timeout | advanced | 30000 | int | Sets the data timeout for waiting for reply Used only by FTPClient | antExclude | filter | | String | Ant style filter exclusion. If both antInclude and antExclude are used antExclude takes precedence over antInclude. Multiple exclusions may be specified in comma-delimited format. | antFilterCaseSensitive | filter | true | boolean | Sets case sensitive flag on ant fiter | antInclude | filter | | String | Ant style filter inclusion. Multiple inclusions may be specified in comma-delimited format. | eagerMaxMessagesPerPoll | filter | true | boolean | Allows for controlling whether the limit from maxMessagesPerPoll is eager or not. If eager then the limit is during the scanning of files. Where as false would scan all files and then perform sorting. Setting this option to false allows for sorting all files first and then limit the poll. Mind that this requires a higher memory usage as all file details are in memory to perform the sorting. | exclude | filter | | String | Is used to exclude files if filename matches the regex pattern (matching is case in-senstive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris | filter | filter | | GenericFileFilter | Pluggable filter as a org.apache.camel.component.file.GenericFileFilter class. Will skip files if filter returns false in its accept() method. | filterDirectory | filter | | String | Filters the directory based on Simple language. For example to filter on current date you can use a simple date pattern such as $date:now:yyyMMdd | filterFile | filter | | String | Filters the file based on Simple language. For example to filter on file size you can use $file:size 5000 | idempotent | filter | false | Boolean | Option to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. Will by default use a memory based LRUCache that holds 1000 entries. If noop=true then idempotent will be enabled as well to avoid consuming the same files over and over again. | idempotentKey | filter | | String | To use a custom idempotent key. By default the absolute path of the file is used. You can use the File Language for example to use the file name and file size you can do: idempotentKey=$file:name-$file:size | idempotentRepository | filter | | String> | A pluggable repository org.apache.camel.spi.IdempotentRepository which by default use MemoryMessageIdRepository if none is specified and idempotent is true. | include | filter | | String | Is used to include files if filename matches the regex pattern (matching is case in-senstive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris | maxDepth | filter | 2147483647 | int | The maximum depth to traverse when recursively processing a directory. | maxMessagesPerPoll | filter | | int | To define a maximum messages to gather per poll. By default no maximum is set. Can be used to set a limit of e.g. 1000 to avoid when starting up the server that there are thousands of files. Set a value of 0 or negative to disabled it. Notice: If this option is in use then the File and FTP components will limit before any sorting. For example if you have 100000 files and use maxMessagesPerPoll=500 then only the first 500 files will be picked up and then sorted. You can use the eagerMaxMessagesPerPoll option and set this to false to allow to scan all files first and then sort afterwards. | minDepth | filter | | int | The minimum depth to start processing when recursively processing a directory. Using minDepth=1 means the base directory. Using minDepth=2 means the first sub directory. | move | filter | | String | Expression (such as Simple Language) used to dynamically set the filename when moving it after processing. To move files into a .done subdirectory just enter .done. | exclusiveReadLockStrategy | lock | | GenericFileExclusiveReadLockStrategy | Pluggable read-lock as a org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy implementation. | readLock | lock | | String | Used by consumer to only poll the files if it has exclusive read-lock on the file (i.e. the file is not in-progress or being written). Camel will wait until the file lock is granted. This option provides the build in strategies: none - No read lock is in use markerFile - Camel creates a marker file (fileName.camelLock) and then holds a lock on it. This option is not available for the FTP component changed - Changed is using file length/modification timestamp to detect whether the file is currently being copied or not. Will at least use 1 sec to determine this so this option cannot consume files as fast as the others but can be more reliable as the JDK IO API cannot always determine whether a file is currently being used by another process. The option readLockCheckInterval can be used to set the check frequency. fileLock - is for using java.nio.channels.FileLock. This option is not avail for the FTP component. This approach should be avoided when accessing a remote file system via a mount/share unless that file system supports distributed file locks. rename - rename is for using a try to rename the file as a test if we can get exclusive read-lock. idempotent - (only for file component) idempotent is for using a idempotentRepository as the read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. idempotent-changed - (only for file component) idempotent-changed is for using a idempotentRepository and changed as the combined read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. idempotent-rename - (only for file component) idempotent-rename is for using a idempotentRepository and rename as the combined read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. Notice: The various read locks is not all suited to work in clustered mode where concurrent consumers on different nodes is competing for the same files on a shared file system. The markerFile using a close to atomic operation to create the empty marker file but its not guaranteed to work in a cluster. The fileLock may work better but then the file system need to support distributed file locks and so on. Using the idempotent read lock can support clustering if the idempotent repository supports clustering such as Hazelcast Component or Infinispan. | readLockCheckInterval | lock | 1000 | long | Interval in millis for the read-lock if supported by the read lock. This interval is used for sleeping between attempts to acquire the read lock. For example when using the changed read lock you can set a higher interval period to cater for slow writes. The default of 1 sec. may be too fast if the producer is very slow writing the file. Notice: For FTP the default readLockCheckInterval is 5000. The readLockTimeout value must be higher than readLockCheckInterval but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit. | readLockDeleteOrphanLockFiles | lock | true | boolean | Whether or not read lock with marker files should upon startup delete any orphan read lock files which may have been left on the file system if Camel was not properly shutdown (such as a JVM crash). If turning this option to false then any orphaned lock file will cause Camel to not attempt to pickup that file this could also be due another node is concurrently reading files from the same shared directory. | readLockLoggingLevel | lock | WARN | LoggingLevel | Logging level used when a read lock could not be acquired. By default a WARN is logged. You can change this level for example to OFF to not have any logging. This option is only applicable for readLock of types: changed fileLock rename. | readLockMarkerFile | lock | true | boolean | Whether to use marker file with the changed rename or exclusive read lock types. By default a marker file is used as well to guard against other processes picking up the same files. This behavior can be turned off by setting this option to false. For example if you do not want to write marker files to the file systems by the Camel application. | readLockMinAge | lock | 0 | long | This option applied only for readLock=change. This option allows to specify a minimum age the file must be before attempting to acquire the read lock. For example use readLockMinAge=300s to require the file is at last 5 minutes old. This can speedup the changed read lock as it will only attempt to acquire files which are at least that given age. | readLockMinLength | lock | 1 | long | This option applied only for readLock=changed. This option allows you to configure a minimum file length. By default Camel expects the file to contain data and thus the default value is 1. You can set this option to zero to allow consuming zero-length files. | readLockRemoveOnCommit | lock | false | boolean | This option applied only for readLock=idempotent. This option allows to specify whether to remove the file name entry from the idempotent repository when processing the file is succeeded and a commit happens. By default the file is not removed which ensures that any race-condition do not occur so another active node may attempt to grab the file. Instead the idempotent repository may support eviction strategies that you can configure to evict the file name entry after X minutes - this ensures no problems with race conditions. | readLockRemoveOnRollback | lock | true | boolean | This option applied only for readLock=idempotent. This option allows to specify whether to remove the file name entry from the idempotent repository when processing the file failed and a rollback happens. If this option is false then the file name entry is confirmed (as if the file did a commit). | readLockTimeout | lock | 10000 | long | Optional timeout in millis for the read-lock if supported by the read-lock. If the read-lock could not be granted and the timeout triggered then Camel will skip the file. At next poll Camel will try the file again and this time maybe the read-lock could be granted. Use a value of 0 or lower to indicate forever. Currently fileLock changed and rename support the timeout. Notice: For FTP the default readLockTimeout value is 20000 instead of 10000. The readLockTimeout value must be higher than readLockCheckInterval but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit. | backoffErrorThreshold | scheduler | | int | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | backoffIdleThreshold | scheduler | | int | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | backoffMultiplier | scheduler | | int | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | delay | scheduler | 500 | long | Milliseconds before the next poll. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour). | greedy | scheduler | false | boolean | If greedy is enabled then the ScheduledPollConsumer will run immediately again if the previous run polled 1 or more messages. | initialDelay | scheduler | 1000 | long | Milliseconds before the first poll starts. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour). | runLoggingLevel | scheduler | TRACE | LoggingLevel | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. | scheduledExecutorService | scheduler | | ScheduledExecutorService | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | scheduler | scheduler | none | ScheduledPollConsumerScheduler | To use a cron scheduler from either camel-spring or camel-quartz2 component | schedulerProperties | scheduler | | Map | To configure additional properties when using a custom scheduler or any of the Quartz2 Spring based scheduler. | startScheduler | scheduler | true | boolean | Whether the scheduler should be auto started. | timeUnit | scheduler | MILLISECONDS | TimeUnit | Time unit for initialDelay and delay options. | useFixedDelay | scheduler | true | boolean | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | shuffle | sort | false | boolean | To shuffle the list of files (sort in random order) | sortBy | sort | | String | Built-in sort by using the File Language. Supports nested sorts so you can have a sort by file name and as a 2nd group sort by modified date. | sorter | sort | | GenericFile> | Pluggable sorter as a java.util.Comparator class. | account | security | | String | Account to use for login | password | security | | String | Password to use for login | username | security | | String | Username to use for login |======================================================================= {% endraw %} // endpoint options: END [Info] ==== FTPS component default trust store When using the `ftpClient.` properties related to SSL with the FTPS component, the trust store accept all certificates. If you only want trust selective certificates, you have to configure the trust store with the `ftpClient.trustStore.xxx` options or by configuring a custom `ftpClient`. When using `sslContextParameters`, the trust store is managed by the configuration of the provided SSLContextParameters instance. ==== You can configure additional options on the `ftpClient` and `ftpClientConfig` from the URI directly by using the `ftpClient.` or `ftpClientConfig.` prefix. For example to set the `setDataTimeout` on the `FTPClient` to 30 seconds you can do: [source,java] -------------------------------------------------------------------------------------- from(""ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000"").to(""bean:foo""); -------------------------------------------------------------------------------------- You can mix and match and have use both prefixes, for example to configure date format or timezones. [source,java] ---------------------------------------------------------------------------------------------------------------------------- from(""ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000&ftpClientConfig.serverLanguageCode=fr"").to(""bean:foo""); ---------------------------------------------------------------------------------------------------------------------------- You can have as many of these options as you like. See the documentation of the Apache Commons FTP FTPClientConfig for possible options and more details. And as well for Apache Commons FTP FTPClient. If you do not like having many and long configuration in the url you can refer to the `ftpClient` or `ftpClientConfig` to use by letting Camel lookup in the link:registry.html[Registry] for it. For example: [source,java] -------------------------------------------------------------------------- -------------------------------------------------------------------------- And then let Camel lookup this bean when you use the # notation in the url. [source,java] ------------------------------------------------------------------------------------ from(""ftp://foo@myserver?password=secret&ftpClientConfig=#myConfig"").to(""bean:foo""); ------------------------------------------------------------------------------------ [[FTP2-MoreURIoptions]] More URI options ^^^^^^^^^^^^^^^^ [Info] ==== See link:file2.html[File2] as all the options there also applies for this component. ==== [[FTP2-Examples]] Examples ^^^^^^^^ `ftp://someone@someftpserver.com/public/upload/images/holiday2008?password=secret&binary=true` + `ftp://someoneelse@someotherftpserver.co.uk:12049/reports/2008/password=secret&binary=false` + `ftp://publicftpserver.com/download` [Warning] ==== FTP Consumer does not support concurrency The FTP consumer (with the same endpoint) does not support concurrency (the backing FTP client is not thread safe). + You can use multiple FTP consumers to poll from different endpoints. It is only a single endpoint that does not support concurrent consumers. The FTP producer does *not* have this issue, it supports concurrency. ==== [Tip] ==== More information This component is an extension of the link:file2.html[File] component. So there are more samples and details on the link:file2.html[File] component page. ==== [[FTP2-Defaultwhenconsumingfiles]] Default when consuming files ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The link:ftp2.html[FTP] consumer will by default leave the consumed files untouched on the remote FTP server. You have to configure it explicitly if you want it to delete the files or move them to another location. For example you can use `delete=true` to delete the files, or use `move=.done` to move the files into a hidden done sub directory. The regular link:file2.html[File] consumer is different as it will by default move files to a `.camel` sub directory. The reason Camel does *not* do this by default for the FTP consumer is that it may lack permissions by default to be able to move or delete files. [[FTP2-limitations]] limitations +++++++++++ The option *readLock* can be used to force Camel *not* to consume files that is currently in the progress of being written. However, this option is turned off by default, as it requires that the user has write access. See the options table at link:file2.html[File2] for more details about read locks. + There are other solutions to avoid consuming files that are currently being written over FTP; for instance, you can write to a temporary destination and move the file after it has been written. When moving files using `move` or `preMove` option the files are restricted to the FTP_ROOT folder. That prevents you from moving files outside the FTP area. If you want to move files to another area you can use soft links and move files into a soft linked folder. [[FTP2-MessageHeaders]] Message Headers ^^^^^^^^^^^^^^^ The following message headers can be used to affect the behavior of the component [width=""100%"",cols=""50%,50%"",options=""header"",] |======================================================================= |Header |Description |`CamelFileName` |Specifies the output file name (relative to the endpoint directory) to be used for the output message when sending to the endpoint. If this is not present and no expression either, then a generated message ID is used as the filename instead. |`CamelFileNameProduced` |The actual filepath (path + name) for the output file that was written. This header is set by Camel and its purpose is providing end-users the name of the file that was written. |`CamelFileIndex` |Current index out of total number of files being consumed in this batch. |`CamelFileSize` |Total number of files being consumed in this batch. |`CamelFileHost` |The remote hostname. |`CamelFileLocalWorkPath` |Path to the local work file, if local work directory is used. |======================================================================= In addition the FTP/FTPS consumer and producer will enrich the Camel `Message` with the following headers [width=""100%"",cols=""50%,50%"",options=""header"",] |======================================================================= |Header |Description |`CamelFtpReplyCode` |*Camel 2.11.1:* The FTP client reply code (the type is a integer) |`CamelFtpReplyString` | *Camel 2.11.1:* The FTP client reply string |======================================================================= [[FTP2-Abouttimeouts]] About timeouts ^^^^^^^^^^^^^^ The two set of libraries (see top) has different API for setting timeout. You can use the `connectTimeout` option for both of them to set a timeout in millis to establish a network connection. An individual `soTimeout` can also be set on the FTP/FTPS, which corresponds to using `ftpClient.soTimeout`. Notice SFTP will automatically use `connectTimeout` as its `soTimeout`. The `timeout` option only applies for FTP/FTSP as the data timeout, which corresponds to the `ftpClient.dataTimeout` value. All timeout values are in millis. [[FTP2-UsingLocalWorkDirectory]] Using Local Work Directory ^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel supports consuming from remote FTP servers and downloading the files directly into a local work directory. This avoids reading the entire remote file content into memory as it is streamed directly into the local file using `FileOutputStream`. Camel will store to a local file with the same name as the remote file, though with `.inprogress` as extension while the file is being downloaded. Afterwards, the file is renamed to remove the `.inprogress` suffix. And finally, when the link:exchange.html[Exchange] is complete the local file is deleted. So if you want to download files from a remote FTP server and store it as files then you need to route to a file endpoint such as: [source,java] ------------------------------------------------------------------------------------------------ from(""ftp://someone@someserver.com?password=secret&localWorkDirectory=/tmp"").to(""file://inbox""); ------------------------------------------------------------------------------------------------ [Tip] ==== *Optimization by renaming work file* The route above is ultra efficient as it avoids reading the entire file content into memory. It will download the remote file directly to a local file stream. The `java.io.File` handle is then used as the link:exchange.html[Exchange] body. The file producer leverages this fact and can work directly on the work file `java.io.File` handle and perform a `java.io.File.rename` to the target filename. As Camel knows it's a local work file, it can optimize and use a rename instead of a file copy, as the work file is meant to be deleted anyway. ==== [[FTP2-Stepwisechangingdirectories]] Stepwise changing directories ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel link:ftp2.html[FTP] can operate in two modes in terms of traversing directories when consuming files (eg downloading) or producing files (eg uploading) * stepwise * not stepwise You may want to pick either one depending on your situation and security issues. Some Camel end users can only download files if they use stepwise, while others can only download if they do not. At least you have the choice to pick (from Camel 2.6 onwards). In Camel 2.0 - 2.5 there is only one mode and it is: * before 2.5 not stepwise * 2.5 stepwise From Camel 2.6 onwards there is now an option `stepwise` you can use to control the behavior. Note that stepwise changing of directory will in most cases only work when the user is confined to it's home directory and when the home directory is reported as `""/""`. The difference between the two of them is best illustrated with an example. Suppose we have the following directory structure on the remote FTP server we need to traverse and download files: [source,java] -------------- / /one /one/two /one/two/sub-a /one/two/sub-b -------------- And that we have a file in each of sub-a (a.txt) and sub-b (b.txt) folder. [[FTP2-Usingstepwise]] Using stepwise=true (default mode) ++++++++++++++++++++++++++++++++++ [source,java] ---------------------------------------------------------- TYPE A 200 Type set to A PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,17,94 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CWD sub-a 250 CWD successful. ""/one/two/sub-a"" is current directory. PORT 127,0,0,1,17,95 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. ""/one/two"" is current directory. CWD sub-b 250 CWD successful. ""/one/two/sub-b"" is current directory. PORT 127,0,0,1,17,96 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. ""/one/two"" is current directory. CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. PORT 127,0,0,1,17,97 200 Port command successful RETR foo.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. CWD sub-a 250 CWD successful. ""/one/two/sub-a"" is current directory. PORT 127,0,0,1,17,98 200 Port command successful RETR a.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. CWD sub-b 250 CWD successful. ""/one/two/sub-b"" is current directory. PORT 127,0,0,1,17,99 200 Port command successful RETR b.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. QUIT 221 Goodbye disconnected. ---------------------------------------------------------- As you can see when stepwise is enabled, it will traverse the directory structure using CD xxx. [[FTP2-Notusingstepwise]] Using stepwise=false ++++++++++++++++++++ [source,java] ------------------------------------------- 230 Logged on TYPE A 200 Type set to A SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,4,122 200 Port command successful LIST one/two 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,123 200 Port command successful LIST one/two/sub-a 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,124 200 Port command successful LIST one/two/sub-b 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,125 200 Port command successful RETR one/two/foo.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,126 200 Port command successful RETR one/two/sub-a/a.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,127 200 Port command successful RETR one/two/sub-b/b.txt 150 Opening data channel for file transfer. 226 Transfer OK QUIT 221 Goodbye disconnected. ------------------------------------------- As you can see when not using stepwise, there are no CD operation invoked at all. [[FTP2-Samples]] Samples ^^^^^^^ In the sample below we set up Camel to download all the reports from the FTP server once every hour (60 min) as BINARY content and store it as files on the local file system. And the route using Spring DSL: [source,xml] ------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ [[FTP2-ConsumingaremoteFTPSserverimplicitSSLandclientauthentication]] Consuming a remote FTPS server (implicit SSL) and client authentication +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [source,java] -------------------------------------------------------------------------------------------------- from(""ftps://admin@localhost:2222/public/camel?password=admin&securityProtocol=SSL&isImplicit=true &ftpClient.keyStore.file=./src/test/resources/server.jks &ftpClient.keyStore.password=password&ftpClient.keyStore.keyPassword=password"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------- [[FTP2-ConsumingaremoteFTPSserverexplicitTLSandacustomtruststoreconfiguration]] Consuming a remote FTPS server (explicit TLS) and a custom trust store configuration ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [source,java] ---------------------------------------------------------------------------------------------------------------------------------------------------------------- from(""ftps://admin@localhost:2222/public/camel?password=admin&ftpClient.trustStore.file=./src/test/resources/server.jks&ftpClient.trustStore.password=password"") .to(""bean:foo""); ---------------------------------------------------------------------------------------------------------------------------------------------------------------- [[FTP2-Filterusingorg.apache.camel.component.file.GenericFileFilter]] Filter using `org.apache.camel.component.file.GenericFileFilter` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel supports pluggable filtering strategies. This strategy it to use the build in `org.apache.camel.component.file.GenericFileFilter` in Java. You can then configure the endpoint with such a filter to skip certain filters before being processed. In the sample we have built our own filter that only accepts files starting with report in the filename. And then we can configure our route using the *filter* attribute to reference our filter (using `#` notation) that we have defined in the spring XML file: [source,xml] --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- [[FTP2-FilteringusingANTpathmatcher]] Filtering using ANT path matcher ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The ANT path matcher is a filter that is shipped out-of-the-box in the *camel-spring* jar. So you need to depend on *camel-spring* if you are using Maven. + The reason is that we leverage Spring's http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/util/AntPathMatcher.html[AntPathMatcher] to do the actual matching. The file paths are matched with the following rules: * `?` matches one character * `*` matches zero or more characters * `**` matches zero or more directories in a path The sample below demonstrates how to use it: [[FTP2-UsingaproxywithSFTP]] Using a proxy with SFTP ^^^^^^^^^^^^^^^^^^^^^^^ To use an HTTP proxy to connect to your remote host, you can configure your route in the following way: [source,xml] ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- You can also assign a user name and password to the proxy, if necessary. Please consult the documentation for `com.jcraft.jsch.Proxy` to discover all options. [[FTP2-SettingpreferredSFTPauthenticationmethod]] Setting preferred SFTP authentication method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you want to explicitly specify the list of authentication methods that should be used by `sftp` component, use `preferredAuthentications` option. If for example you would like Camel to attempt to authenticate with private/public SSH key and fallback to user/password authentication in the case when no public key is available, use the following route configuration: [source,java] ------------------------------------------------------------------------------------------------------------- from(""sftp://localhost:9999/root?username=admin&password=admin&preferredAuthentications=publickey,password""). to(""bean:processFile""); ------------------------------------------------------------------------------------------------------------- [[FTP2-Consumingasinglefileusingafixedname]] Consuming a single file using a fixed name ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When you want to download a single file and knows the file name, you can use `fileName=myFileName.txt` to tell Camel the name of the file to download. By default the consumer will still do a FTP LIST command to do a directory listing and then filter these files based on the `fileName` option. Though in this use-case it may be desirable to turn off the directory listing by setting `useList=false`. For example the user account used to login to the FTP server may not have permission to do a FTP LIST command. So you can turn off this with `useList=false`, and then provide the fixed name of the file to download with `fileName=myFileName.txt`, then the FTP consumer can still download the file. If the file for some reason does not exist, then Camel will by default throw an exception, you can turn this off and ignore this by setting `ignoreFileNotFoundOrPermissionError=true`. For example to have a Camel route that pickup a single file, and delete it after use you can do [source,java] ------------------------------------------------------------------------------------------------------------------------------------------------------------- from(""ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true"") .to(""activemq:queue:report""); ------------------------------------------------------------------------------------------------------------------------------------------------------------- Notice that we have use all the options we talked above above. You can also use this with `ConsumerTemplate`. For example to download a single file (if it exists) and grab the file content as a String type: [source,java] ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- String data = template.retrieveBodyNoWait(""ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true"", String.class); ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [[FTP2-Debuglogging]] Debug logging ^^^^^^^^^^^^^ This component has log level *TRACE* that can be helpful if you have problems. [[FTP2-SeeAlso]] See Also ^^^^^^^^ * link:configuring-camel.html[Configuring Camel] * link:component.html[Component] * link:endpoint.html[Endpoint] * link:getting-started.html[Getting Started] * link:file2.html[File2] ",12264,False,2060.729717796334,median "/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2019, Nefelus Inc // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include ""extprocess.h"" //#include ""logger.h"" #include namespace rcx { extConductor::extConductor() { strcpy(_name, """"); _height = 0; _distance = 0; _thickness = 0; _min_width = 0; _min_spacing = 0; _origin_x = 0; _bottom_left_x = 0; _bottom_right_x = 0; _top_left_x = 0; _top_right_x = 0; _var_table_index = 0; _p = 0.0; _min_cw_del = 0; _max_cw_del = 0; _min_ct_del = 0; _max_ct_del = 0; _min_ca = 0; _max_ca = 0; _top_ext = 0; _bot_ext = 0; } void extConductor::printConductor(FILE* fp, Ath__parser* parse) { fprintf(fp, ""CONDUCTOR {\\n""); parse->printString(fp, ""\\t"", ""name"", _name); parse->printDouble(fp, ""\\t"", ""height"", _height, true); parse->printDouble(fp, ""\\t"", ""thickness"", _thickness, true); parse->printDouble(fp, ""\\t"", ""min_width"", _min_width, true); parse->printDouble(fp, ""\\t"", ""min_spacing"", _min_spacing, true); parse->printDouble(fp, ""\\t"", ""origin_x"", _origin_x, true); parse->printDouble(fp, ""\\t"", ""bottom_left_x"", _bottom_left_x, true); parse->printDouble(fp, ""\\t"", ""bottom_right_x"", _bottom_right_x, true); parse->printDouble(fp, ""\\t"", ""top_left_x"", _top_left_x, true); parse->printDouble(fp, ""\\t"", ""top_right_x"", _top_right_x, true); parse->printDouble(fp, ""\\t"", ""top_extension"", _top_ext, false); parse->printDouble(fp, ""\\t"", ""bottom_extension"", _bot_ext, false); parse->printInt(fp, ""\\t"", ""var_table"", _var_table_index, true); parse->printDouble(fp, ""\\t"", ""resistivity"", _p, true); fprintf(fp, ""}\\n""); } bool extConductor::readConductor(Ath__parser* parser) { if (parser->setDoubleVal(""distance"", 1, _distance)) return true; else if (parser->setDoubleVal(""height"", 1, _height)) return true; else if (parser->setDoubleVal(""thickness"", 1, _thickness)) return true; else if (parser->setDoubleVal(""min_width"", 1, _min_width)) return true; else if (parser->setDoubleVal(""min_spacing"", 1, _min_spacing)) return true; else if (parser->setDoubleVal(""origin_x"", 1, _origin_x)) return true; else if (parser->setDoubleVal(""bottom_left_x"", 1, _bottom_left_x)) return true; else if (parser->setDoubleVal(""bottom_right_x"", 1, _bottom_right_x)) return true; else if (parser->setDoubleVal(""top_left_x"", 1, _top_left_x)) return true; else if (parser->setDoubleVal(""top_right_x"", 1, _top_right_x)) return true; else if (parser->setIntVal(""var_table"", 1, _var_table_index)) return true; else if (parser->setDoubleVal(""resistivity"", 1, _p)) return true; else if (parser->setDoubleVal(""min_cw_del"", 1, _min_cw_del)) return true; else if (parser->setDoubleVal(""max_cw_del"", 1, _max_cw_del)) return true; else if (parser->setDoubleVal(""min_ct_del"", 1, _min_ct_del)) return true; else if (parser->setDoubleVal(""max_ct_del"", 1, _max_ct_del)) return true; else if (parser->setDoubleVal(""min_ca"", 1, _min_ca)) return true; else if (parser->setDoubleVal(""max_ca"", 1, _max_ca)) return true; else if (parser->setDoubleVal(""top_extension"", 1, _top_ext)) return true; else if (parser->setDoubleVal(""bottom_extension"", 1, _bot_ext)) return true; return false; } extDielectric::extDielectric() { strcpy(_name, """"); strcpy(_non_conformal_metal, """"); _epsilon = 0; _height = 0; _distance = 0; _thickness = 0; _left_thickness = 0; _right_thickness = 0; _top_thickness = 0; _bottom_thickness = 0; _conformal = false; _trench = false; _bottom_ext = 0; _slope = 0; _met = 0; _nextMet = 0; } void extDielectric::printDielectric(FILE* fp, Ath__parser* parse) { fprintf(fp, ""DIELECTRIC {\\n""); parse->printString(fp, ""\\t"", ""name"", _name); parse->printDouble(fp, ""\\t"", ""epsilon"", _epsilon); if (!_conformal && !_trench) parse->printString( fp, ""\\t"", ""non_conformal_metal"", _non_conformal_metal, true); parse->printDouble(fp, ""\\t"", ""height"", _height, true); parse->printDouble(fp, ""\\t"", ""thickness"", _thickness, true); parse->printDouble(fp, ""\\t"", ""left_thickness"", _left_thickness, true); parse->printDouble(fp, ""\\t"", ""right_thickness"", _right_thickness, true); parse->printDouble(fp, ""\\t"", ""top_thickness"", _top_thickness, true); parse->printDouble(fp, ""\\t"", ""bottom_thickness"", _bottom_thickness, true); parse->printDouble(fp, ""\\t"", ""bottom_ext"", _bottom_ext, true); parse->printDouble(fp, ""\\t"", ""slope"", _slope, false); parse->printInt(fp, ""\\t"", ""met"", _met, true); parse->printInt(fp, ""\\t"", ""next_met"", _nextMet, true); fprintf(fp, ""}\\n""); } void extDielectric::printDielectric(FILE* fp, float planeWidth, float planeThickness) { fprintf(fp, ""BOX NAME %-15s; CX=0; CY=%g; W=%g; H= %g; DIEL= %g;\\n"", _name, _height, planeWidth, planeThickness, _epsilon); } void extDielectric::printDielectric3D(FILE* fp, float blockWidth, float blockThickness, float blockLength) { fprintf(fp, ""BLOCK NAME %-15s; V1=0,%g,%g; LENGTH=%g; WIDTH=%g; HEIGHT=%g; "" ""DIEL=%g;\\n"", _name, _height - (blockThickness * 0.5), blockLength * 0.5, blockThickness, blockWidth, blockLength, _epsilon); } void extMasterConductor::writeRaphaelDielPoly(FILE* fp, double X, double width, extDielectric* diel) { fprintf(fp, ""POLY NAME= %s; "", diel->_name); fprintf(fp, "" COORD= ""); writeRaphaelPointXY(fp, X + _loLeft[0], _loLeft[2]); writeRaphaelPointXY(fp, X + _loRight[0], _loLeft[2]); writeRaphaelPointXY(fp, X + _hiRight[0], _hiRight[2]); writeRaphaelPointXY(fp, X + _hiLeft[0], _hiLeft[2]); fprintf(fp, "" DIEL=%g ;\\n"", diel->_epsilon); } void extMasterConductor::writeRaphaelDielPoly3D(FILE* fp, double X, double width, double length, extDielectric* diel) { fprintf(fp, ""POLY3D NAME= %s; "", diel->_name); fprintf(fp, "" COORD= ""); writeRaphaelPointXY(fp, X + _loLeft[0], _loLeft[2]); writeRaphaelPointXY(fp, X + _loRight[0], _loLeft[2]); writeRaphaelPointXY(fp, X + _hiRight[0], _hiRight[2]); writeRaphaelPointXY(fp, X + _hiLeft[0], _hiLeft[2]); fprintf(fp, ""V1=0,0,0; HEIGHT=%g;"", length); fprintf(fp, "" DIEL=%g ;\\n"", diel->_epsilon); } void extMasterConductor::printDielBox(FILE* fp, double X, double width, extDielectric* diel, const char* width_name) { // non conformal double thickness = _hiLeft[2] - _loLeft[2]; if (thickness == 0.0) return; if (width_name != NULL) { double height = _loLeft[2]; fprintf(fp, ""BOX NAME=%-15s; CX=0; CY=%6.3f; W=%s; H= %.3f; DIEL= %g;\\n"", diel->_name, height, width_name, thickness, diel->_epsilon); /* fprintf(stdout, ""BOX NAME=%-15s; CX=0; CY=%6.3f; W=%s; H= %.3f; DIEL= %g;\\n"", diel->_name, height, width_name, thickness, diel->_epsilon); */ odb::notice(0, ""BOX NAME=%-15s; CX=0; CY=%6.3f; W=%s; H= %.3f; DIEL= %g;\\n"", diel->_name, height, width_name, thickness, diel->_epsilon); } else { _loRight[0] = _loLeft[0] + width; _hiRight[0] = _hiLeft[0] + width; writeRaphaelDielPoly(fp, X, width, diel); // writeRaphaelDielPoly(stdout, X, width, diel); } } void extMasterConductor::printDielBox3D(FILE* fp, double X, double width, double length, extDielectric* diel, const char* width_name) { // non conformal if (width_name != NULL) { // double height= _loLeft[2]; double thickness = _hiLeft[2] - _loLeft[2]; fprintf(fp, ""BLOCK NAME=%-15s; V1=0,0,%6.3f; WIDTH=%s; LENGTH= %.3f; "" ""HEIGHT=%6.3f; DIEL= %g;\\n"", diel->_name, 0.5 * length, width_name, thickness, length, diel->_epsilon); /* fprintf(stdout, ""BLOCK NAME=%-15s; V1=0,0,%6.3f; WIDTH=%s; LENGTH= %.3f; HEIGHT=%6.3f; DIEL= %g;\\n"", diel->_name, 0.5*length, width_name, thickness, length, diel->_epsilon); */ odb::notice(0, ""BLOCK NAME=%-15s; V1=0,0,%6.3f; WIDTH=%s; LENGTH= %.3f; "" ""HEIGHT=%6.3f; DIEL= %g;\\n"", diel->_name, 0.5 * length, width_name, thickness, length, diel->_epsilon); } else { _loRight[0] = _loLeft[0] + width; _hiRight[0] = _hiLeft[0] + width; writeRaphaelDielPoly3D(fp, X, width, length, diel); } } void extProcess::writeProcess(FILE* fp, char* gndName, float planeWidth, float planeThickness) { fprintf(fp, ""WINDOW X1=%g; Y1=-1.0; X2=%g; Y2=%g; DIEL=1.0;\\n"", -planeWidth * 0.5, planeWidth * 0.5, planeThickness); for (uint jj = 1; jj < _dielTable->getCnt(); jj++) { extDielectric* diel = _dielTable->get(jj); // if (diel->_conformal) diel->printDielectric(fp, planeWidth, planeThickness); } fprintf(fp, ""BOX NAME=%s CX=0; CY=-0.5; W=%g; H=1.0; VOLT=0.0;\\n"", gndName, planeWidth); fprintf(fp, ""OPTIONS SET_GRID=10000;\\n""); } void extProcess::writeProcess3D(FILE* fp, char* gndName, float blockWidth, float blockThickness, float blockLength) { fprintf(fp, ""WINDOW3D V1=%g,0,0; V2=%g,%g,%g; DIEL=1.0;\\n"", -blockWidth * 0.5, blockWidth * 0.5, blockThickness, blockLength); for (uint jj = 1; jj < _dielTable->getCnt(); jj++) { extDielectric* diel = _dielTable->get(jj); // if (diel->_conformal) diel->printDielectric3D(fp, blockWidth, blockThickness, blockLength); } fprintf( fp, ""BLOCK NAME=%s; V1=0,-1,%g; LENGTH=1.0; WIDTH=%g, HEIGHT=%g; VOLT=0.0;\\n"", gndName, blockLength * 0.5, blockWidth, blockLength); fprintf(fp, ""OPTIONS SET_GRID=1000000;\\n""); } void extProcess::writeParam(FILE* fp, const char* name, double val) { fprintf(fp, ""param %s=%g;\\n"", name, val); } void extProcess::writeWindow(FILE* fp, const char* param_width_name, double y1, const char* param_thickness_name) { fprintf(fp, ""\\n$ Simulation window\\n""); fprintf(fp, ""WINDOW X1=-0.5*%s; Y1=%g; X2=0.5*%s; Y2=%s; DIEL=1.0;\\n"", param_width_name, y1, param_width_name, param_thickness_name); } void extProcess::writeWindow3D(FILE* fp, const char* param_width_name, double y1, const char* param_thickness_name, const char* param_length_name) { fprintf(fp, ""\\n$ Simulation window\\n""); fprintf(fp, ""WINDOW3D V1=-0.5*%s,%g,0; V2=0.5*%s,%s,%s; DIEL=1.0;\\n"", param_width_name, y1, param_width_name, param_thickness_name, param_length_name); } void extProcess::writeGround(FILE* fp, int met, const char* name, double width, double x1, double volt, bool diag) { if (met < 0) return; if (!met && diag) return; double y1 = -1.0; double th = 1.0; extMasterConductor* m; if (met > 0 && !diag) { m = getMasterConductor(met); y1 = m->_loLeft[2]; th = m->_hiLeft[2] - y1; m->writeRaphaelConformalGround(fp, x1, width, this); fprintf(fp, ""POLY NAME= M%d__%s; "", met, name); } else { fprintf(fp, ""POLY NAME= M0__%s; "", name); } fprintf(fp, "" COORD= ""); writeRaphaelPointXY(fp, x1, y1); writeRaphaelPointXY(fp, x1 + width, y1); writeRaphaelPointXY(fp, x1 + width, y1 + th); writeRaphaelPointXY(fp, x1, y1 + th); fprintf(fp, "" VOLT=%g ;\\n"", volt); fprintf(fp, ""OPTIONS SET_GRID=10000;\\n\\n""); } void extProcess::writeGround3D(FILE* fp, int met, const char* name, double width, double length, double x1, double volt, bool diag) { if (met < 0) return; double y1 = -1.0; double th = 1.0; if (!met || diag) { if (diag) fprintf(fp, ""POLY3D NAME= M0__w0; ""); else fprintf(fp, ""POLY3D NAME= M%d__w0; "", met); fprintf(fp, "" COORD= ""); writeRaphaelPointXY(fp, x1, y1); writeRaphaelPointXY(fp, x1 + width, y1); writeRaphaelPointXY(fp, x1 + width, y1 + th); writeRaphaelPointXY(fp, x1, y1 + th); fprintf(fp, "" V1=0,0,0; HEIGHT=%g;"", length); fprintf(fp, "" VOLT=%g ;\\n"", volt); fprintf(fp, ""OPTIONS SET_GRID=1000000;\\n\\n""); return; } double w, s, p; if (met > 0) { extMasterConductor* m = getMasterConductor(met); y1 = m->_loLeft[2]; th = m->_hiLeft[2] - y1; w = getConductor(met)->_min_width; s = getConductor(met)->_min_spacing; p = w + s; } double l = 2 * p; double end = length - 2 * p; while (l <= end) { fprintf(fp, ""POLY3D NAME= M%d__w0; "", met); fprintf(fp, "" COORD= ""); writeRaphaelPointXY(fp, x1, y1); writeRaphaelPointXY(fp, x1 + width, y1); writeRaphaelPointXY(fp, x1 + width, y1 + th); writeRaphaelPointXY(fp, x1, y1 + th); fprintf(fp, "" V1=0,0,%g; HEIGHT=%g;"", l, w); fprintf(fp, "" VOLT=%g ;\\n"", volt); l += p; } fprintf(fp, ""OPTIONS SET_GRID=1000000;\\n\\n""); } void extProcess::writeGround(FILE* fp, int met, const char* name, const char* param_width_name, double x1, double volt) { if (met < 0) return; double y1 = -0.5; double th = 1.0; if (met > 0) { extMasterConductor* m = getMasterConductor(met); y1 = m->_loLeft[2]; th = m->_hiLeft[2] - y1; } fprintf(fp, ""BOX NAME=M%d__%s CX=%g; CY=%g; W=%s; H=%g; VOLT=%g;\\n"", met, name, x1, y1, param_width_name, th, volt); fprintf(fp, ""OPTIONS SET_GRID=10000;\\n\\n""); } void extProcess::writeFullProcess(FILE* fp, double X, double width, char* width_name) { for (uint jj = 1; jj < _masterDielectricTable->getCnt(); jj++) { extMasterConductor* m = _masterDielectricTable->get(jj); extDielectric* diel = _dielTable->get(m->_condId); // if (diel->_conformal) m->printDielBox(fp, X, width, diel, width_name); } } void extProcess::writeFullProcess3D(FILE* fp, double X, double width, double length, char* width_name) { for (uint jj = 1; jj < _masterDielectricTable->getCnt(); jj++) { extMasterConductor* m = _masterDielectricTable->get(jj); extDielectric* diel = _dielTable->get(m->_condId); // if (diel->_conformal) m->printDielBox3D(fp, X, width, length, diel, width_name); } } void extProcess::writeFullProcess(FILE* fp, char* gndName, double planeWidth, double planeThickness) { fprintf(fp, ""param plane_width=%g;\\n"", planeWidth); fprintf(fp, ""WINDOW X1=%g; Y1=-1.0; X2=%g; Y2=%g; DIEL=1.0;\\n"", -planeWidth * 0.5, planeWidth * 0.5, planeThickness); for (uint jj = 1; jj < _masterDielectricTable->getCnt(); jj++) { extMasterConductor* m = _masterDielectricTable->get(jj); extDielectric* diel = _dielTable->get(m->_condId); // if (diel->_conformal) m->printDielBox(fp, 0.0, planeWidth, diel, ""plane_width""); } fprintf(fp, ""\\nBOX NAME=%s CX=0; CY=-0.5; W=%g; H=1.0; VOLT=0.0;\\n"", gndName, planeWidth); fprintf(fp, ""OPTIONS SET_GRID=10000;\\n\\n""); } void extProcess::writeProcessAndGround(FILE* wfp, const char* gndName, int underMet, int overMet, double X, double width, double thickness, bool diag) { const char* widthName = ""window_width""; const char* thicknessName = ""window_thichness""; writeParam(wfp, widthName, width); writeParam(wfp, thicknessName, thickness); // CX,CY bug : writeFullProcess(wfp, X, width, widthName); writeFullProcess(wfp, X, width, NULL); double y1 = 0.0; writeWindow(wfp, widthName, y1, thicknessName); fprintf(wfp, ""\\n$ Ground Plane(s)\\n""); // writeGround(wfp, underMet, gndName, widthName, 0.0, 0.0); // writeGround(wfp, overMet, gndName, widthName, 0.0, 0.0); writeGround(wfp, underMet, gndName, width, -0.5 * width, 0.0, diag); writeGround(wfp, overMet, gndName, width, -0.5 * width, 0.0, diag); } void extProcess::writeProcessAndGround3D(FILE* wfp, const char* gndName, int underMet, int overMet, double X, double width, double length, double thickness, double W, bool diag) { double wid, x; if (width > W) { wid = width; x = X; } else { wid = W + 10.0; x = -wid * 0.5; } const char* widthName = ""window_width""; const char* thicknessName = ""window_thichness""; const char* lengthName = ""window_length""; writeParam(wfp, widthName, wid); writeParam(wfp, thicknessName, thickness); writeParam(wfp, lengthName, length); // CX,CY bug : writeFullProcess(wfp, X, width, widthName); writeFullProcess3D(wfp, x, width, length, NULL); double y1 = 0.0; writeWindow3D(wfp, widthName, y1, thicknessName, lengthName); fprintf(wfp, ""\\n$ Ground Plane(s)\\n""); writeGround3D(wfp, 0, gndName, wid, length, -0.5 * wid, 0.0); double w, s, offset; if (underMet > 0) { w = getConductor(underMet)->_min_width; s = getConductor(underMet)->_min_spacing; offset = w + s; wid = W + 2 * offset; writeGround3D(wfp, underMet, gndName, wid, length, -0.5 * wid, 0.0); } if (overMet > 0) { w = getConductor(overMet)->_min_width; s = getConductor(overMet)->_min_spacing; offset = w + s; wid = W + 2 * offset; writeGround3D(wfp, overMet, gndName, wid, length, -0.5 * wid, 0.0); } } bool extDielectric::readDielectric(Ath__parser* parser) { if (strcmp(""non_conformal_metal"", parser->get(0)) == 0) { strcpy(_non_conformal_metal, parser->get(1)); _conformal = false; _trench = false; return true; } else if (strcmp(""conformal"", parser->get(0)) == 0) { _conformal = true; return true; } else if (strcmp(""trench"", parser->get(0)) == 0) { _trench = true; return true; } else if (parser->setDoubleVal(""epsilon"", 1, _epsilon)) return true; else if (parser->setDoubleVal(""distance"", 1, _distance)) return true; else if (parser->setIntVal(""met"", 1, _met)) return true; else if (parser->setIntVal(""next_met"", 1, _nextMet)) return true; else if (parser->setDoubleVal(""height"", 1, _height)) return true; else if (parser->setDoubleVal(""thickness"", 1, _thickness)) return true; else if (parser->setDoubleVal(""bottom_thickness"", 1, _bottom_thickness)) return true; else if (parser->setDoubleVal(""top_thickness"", 1, _top_thickness)) return true; else if (parser->setDoubleVal(""left_thickness"", 1, _left_thickness)) return true; else if (parser->setDoubleVal(""right_thickness"", 1, _right_thickness)) return true; else if (parser->setDoubleVal(""bottom_ext"", 1, _bottom_ext)) return true; else if (parser->setDoubleVal(""slope"", 1, _slope)) return true; return false; } extMasterConductor::extMasterConductor(uint condId, extConductor* cond, double prevHeight) { _condId = condId; // X coordinates double min_width = cond->_min_width; if (cond->_bottom_right_x - cond->_bottom_left_x > 0) { _loLeft[0] = cond->_bottom_left_x; _loRight[0] = cond->_bottom_right_x; } else { if (cond->_bot_ext == 0.0) _loLeft[0] = 0; else _loLeft[0] = -cond->_bot_ext; if (!(min_width > 0)) { /* fprintf(stdout, ""Cannot determine Bottom Width for Conductor <%s>\\n"", cond->_name); */ odb::warning( 0, ""Cannot determine Bottom Width for Conductor <%s>\\n"", cond->_name); exit(0); } if (cond->_bot_ext == 0.0) _loRight[0] = min_width; else _loRight[0] = min_width + cond->_bot_ext; } _hiLeft[0] = cond->_top_left_x; _hiRight[0] = cond->_top_right_x; if (cond->_top_right_x - cond->_top_left_x > 0) { _hiLeft[0] = cond->_top_left_x; _hiRight[0] = cond->_top_right_x; } else { if (cond->_top_ext == 0.0) _hiLeft[0] = 0; else _hiLeft[0] = -cond->_top_ext; if (!(min_width > 0)) { /* fprintf(stdout, ""Cannot determine Top Width for Conductor <%s>\\n"", cond->_name); */ odb::warning( 0, ""Cannot determine Top Width for Conductor <%s>\\n"", cond->_name); exit(0); } if (cond->_top_ext == 0.0) _hiRight[0] = min_width; else _hiRight[0] = min_width + cond->_top_ext; } // Y coordinates _loLeft[1] = 0; _loRight[1] = 0; _hiLeft[1] = 0; _hiRight[1] = 0; // Z coordinates double height = cond->_height; if (height <= 0) { height += prevHeight + cond->_distance; cond->_height = height; } _loLeft[2] = height; _loRight[2] = height; double thickness = cond->_thickness; if (!(thickness > 0)) { /* fprintf(stdout, ""Cannot determine thickness for Conductor <%s>\\n"", cond->_name); */ odb::warning( 0, ""Cannot determine thickness for Conductor <%s>\\n"", cond->_name); exit(0); } _hiLeft[2] = height + thickness; _hiRight[2] = height + thickness; _dy = 0; _e = 0.0; for (uint i = 0; i < 3; i++) _conformalId[i] = 0; } void extMasterConductor::resetThicknessHeight(double height, double thickness) { _hiLeft[2] = height + thickness; _hiRight[2] = height + thickness; _loLeft[2] = _hiLeft[2] - thickness; _loRight[2] = _loLeft[2]; } void extMasterConductor::resetWidth(double top_width, double bottom_width) { _loLeft[0] = -bottom_width / 2; _loRight[0] = bottom_width / 2; _hiLeft[0] = -top_width / 2; _hiRight[0] = top_width / 2; } void extMasterConductor::reset(double height, double top_width, double bottom_width, double thickness) { _loLeft[0] = -bottom_width / 2; _loRight[0] = bottom_width / 2; _hiLeft[0] = -top_width / 2; _hiRight[0] = top_width / 2; // Y coordinates _loLeft[1] = 0; _loRight[1] = 0; _hiLeft[1] = 0; _hiRight[1] = 0; // Z coordinates // assume target height and thickness were set _hiLeft[2] = height + thickness; _hiRight[2] = height + thickness; _loLeft[2] = _hiLeft[2] - thickness; _loRight[2] = _loLeft[2]; //_hiLeft[2]= height + thickness; //_hiRight[2]= height + thickness; //_loLeft[2]= height; //_loRight[2]= height; } double extMasterConductor::writeRaphaelBox(FILE* fp, uint wireNum, double width, double X, double volt) { return writeRaphaelPoly(fp, wireNum, width, X, volt); fprintf(fp, ""BOX NAME=""); writeBoxName(fp, wireNum); fprintf(fp, "" CX=%g; CY=%g; W=%g; H=%g; VOLT=%g\\n"", X, _loLeft[2], width, _hiLeft[2] - _loLeft[2], volt); return X + width; } void extMasterConductor::writeRaphaelPointXY(FILE* fp, double X, double Y) { fprintf(fp, "" %6.3f,%6.3f ; "", X, Y); } void extProcess::writeRaphaelPointXY(FILE* fp, double X, double Y) { fprintf(fp, "" %6.3f,%6.3f ; "", X, Y); } void extMasterConductor::writeRaphaelPoly(FILE* fp, uint wireNum, double X, double volt) { fprintf(fp, ""POLY NAME=""); writeBoxName(fp, wireNum); fprintf(fp, "" COORD= ""); writeRaphaelPointXY(fp, X + _loLeft[0], _loLeft[2]); writeRaphaelPointXY(fp, X + _loRight[0], _loLeft[2]); writeRaphaelPointXY(fp, X + _hiRight[0], _hiRight[2]); writeRaphaelPointXY(fp, X + _hiLeft[0], _hiLeft[2]); fprintf(fp, "" VOLT=%g\\n"", volt); } void extMasterConductor::writeRaphaelConformalPoly(FILE* fp, double width, double X, extProcess* p) { double height[3]; double thickness[3]; double bottom_ext[3]; double slope[3]; double e[3]; bool trench = false; uint cnt = 0; uint start = 0; double h = _loLeft[2]; for (uint i = 0; i < 3; i++) { uint j = 2 - i; if (!_conformalId[j]) continue; if (!start) start = i; extDielectric* d = p->getDielectric(_conformalId[j]); // assuming conformal and trench will not show up at the same time. Also // height for the trench layer is negative. trench = d->_trench; height[i] = d->_height; thickness[i] = d->_thickness; bottom_ext[i] = d->_bottom_ext; slope[i] = d->_slope; e[i] = d->_epsilon; h += d->_thickness; cnt++; } if (!cnt) return; if (trench) { for (uint j = start; j < start + cnt; j++) { fprintf(fp, ""POLY NAME=""); fprintf(fp, ""M%d_Trench%d;"", _condId, 2 - j); if (width == 0.0) { writeRaphaelPointXY( fp, X + _loLeft[0] - bottom_ext[j], _hiRight[2] + height[j]); writeRaphaelPointXY( fp, X + _loRight[0] + bottom_ext[j], _hiRight[2] + height[j]); writeRaphaelPointXY(fp, X + _hiRight[0] + bottom_ext[j], _hiRight[2]); writeRaphaelPointXY(fp, X + _hiLeft[0] - bottom_ext[j], _hiRight[2]); fprintf(fp, "" DIEL=%g\\n"", e[j]); } else { writeRaphaelPointXY(fp, X - bottom_ext[j], _hiRight[2] + height[j]); writeRaphaelPointXY( fp, X + width + bottom_ext[j], _hiRight[2] + height[j]); writeRaphaelPointXY(fp, X + width + bottom_ext[j], _hiRight[2]); writeRaphaelPointXY(fp, X - bottom_ext[j], _hiRight[2]); fprintf(fp, "" DIEL=%g\\n"", e[j]); } } return; } double dx; for (uint j = start; j < start + cnt; j++) { fprintf(fp, ""POLY NAME=""); fprintf(fp, ""M%d_Conformal%d;"", _condId, 2 - j); if (width == 0.0) { if (slope[j]) dx = (height[j] - thickness[j]) / slope[j]; else dx = bottom_ext[j]; writeRaphaelPointXY(fp, X + _loLeft[0] - bottom_ext[j], h); writeRaphaelPointXY(fp, X + _loRight[0] + bottom_ext[j], h); h -= thickness[j]; writeRaphaelPointXY( fp, X + _hiRight[0] + bottom_ext[j] - dx, h + height[j]); writeRaphaelPointXY( fp, X + _hiLeft[0] - bottom_ext[j] + dx, h + height[j]); fprintf(fp, "" DIEL=%g\\n"", e[j]); } else { if (slope[j]) dx = (height[j] - thickness[j]) / slope[j]; else dx = bottom_ext[j]; writeRaphaelPointXY(fp, X - bottom_ext[j], h); writeRaphaelPointXY(fp, X + width + bottom_ext[j], h); h -= thickness[j]; writeRaphaelPointXY(fp, X + width + bottom_ext[j] - dx, h + height[j]); writeRaphaelPointXY(fp, X - bottom_ext[j] + dx, h + height[j]); fprintf(fp, "" DIEL=%g\\n"", e[j]); } } } void extMasterConductor::writeRaphaelConformalGround(FILE* fp, double X, double width, extProcess* p) { double height[3]; double thickness[3]; double bottom_ext[3]; double slope[3]; double e[3]; bool trench = false; uint cnt = 0; uint start = 0; double h = _loLeft[2]; for (uint i = 0; i < 3; i++) { uint j = 2 - i; if (!_conformalId[j]) continue; if (!start) start = i; extDielectric* d = p->getDielectric(_conformalId[j]); // assuming conformal and trench will not show up at the same time. Also // height for the trench layer is negative. trench = d->_trench; height[i] = d->_height; thickness[i] = d->_thickness; bottom_ext[i] = d->_bottom_ext; slope[i] = d->_slope; e[i] = d->_epsilon; h += d->_thickness; cnt++; } if (!cnt) return; if (trench) { for (uint j = start; j < start + cnt; j++) { fprintf(fp, ""POLY NAME=""); fprintf(fp, ""M%d_Trench%d;"", _condId, 2 - j); writeRaphaelPointXY(fp, X, _hiRight[2] + height[j]); writeRaphaelPointXY(fp, X + width, _hiRight[2] + height[j]); writeRaphaelPointXY(fp, X + width, _hiRight[2]); writeRaphaelPointXY(fp, X, _hiRight[2]); fprintf(fp, "" DIEL=%g\\n"", e[j]); } return; } for (uint j = start; j < start + cnt; j++) { fprintf(fp, ""POLY NAME=""); fprintf(fp, ""M%d_Conformal%d;"", _condId, 2 - j); h -= thickness[j]; writeRaphaelPointXY(fp, X, h); writeRaphaelPointXY(fp, X + width, h); writeRaphaelPointXY(fp, X + width, h + height[j]); writeRaphaelPointXY(fp, X, h + height[j]); fprintf(fp, "" DIEL=%g\\n"", e[j]); } } void extMasterConductor::writeRaphaelPoly3D(FILE* fp, uint wireNum, double X, double length, double volt) { fprintf(fp, ""POLY3D NAME=""); writeBoxName(fp, wireNum); fprintf(fp, "" COORD= ""); writeRaphaelPointXY(fp, X + _loLeft[0], _loLeft[2]); writeRaphaelPointXY(fp, X + _loRight[0], _loLeft[2]); writeRaphaelPointXY(fp, X + _hiRight[0], _hiRight[2]); writeRaphaelPointXY(fp, X + _hiLeft[0], _hiLeft[2]); fprintf(fp, ""V1=0,0,0; HEIGHT=%g;"", length); fprintf(fp, "" VOLT=%g\\n"", volt); } double extMasterConductor::writeRaphaelPoly(FILE* fp, uint wireNum, double width, double X, double volt, extProcess* p) { fprintf(fp, ""POLY NAME=""); writeBoxName(fp, wireNum); fprintf(fp, "" COORD= ""); extConductor* cond = p->getConductor(_condId); double top_ext = cond->_top_ext; double bot_ext = cond->_bot_ext; writeRaphaelPointXY(fp, X - bot_ext, _loLeft[2]); writeRaphaelPointXY(fp, X + width + bot_ext, _loLeft[2]); writeRaphaelPointXY(fp, X + width + top_ext, _hiRight[2]); writeRaphaelPointXY(fp, X - top_ext, _hiLeft[2]); fprintf(fp, "" VOLT=%g\\n"", volt); return X + width; } double extMasterConductor::writeRaphaelPoly3D(FILE* fp, uint wireNum, double width, double length, double X, double volt) { fprintf(fp, ""POLY3D NAME=""); writeBoxName(fp, wireNum); fprintf(fp, "" COORD= ""); writeRaphaelPointXY(fp, X, _loLeft[2]); writeRaphaelPointXY(fp, X + width, _loLeft[2]); writeRaphaelPointXY(fp, X + width, _hiRight[2]); writeRaphaelPointXY(fp, X, _hiLeft[2]); fprintf(fp, "" V1=0,0,0; HEIGHT=%g;"", length); fprintf(fp, "" VOLT=%g\\n"", volt); return X + width; } void extMasterConductor::writeBoxName(FILE* fp, uint wireNum) { fprintf(fp, ""M%d_w%d;"", _condId, wireNum); } extMasterConductor::extMasterConductor(uint dielId, extDielectric* diel, double xlo, double dx1, double xhi, double dx2, double h, double th) { _condId = dielId; // X coordinates _loLeft[0] = xlo; _loRight[0] = xlo + dx1; _hiLeft[0] = xhi; _hiRight[0] = xhi + dx2; // Y coordinates _loLeft[1] = 0; _loRight[1] = 0; _hiLeft[1] = 0; _hiRight[1] = 0; // Z coordinates _loLeft[2] = h; _loRight[2] = h; if (!(th > 0)) { /* fprintf(stdout, ""Cannot determine thickness for Diel <%s>\\n"", diel->_name); */ odb::warning(0, ""Cannot determine thickness for Diel <%s>\\n"", diel->_name); // exit(0); } _hiLeft[2] = h + th; _hiRight[2] = h + th; _dy = 0; _e = diel->_epsilon; for (uint i = 0; i < 3; i++) _conformalId[i] = 0; } FILE* extProcess::openFile(const char* filename, const char* permissions) { FILE* fp = fopen(filename, permissions); if (fp == NULL) { // fprintf(stdout, ""cannot open file %s with permissions <%s>\\n"", // filename, permissions); odb::warning(0, ""cannot open file %s with permissions <%s>\\n"", filename, permissions); exit(0); } return fp; } double extProcess::adjustMasterLayersForHeight(uint met, double thickness) { double condThickness = _condTable->get(met)->_thickness; double dth = (thickness - condThickness) / condThickness; double h = 0.0; for (uint ii = 1; ii < _masterConductorTable->getCnt(); ii++) { extConductor* cond = _condTable->get(ii); extMasterConductor* m = _masterConductorTable->get(ii); if (_thickVarFlag) h += cond->_distance * (1 + dth); else h += cond->_distance; double th = cond->_thickness; if (_thickVarFlag) th *= (1 + dth); else if (ii == met) th = thickness; m->resetThicknessHeight(h, th); h += th; } return dth; } double extProcess::adjustMasterDielectricsForHeight(uint met, double dth) { double h = 0.0; for (uint ii = 1; ii < _masterDielectricTable->getCnt(); ii++) { extDielectric* diel = _dielTable->get(ii); extMasterConductor* m = _masterDielectricTable->get(ii); double th = diel->_thickness; if (_thickVarFlag) th *= (1 + dth); else if (diel->_met == (int) met) th *= (1 + dth); m->resetThicknessHeight(h, th); h += th; } return h; } void extProcess::createMasterLayers() { double upperCondHeight = 0; for (uint ii = 1; ii < _condTable->getCnt(); ii++) { extConductor* cond = _condTable->get(ii); extMasterConductor* m = new extMasterConductor(ii, cond, upperCondHeight); _masterConductorTable->add(m); upperCondHeight = cond->_height + cond->_thickness; } double h = 0.0; for (uint jj = 1; jj < _dielTable->getCnt(); jj++) { extDielectric* diel = _dielTable->get(jj); if ((diel->_conformal || diel->_trench) && diel->_met) { extMasterConductor* mm = _masterConductorTable->get(diel->_met); for (uint i = 0; i < 3; i++) { if (!mm->_conformalId[i]) { mm->_conformalId[i] = jj; break; } } } // if (diel->_conformal) { extMasterConductor* m = new extMasterConductor(jj, diel, 0, 0, 0, 0, h, diel->_thickness); h += diel->_thickness; _masterDielectricTable->add(m); /* } else { extMasterConductor *m= new extMasterConductor(jj, diel, 0, 0, 0, 0, 0, 0); _masterDielectricTable->add(m); } */ } } extConductor* extProcess::getConductor(uint ii) { return _condTable->get(ii); } extMasterConductor* extProcess::getMasterConductor(uint ii) { return _masterConductorTable->get(ii); } extDielectric* extProcess::getDielectric(uint ii) { return _dielTable->get(ii); } Ath__array1D* extProcess::getWidthTable(uint met) { double min_width = getConductor(met)->_min_width; // const double wTable[7]= {1.0, 1.5, 2.0, 2.5, 3, 3.5, 4}; // const double wTable[3]= {1.0, 1.5, 2.0 }; const double wTable[8] = {1.0, 1.5, 2.0, 2.5, 3, 4, 5, 10}; // Ath__array1D* A= new Ath__array1D(8); Ath__array1D* A = new Ath__array1D(11); // for (uint ii= 0; ii<7; ii++) { // for (uint ii= 0; ii<3; ii++) { for (uint ii = 0; ii < 8; ii++) { double w = wTable[ii] * min_width; A->add(w); } return A; } Ath__array1D* extProcess::getSpaceTable(uint met) { double min_spacing = getConductor(met)->_min_spacing; // const double sTable[18]= {1.0, 1.2, 1.5, 1.7, 2.0, 2.25, 2.5, 2.75, // 3, 3.5, 4, 4.5, 5, 6, 7, 8, 9, 10}; const double sTable[8] = {1.0, 1.5, 2.0, 2.5, 3, 4, 5, 10}; // const double sTable[3]= {1.0, 1.5, 2.0}; Ath__array1D* A = new Ath__array1D(8); for (uint ii = 0; ii < 8; ii++) { // for (uint ii= 0; ii<3; ii++) { double s = sTable[ii] * min_spacing; A->add(s); } return A; } Ath__array1D* extProcess::getDiagSpaceTable(uint met) { double min_spacing = getConductor(met)->_min_spacing; double min_width = getConductor(met)->_min_width; double p = min_spacing + min_width; const double sTable[7] = {0, 0.2, 0.5, 0.7, 1.0, 2.0, 3}; // const double sTable[3]= {0, 0.5, 1.0}; Ath__array1D* A = new Ath__array1D(8); for (uint ii = 0; ii < 7; ii++) { // for (uint ii= 0; ii<3; ii++) { double s = sTable[ii] * p; A->add(s); } return A; } Ath__array1D* extProcess::getDataRateTable(uint met) { if (_dataRateTable) return _dataRateTable; Ath__array1D* A = new Ath__array1D(8); A->add(0.0); return A; } void extProcess::readDataRateTable(Ath__parser* parser, const char* keyword) { if ((keyword != NULL) && (strcmp(keyword, parser->get(0)) != 0)) return; if (parser->getWordCnt() < 1) return; Ath__array1D* A = new Ath__array1D(parser->getWordCnt() + 1); A->add(0.0); parser->getDoubleArray(A, 1); _dataRateTable = A; _thickVarFlag = true; } bool extProcess::getMaxMinFlag() { return _maxMinFlag; } bool extProcess::getThickVarFlag() { return _thickVarFlag; } extMasterConductor* extProcess::getMasterConductor(uint met, uint wIndex, uint sIndex, double& w, double& s) { const double wTable[7] = {1.0, 1.5, 2.0, 2.5, 3, 3.5, 4}; const double sTable[14] = {1.0, 1.2, 1.5, 1.7, 2.0, 2.25, 2.5, 2.75, 3, 3.5, 4, 4.5, 5, 6}; extMasterConductor* m = getMasterConductor(met); w = wTable[wIndex] * getConductor(met)->_min_width; s = sTable[sIndex] * getConductor(met)->_min_spacing; return m; } extVariation* extProcess::getVariation(uint met) { extConductor* m = getConductor(met); extVariation* v = NULL; if (m->_var_table_index > 0) v = _varTable->get(m->_var_table_index); return v; } double extVariation::interpolate(double w, Ath__array1D* X, Ath__array1D* Y) { if (X->getCnt() < 2) return w; int jj = X->findNextBiggestIndex(w); if (jj >= (int) X->getCnt() - 1) jj = X->getCnt() - 2; else if (jj < 0) jj = 0; double w1 = X->get(jj); double w2 = X->get(jj + 1); double v1 = Y->get(jj); double v2 = Y->get(jj + 1); double slope = (v2 - v1) / (w2 - w1); double retVal = v2 - slope * (w2 - w); return retVal; } double extVariation::getThickness(double w, uint dIndex) { return interpolate(w, _thicknessC->_width, _thicknessC->_vTable[dIndex]); } double extVariation::getThicknessR(double w, uint dIndex) { return interpolate(w, _thicknessR->_width, _thicknessR->_vTable[dIndex]); } double extVariation::getBottomWidth(double w, uint dIndex) { return interpolate(w, _loWidthC->_width, _loWidthC->_vTable[dIndex]); } double extVariation::getBottomWidthR(double w, uint dIndex) { return interpolate(w, _loWidthR->_width, _loWidthR->_vTable[dIndex]); } double extVariation::getTopWidth(uint ii, uint jj) { return _hiWidthC->getVal(ii, jj); } double extVariation::getTopWidthR(uint ii, uint jj) { return _hiWidthR->getVal(ii, jj); } Ath__array1D* extVariation::getWidthTable() { return _hiWidthC->_width; } Ath__array1D* extVariation::getSpaceTable() { return _hiWidthC->_space; } Ath__array1D* extVariation::getDataRateTable() { return _loWidthC->_density; } Ath__array1D* extVariation::getPTable() { if (_p == NULL) return NULL; return _p->_p; } double extVariation::getP(double w) { if (_p == NULL) return 0; return interpolate(w, _p->_width, _p->_p); } void extProcess::writeProcess(const char* filename) { FILE* fp = openFile(filename, ""w""); Ath__parser parse; for (uint kk = 1; kk < _varTable->getCnt(); kk++) { _varTable->get(kk)->printVariation(fp, kk); } for (uint ii = 1; ii < _condTable->getCnt(); ii++) { extConductor* cond = _condTable->get(ii); cond->printConductor(fp, &parse); } for (uint jj = 1; jj < _dielTable->getCnt(); jj++) { extDielectric* diel = _dielTable->get(jj); diel->printDielectric(fp, &parse); } fclose(fp); } Ath__array1D* extVarTable::readDoubleArray(Ath__parser* parser, const char* keyword) { if ((keyword != NULL) && (strcmp(keyword, parser->get(0)) != 0)) return NULL; if (parser->getWordCnt() < 1) return NULL; Ath__array1D* A = new Ath__array1D(parser->getWordCnt()); uint start = 0; if (keyword != NULL) start = 1; parser->getDoubleArray(A, start); return A; } void extVarTable::printOneLine(FILE* fp, Ath__array1D* A, const char* header, const char* trail) { if (A == NULL) return; if (header != NULL) fprintf(fp, ""%s "", header); for (uint ii = 0; ii < A->getCnt(); ii++) fprintf(fp, ""%g "", A->get(ii)); fprintf(fp, ""%s"", trail); } int extVarTable::readWidthSpacing2D(Ath__parser* parser, const char* keyword1, const char* keyword2, const char* keyword3, const char* key4) { uint debug = 0; if (strcmp(""}"", parser->get(0)) == 0) return -1; _width = readDoubleArray(parser, keyword1); if (debug > 0) printOneLine(stdout, _width, keyword1, ""\\n""); if (!(parser->parseNextLine() > 0)) return -1; if (strcmp(""Spacing"", keyword2) == 0) { _space = readDoubleArray(parser, keyword2); } else if (strcmp(""Deff"", keyword2) == 0) { _density = readDoubleArray(parser, keyword2); for (uint jj = 0; jj < _density->getCnt(); jj++) _vTable[jj] = new Ath__array1D(_width->getCnt()); if (debug > 0) { printOneLine(stdout, _space, keyword2, ""\\n""); printOneLine(stdout, _density, keyword2, ""\\n""); } } else if (strcmp(""P"", keyword2) == 0) { _p = readDoubleArray(parser, keyword2); _rowCnt = 1; if (debug > 0) printOneLine(stdout, _p, keyword2, ""\\n""); } if (!(parser->parseNextLine() > 0)) return -1; if (strcmp(""}"", keyword3) == 0) { return 1; } else if (strcmp(keyword3, parser->get(0)) != 0) { return -1; } uint ii = 0; while (parser->parseNextLine() > 0) { if (strcmp(key4, parser->get(0)) == 0) { break; } if (strcmp(""}"", parser->get(0)) == 0) break; if (_space != NULL) { _vTable[ii++] = readDoubleArray(parser, NULL); if (debug > 0) printOneLine(stdout, _vTable[ii - 1], NULL, ""\\n""); } else { ii++; for (int jj = 0; jj < parser->getWordCnt(); jj++) _vTable[jj]->add(parser->getDouble(jj)); } } if (debug > 0) { if (_density != NULL) { for (uint jj = 0; jj < _density->getCnt(); jj++) printOneLine(stdout, _vTable[jj], NULL, ""\\n""); } } if (_space != NULL) _rowCnt = ii; else _rowCnt = _density->getCnt(); return ii; } void extVarTable::printTable(FILE* fp, const char* valKey) { printOneLine(fp, _width, ""Width"", ""\\n""); if (_space != NULL) printOneLine(fp, _space, ""Spacing"", ""\\n""); else if (_density != NULL) printOneLine(fp, _space, ""Deff"", ""\\n""); else { printOneLine(fp, _p, ""P"", ""\\n""); return; } fprintf(fp, ""%s\\n"", valKey); for (uint ii = 0; ii < _rowCnt; ii++) printOneLine(fp, _vTable[ii], NULL, ""\\n""); } void extVariation::printVariation(FILE* fp, uint n) { fprintf(fp, ""VAR_TABLE %d {\\n"", n); _hiWidthC->printTable(fp, ""hi_cWidth_eff""); _loWidthC->printTable(fp, ""lo_cWidth_delta""); _thicknessC->printTable(fp, ""c_thickness_eff""); _hiWidthR->printTable(fp, ""hi_rWidth_eff""); _loWidthR->printTable(fp, ""lo_rWidth_delta""); _thicknessR->printTable(fp, ""r_thickness_eff""); if (_p != NULL) _p->printTable(fp, ""P""); fprintf(fp, ""}\\n""); } extVarTable* extVariation::readVarTable(Ath__parser* parser, const char* key1, const char* key2, const char* key3, const char* endKey) { extVarTable* V = new extVarTable(20); // TODO if (V->readWidthSpacing2D(parser, key1, key2, key3, endKey) < 1) { // fprintf(stdout, ""Cannot read VarTable section: <%s>"", key3); odb::warning(0, ""Cannot read VarTable section: <%s>"", key3); delete V; return NULL; } return V; } int extVariation::readVariation(Ath__parser* parser) { _hiWidthC = readVarTable(parser, ""Width"", ""Spacing"", ""hi_cWidth_eff"", ""Width""); _loWidthC = readVarTable(parser, ""Width"", ""Deff"", ""lo_cWidth_delta"", ""Width""); _thicknessC = readVarTable(parser, ""Width"", ""Deff"", ""c_thickness_eff"", ""Width""); _hiWidthR = readVarTable(parser, ""Width"", ""Spacing"", ""hi_rWidth_eff"", ""Width""); _loWidthR = readVarTable(parser, ""Width"", ""Deff"", ""lo_rWidth_delta"", ""Width""); _thicknessR = readVarTable(parser, ""Width"", ""Deff"", ""r_thickness_eff"", ""Width""); if (strcmp(""}"", parser->get(0)) == 0) return 0; _p = readVarTable(parser, ""Width"", ""P"", ""}"", """"); return 0; } uint extProcess::readProcess(const char* name, char* filename) { uint debug = 0; // create process object // read process numbers Ath__parser parser; parser.addSeparator(""\\r""); parser.openFile(filename); while (parser.parseNextLine() > 0) { if (strcmp(""PROCESS"", parser.get(0)) == 0) { while (parser.parseNextLine() > 0) { if (strcmp(""}"", parser.get(0)) == 0) break; } } else if (strcmp(""THICKNESS_VARIATION"", parser.get(0)) == 0) { readDataRateTable(&parser, ""THICKNESS_VARIATION""); } else if (strcmp(""VAR_TABLE"", parser.get(0)) == 0) { parser.setDbg(debug); parser.getInt(1); extVariation* extVar = new extVariation(); while (parser.parseNextLine() > 0) { if (strcmp(""}"", parser.get(0)) == 0) break; extVar->readVariation(&parser); parser.setDbg(0); if (strcmp(""}"", parser.get(0)) == 0) break; } _varTable->add(extVar); } else if (strcmp(""CONDUCTOR"", parser.get(0)) == 0) { extConductor* cond = new extConductor(); strcpy(cond->_name, parser.get(1)); while (parser.parseNextLine() > 0) { if (strcmp(""}"", parser.get(0)) == 0) break; cond->readConductor(&parser); } _condTable->add(cond); } else if (strcmp(""DIELECTRIC"", parser.get(0)) == 0) { extDielectric* diel = new extDielectric(); if (parser.getWordCnt() > 2) strcpy(diel->_name, parser.get(1)); while (parser.parseNextLine() > 0) { if (strcmp(""}"", parser.get(0)) == 0) break; diel->readDielectric(&parser); } _dielTable->add(diel); } else if (strcmp(""SETMAXMINFLAG"", parser.get(0)) == 0) { _maxMinFlag = true; } } createMasterLayers(); // create dielectric ""planes"" // uint layerCnt= 8; // extRCModel *m= new extRCModel(layerCnt, (char *) name); // _modelTable->add(m); return 0; } extProcess::extProcess(uint condCnt, uint dielCnt) { _condTable = new Ath__array1D(condCnt); _condTable->add(NULL); _maxMinFlag = false; _dielTable = new Ath__array1D(dielCnt); _dielTable->add(NULL); _masterConductorTable = new Ath__array1D(condCnt); _masterConductorTable->add(NULL); _masterDielectricTable = new Ath__array1D(dielCnt); _masterDielectricTable->add(NULL); _varTable = new Ath__array1D(condCnt); _varTable->add(NULL); _dataRateTable = NULL; _thickVarFlag = false; } extVarTable::extVarTable(uint rowCnt) { _rowCnt = rowCnt; _vTable = new Ath__array1D*[rowCnt]; _density = NULL; _space = NULL; _width = NULL; _p = NULL; } extVarTable::~extVarTable() { for (uint ii = 0; ii < _rowCnt; ii++) { if (_vTable[ii] != NULL) delete _vTable[ii]; } delete[] _vTable; if (_density != NULL) delete _density; if (_space != NULL) delete _space; if (_width != NULL) delete _width; if (_p != NULL) delete _p; _p = NULL; _density = NULL; _space = NULL; _width = NULL; } } // namespace rcx ",16132,True,2705.044707443948,median "// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define RAPIDJSON_HAS_STDSTRING 1 #include ""flutter/shell/common/shell.h"" #include #include #include #include ""flutter/assets/directory_asset_bundle.h"" #include ""flutter/common/graphics/persistent_cache.h"" #include ""flutter/fml/base32.h"" #include ""flutter/fml/file.h"" #include ""flutter/fml/icu_util.h"" #include ""flutter/fml/log_settings.h"" #include ""flutter/fml/logging.h"" #include ""flutter/fml/make_copyable.h"" #include ""flutter/fml/message_loop.h"" #include ""flutter/fml/paths.h"" #include ""flutter/fml/trace_event.h"" #include ""flutter/fml/unique_fd.h"" #include ""flutter/runtime/dart_vm.h"" #include ""flutter/shell/common/engine.h"" #include ""flutter/shell/common/skia_event_tracer_impl.h"" #include ""flutter/shell/common/switches.h"" #include ""flutter/shell/common/vsync_waiter.h"" #include ""rapidjson/stringbuffer.h"" #include ""rapidjson/writer.h"" #include ""third_party/dart/runtime/include/dart_tools_api.h"" #include ""third_party/skia/include/core/SkGraphics.h"" #include ""third_party/skia/include/utils/SkBase64.h"" #include ""third_party/tonic/common/log.h"" namespace flutter { constexpr char kSkiaChannel[] = ""flutter/skia""; constexpr char kSystemChannel[] = ""flutter/system""; constexpr char kTypeKey[] = ""type""; constexpr char kFontChange[] = ""fontsChange""; namespace { std::unique_ptr CreateEngine( Engine::Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, fml::RefPtr isolate_snapshot, TaskRunners task_runners, const PlatformData& platform_data, Settings settings, std::unique_ptr animator, fml::WeakPtr io_manager, fml::RefPtr unref_queue, fml::WeakPtr snapshot_delegate, std::shared_ptr volatile_path_tracker) { return std::make_unique(delegate, // dispatcher_maker, // vm, // isolate_snapshot, // task_runners, // platform_data, // settings, // std::move(animator), // io_manager, // unref_queue, // snapshot_delegate, // volatile_path_tracker); } // Though there can be multiple shells, some settings apply to all components in // the process. These have to be set up before the shell or any of its // sub-components can be initialized. In a perfect world, this would be empty. // TODO(chinmaygarde): The unfortunate side effect of this call is that settings // that cause shell initialization failures will still lead to some of their // settings being applied. void PerformInitializationTasks(Settings& settings) { { fml::LogSettings log_settings; log_settings.min_log_level = settings.verbose_logging ? fml::LOG_INFO : fml::LOG_ERROR; fml::SetLogSettings(log_settings); } static std::once_flag gShellSettingsInitialization = {}; std::call_once(gShellSettingsInitialization, [&settings] { if (settings.engine_start_timestamp.count() == 0) { settings.engine_start_timestamp = std::chrono::microseconds(Dart_TimelineGetMicros()); } tonic::SetLogHandler( [](const char* message) { FML_LOG(ERROR) << message; }); if (settings.trace_skia) { InitSkiaEventTracer(settings.trace_skia, settings.trace_skia_allowlist); } if (!settings.trace_allowlist.empty()) { fml::tracing::TraceSetAllowlist(settings.trace_allowlist); } if (!settings.skia_deterministic_rendering_on_cpu) { SkGraphics::Init(); } else { FML_DLOG(INFO) << ""Skia deterministic rendering is enabled.""; } if (settings.icu_initialization_required) { if (settings.icu_data_path.size() != 0) { fml::icu::InitializeICU(settings.icu_data_path); } else if (settings.icu_mapper) { fml::icu::InitializeICUFromMapping(settings.icu_mapper()); } else { FML_DLOG(WARNING) << ""Skipping ICU initialization in the shell.""; } } }); PersistentCache::SetCacheSkSL(settings.cache_sksl); } } // namespace std::unique_ptr Shell::Create( const PlatformData& platform_data, TaskRunners task_runners, Settings settings, const Shell::CreateCallback& on_create_platform_view, const Shell::CreateCallback& on_create_rasterizer, bool is_gpu_disabled) { // This must come first as it initializes tracing. PerformInitializationTasks(settings); TRACE_EVENT0(""flutter"", ""Shell::Create""); // Always use the `vm_snapshot` and `isolate_snapshot` provided by the // settings to launch the VM. If the VM is already running, the snapshot // arguments are ignored. auto vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings); auto isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings); auto vm = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot); FML_CHECK(vm) << ""Must be able to initialize the VM.""; // If the settings did not specify an `isolate_snapshot`, fall back to the // one the VM was launched with. if (!isolate_snapshot) { isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot(); } return CreateWithSnapshot(std::move(platform_data), // std::move(task_runners), // /*parent_merger=*/nullptr, // std::move(settings), // std::move(vm), // std::move(isolate_snapshot), // std::move(on_create_platform_view), // std::move(on_create_rasterizer), // CreateEngine, is_gpu_disabled); } std::unique_ptr Shell::CreateShellOnPlatformThread( DartVMRef vm, fml::RefPtr parent_merger, TaskRunners task_runners, const PlatformData& platform_data, Settings settings, fml::RefPtr isolate_snapshot, const Shell::CreateCallback& on_create_platform_view, const Shell::CreateCallback& on_create_rasterizer, const Shell::EngineCreateCallback& on_create_engine, bool is_gpu_disabled) { if (!task_runners.IsValid()) { FML_LOG(ERROR) << ""Task runners to run the shell were invalid.""; return nullptr; } auto shell = std::unique_ptr( new Shell(std::move(vm), task_runners, parent_merger, settings, std::make_shared( task_runners.GetUITaskRunner(), !settings.skia_deterministic_rendering_on_cpu), is_gpu_disabled)); // Create the rasterizer on the raster thread. std::promise> rasterizer_promise; auto rasterizer_future = rasterizer_promise.get_future(); std::promise> snapshot_delegate_promise; auto snapshot_delegate_future = snapshot_delegate_promise.get_future(); fml::TaskRunner::RunNowOrPostTask( task_runners.GetRasterTaskRunner(), [&rasterizer_promise, // &snapshot_delegate_promise, on_create_rasterizer, // shell = shell.get() // ]() { TRACE_EVENT0(""flutter"", ""ShellSetupGPUSubsystem""); std::unique_ptr rasterizer(on_create_rasterizer(*shell)); snapshot_delegate_promise.set_value(rasterizer->GetSnapshotDelegate()); rasterizer_promise.set_value(std::move(rasterizer)); }); // Create the platform view on the platform thread (this thread). auto platform_view = on_create_platform_view(*shell.get()); if (!platform_view || !platform_view->GetWeakPtr()) { return nullptr; } // Ask the platform view for the vsync waiter. This will be used by the engine // to create the animator. auto vsync_waiter = platform_view->CreateVSyncWaiter(); if (!vsync_waiter) { return nullptr; } // Create the IO manager on the IO thread. The IO manager must be initialized // first because it has state that the other subsystems depend on. It must // first be booted and the necessary references obtained to initialize the // other subsystems. std::promise> io_manager_promise; auto io_manager_future = io_manager_promise.get_future(); std::promise> weak_io_manager_promise; auto weak_io_manager_future = weak_io_manager_promise.get_future(); std::promise> unref_queue_promise; auto unref_queue_future = unref_queue_promise.get_future(); auto io_task_runner = shell->GetTaskRunners().GetIOTaskRunner(); // TODO(gw280): The WeakPtr here asserts that we are derefing it on the // same thread as it was created on. We are currently on the IO thread // inside this lambda but we need to deref the PlatformView, which was // constructed on the platform thread. // // https://github.com/flutter/flutter/issues/42948 fml::TaskRunner::RunNowOrPostTask( io_task_runner, [&io_manager_promise, // &weak_io_manager_promise, // &unref_queue_promise, // platform_view = platform_view->GetWeakPtr(), // io_task_runner, // is_backgrounded_sync_switch = shell->GetIsGpuDisabledSyncSwitch() // ]() { TRACE_EVENT0(""flutter"", ""ShellSetupIOSubsystem""); auto io_manager = std::make_unique( platform_view.getUnsafe()->CreateResourceContext(), is_backgrounded_sync_switch, io_task_runner); weak_io_manager_promise.set_value(io_manager->GetWeakPtr()); unref_queue_promise.set_value(io_manager->GetSkiaUnrefQueue()); io_manager_promise.set_value(std::move(io_manager)); }); // Send dispatcher_maker to the engine constructor because shell won't have // platform_view set until Shell::Setup is called later. auto dispatcher_maker = platform_view->GetDispatcherMaker(); // Create the engine on the UI thread. std::promise> engine_promise; auto engine_future = engine_promise.get_future(); fml::TaskRunner::RunNowOrPostTask( shell->GetTaskRunners().GetUITaskRunner(), fml::MakeCopyable([&engine_promise, // shell = shell.get(), // &dispatcher_maker, // &platform_data, // isolate_snapshot = std::move(isolate_snapshot), // vsync_waiter = std::move(vsync_waiter), // &weak_io_manager_future, // &snapshot_delegate_future, // &unref_queue_future, // &on_create_engine]() mutable { TRACE_EVENT0(""flutter"", ""ShellSetupUISubsystem""); const auto& task_runners = shell->GetTaskRunners(); // The animator is owned by the UI thread but it gets its vsync pulses // from the platform. auto animator = std::make_unique(*shell, task_runners, std::move(vsync_waiter)); engine_promise.set_value( on_create_engine(*shell, // dispatcher_maker, // *shell->GetDartVM(), // std::move(isolate_snapshot), // task_runners, // platform_data, // shell->GetSettings(), // std::move(animator), // weak_io_manager_future.get(), // unref_queue_future.get(), // snapshot_delegate_future.get(), // shell->volatile_path_tracker_)); })); if (!shell->Setup(std::move(platform_view), // engine_future.get(), // rasterizer_future.get(), // io_manager_future.get()) // ) { return nullptr; } return shell; } std::unique_ptr Shell::CreateWithSnapshot( const PlatformData& platform_data, TaskRunners task_runners, fml::RefPtr parent_thread_merger, Settings settings, DartVMRef vm, fml::RefPtr isolate_snapshot, const Shell::CreateCallback& on_create_platform_view, const Shell::CreateCallback& on_create_rasterizer, const Shell::EngineCreateCallback& on_create_engine, bool is_gpu_disabled) { // This must come first as it initializes tracing. PerformInitializationTasks(settings); TRACE_EVENT0(""flutter"", ""Shell::CreateWithSnapshot""); const bool callbacks_valid = on_create_platform_view && on_create_rasterizer && on_create_engine; if (!task_runners.IsValid() || !callbacks_valid) { return nullptr; } fml::AutoResetWaitableEvent latch; std::unique_ptr shell; fml::TaskRunner::RunNowOrPostTask( task_runners.GetPlatformTaskRunner(), fml::MakeCopyable( [&latch, // &shell, // parent_thread_merger, // task_runners = std::move(task_runners), // platform_data = std::move(platform_data), // settings = std::move(settings), // vm = std::move(vm), // isolate_snapshot = std::move(isolate_snapshot), // on_create_platform_view = std::move(on_create_platform_view), // on_create_rasterizer = std::move(on_create_rasterizer), // on_create_engine = std::move(on_create_engine), is_gpu_disabled]() mutable { shell = CreateShellOnPlatformThread( std::move(vm), // parent_thread_merger, // std::move(task_runners), // std::move(platform_data), // std::move(settings), // std::move(isolate_snapshot), // std::move(on_create_platform_view), // std::move(on_create_rasterizer), // std::move(on_create_engine), is_gpu_disabled); latch.Signal(); })); latch.Wait(); return shell; } Shell::Shell(DartVMRef vm, TaskRunners task_runners, fml::RefPtr parent_merger, Settings settings, std::shared_ptr volatile_path_tracker, bool is_gpu_disabled) : task_runners_(std::move(task_runners)), parent_raster_thread_merger_(parent_merger), settings_(std::move(settings)), vm_(std::move(vm)), is_gpu_disabled_sync_switch_(new fml::SyncSwitch(is_gpu_disabled)), volatile_path_tracker_(std::move(volatile_path_tracker)), weak_factory_gpu_(nullptr), weak_factory_(this) { FML_CHECK(vm_) << ""Must have access to VM to create a shell.""; FML_DCHECK(task_runners_.IsValid()); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); display_manager_ = std::make_unique(); // Generate a WeakPtrFactory for use with the raster thread. This does not // need to wait on a latch because it can only ever be used from the raster // thread from this class, so we have ordering guarantees. fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), fml::MakeCopyable([this]() mutable { this->weak_factory_gpu_ = std::make_unique>(this); })); // Install service protocol handlers. service_protocol_handlers_[ServiceProtocol::kScreenshotExtensionName] = { task_runners_.GetRasterTaskRunner(), std::bind(&Shell::OnServiceProtocolScreenshot, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_[ServiceProtocol::kScreenshotSkpExtensionName] = { task_runners_.GetRasterTaskRunner(), std::bind(&Shell::OnServiceProtocolScreenshotSKP, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_[ServiceProtocol::kRunInViewExtensionName] = { task_runners_.GetUITaskRunner(), std::bind(&Shell::OnServiceProtocolRunInView, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_ [ServiceProtocol::kFlushUIThreadTasksExtensionName] = { task_runners_.GetUITaskRunner(), std::bind(&Shell::OnServiceProtocolFlushUIThreadTasks, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_ [ServiceProtocol::kSetAssetBundlePathExtensionName] = { task_runners_.GetUITaskRunner(), std::bind(&Shell::OnServiceProtocolSetAssetBundlePath, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_ [ServiceProtocol::kGetDisplayRefreshRateExtensionName] = { task_runners_.GetUITaskRunner(), std::bind(&Shell::OnServiceProtocolGetDisplayRefreshRate, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_[ServiceProtocol::kGetSkSLsExtensionName] = { task_runners_.GetIOTaskRunner(), std::bind(&Shell::OnServiceProtocolGetSkSLs, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_ [ServiceProtocol::kEstimateRasterCacheMemoryExtensionName] = { task_runners_.GetRasterTaskRunner(), std::bind(&Shell::OnServiceProtocolEstimateRasterCacheMemory, this, std::placeholders::_1, std::placeholders::_2)}; } Shell::~Shell() { PersistentCache::GetCacheForProcess()->RemoveWorkerTaskRunner( task_runners_.GetIOTaskRunner()); vm_->GetServiceProtocol()->RemoveHandler(this); fml::AutoResetWaitableEvent ui_latch, gpu_latch, platform_latch, io_latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), fml::MakeCopyable([this, &ui_latch]() mutable { engine_.reset(); ui_latch.Signal(); })); ui_latch.Wait(); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), fml::MakeCopyable( [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable { rasterizer.reset(); this->weak_factory_gpu_.reset(); gpu_latch.Signal(); })); gpu_latch.Wait(); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetIOTaskRunner(), fml::MakeCopyable([io_manager = std::move(io_manager_), platform_view = platform_view_.get(), &io_latch]() mutable { io_manager.reset(); if (platform_view) { platform_view->ReleaseResourceContext(); } io_latch.Signal(); })); io_latch.Wait(); // The platform view must go last because it may be holding onto platform side // counterparts to resources owned by subsystems running on other threads. For // example, the NSOpenGLContext on the Mac. fml::TaskRunner::RunNowOrPostTask( task_runners_.GetPlatformTaskRunner(), fml::MakeCopyable([platform_view = std::move(platform_view_), &platform_latch]() mutable { platform_view.reset(); platform_latch.Signal(); })); platform_latch.Wait(); } std::unique_ptr Shell::Spawn( RunConfiguration run_configuration, const std::string& initial_route, const CreateCallback& on_create_platform_view, const CreateCallback& on_create_rasterizer) const { FML_DCHECK(task_runners_.IsValid()); // It's safe to store this value since it is set on the platform thread. bool is_gpu_disabled = false; GetIsGpuDisabledSyncSwitch()->Execute( fml::SyncSwitch::Handlers() .SetIfFalse([&is_gpu_disabled] { is_gpu_disabled = false; }) .SetIfTrue([&is_gpu_disabled] { is_gpu_disabled = true; })); std::unique_ptr result = (CreateWithSnapshot( PlatformData{}, task_runners_, rasterizer_->GetRasterThreadMerger(), GetSettings(), vm_, vm_->GetVMData()->GetIsolateSnapshot(), on_create_platform_view, on_create_rasterizer, [engine = this->engine_.get(), initial_route]( Engine::Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, fml::RefPtr isolate_snapshot, TaskRunners task_runners, const PlatformData& platform_data, Settings settings, std::unique_ptr animator, fml::WeakPtr io_manager, fml::RefPtr unref_queue, fml::WeakPtr snapshot_delegate, std::shared_ptr volatile_path_tracker) { return engine->Spawn(/*delegate=*/delegate, /*dispatcher_maker=*/dispatcher_maker, /*settings=*/settings, /*animator=*/std::move(animator), /*initial_route=*/initial_route); }, is_gpu_disabled)); result->shared_resource_context_ = io_manager_->GetSharedResourceContext(); result->RunEngine(std::move(run_configuration)); return result; } void Shell::NotifyLowMemoryWarning() const { auto trace_id = fml::tracing::TraceNonce(); TRACE_EVENT_ASYNC_BEGIN0(""flutter"", ""Shell::NotifyLowMemoryWarning"", trace_id); // This does not require a current isolate but does require a running VM. // Since a valid shell will not be returned to the embedder without a valid // DartVMRef, we can be certain that this is a safe spot to assume a VM is // running. ::Dart_NotifyLowMemory(); task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() { if (rasterizer) { rasterizer->NotifyLowMemoryWarning(); } TRACE_EVENT_ASYNC_END0(""flutter"", ""Shell::NotifyLowMemoryWarning"", trace_id); }); // The IO Manager uses resource cache limits of 0, so it is not necessary // to purge them. } void Shell::RunEngine(RunConfiguration run_configuration) { RunEngine(std::move(run_configuration), nullptr); } void Shell::RunEngine( RunConfiguration run_configuration, const std::function& result_callback) { auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(), result_callback](Engine::RunStatus run_result) { if (!result_callback) { return; } platform_runner->PostTask( [result_callback, run_result]() { result_callback(run_result); }); }; FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), fml::MakeCopyable( [run_configuration = std::move(run_configuration), weak_engine = weak_engine_, result]() mutable { if (!weak_engine) { FML_LOG(ERROR) << ""Could not launch engine with configuration - no engine.""; result(Engine::RunStatus::Failure); return; } auto run_result = weak_engine->Run(std::move(run_configuration)); if (run_result == flutter::Engine::RunStatus::Failure) { FML_LOG(ERROR) << ""Could not launch engine with configuration.""; } result(run_result); })); } std::optional Shell::GetUIIsolateLastError() const { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (!weak_engine_) { return std::nullopt; } switch (weak_engine_->GetUIIsolateLastError()) { case tonic::kCompilationErrorType: return DartErrorCode::CompilationError; case tonic::kApiErrorType: return DartErrorCode::ApiError; case tonic::kUnknownErrorType: return DartErrorCode::UnknownError; case tonic::kNoError: return DartErrorCode::NoError; } return DartErrorCode::UnknownError; } bool Shell::EngineHasLivePorts() const { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (!weak_engine_) { return false; } return weak_engine_->UIIsolateHasLivePorts(); } bool Shell::IsSetup() const { return is_setup_; } bool Shell::Setup(std::unique_ptr platform_view, std::unique_ptr engine, std::unique_ptr rasterizer, std::unique_ptr io_manager) { if (is_setup_) { return false; } if (!platform_view || !engine || !rasterizer || !io_manager) { return false; } platform_view_ = std::move(platform_view); platform_message_handler_ = platform_view_->GetPlatformMessageHandler(); engine_ = std::move(engine); rasterizer_ = std::move(rasterizer); io_manager_ = std::move(io_manager); // Set the external view embedder for the rasterizer. auto view_embedder = platform_view_->CreateExternalViewEmbedder(); rasterizer_->SetExternalViewEmbedder(view_embedder); rasterizer_->SetSnapshotSurfaceProducer( platform_view_->CreateSnapshotSurfaceProducer()); // The weak ptr must be generated in the platform thread which owns the unique // ptr. weak_engine_ = engine_->GetWeakPtr(); weak_rasterizer_ = rasterizer_->GetWeakPtr(); weak_platform_view_ = platform_view_->GetWeakPtr(); // Setup the time-consuming default font manager right after engine created. if (!settings_.prefetched_default_font_manager) { fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), [engine = weak_engine_] { if (engine) { engine->SetupDefaultFontManager(); } }); } is_setup_ = true; PersistentCache::GetCacheForProcess()->AddWorkerTaskRunner( task_runners_.GetIOTaskRunner()); PersistentCache::GetCacheForProcess()->SetIsDumpingSkp( settings_.dump_skp_on_shader_compilation); if (settings_.purge_persistent_cache) { PersistentCache::GetCacheForProcess()->Purge(); } return true; } const Settings& Shell::GetSettings() const { return settings_; } const TaskRunners& Shell::GetTaskRunners() const { return task_runners_; } const fml::RefPtr Shell::GetParentRasterThreadMerger() const { return parent_raster_thread_merger_; } fml::TaskRunnerAffineWeakPtr Shell::GetRasterizer() const { FML_DCHECK(is_setup_); return weak_rasterizer_; } fml::WeakPtr Shell::GetEngine() { FML_DCHECK(is_setup_); return weak_engine_; } fml::WeakPtr Shell::GetPlatformView() { FML_DCHECK(is_setup_); return weak_platform_view_; } fml::WeakPtr Shell::GetIOManager() { FML_DCHECK(is_setup_); return io_manager_->GetWeakPtr(); } DartVM* Shell::GetDartVM() { return &vm_; } // |PlatformView::Delegate| void Shell::OnPlatformViewCreated(std::unique_ptr surface) { TRACE_EVENT0(""flutter"", ""Shell::OnPlatformViewCreated""); FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); // Prevent any request to change the thread configuration for raster and // platform queues while the platform view is being created. // // This prevents false positives such as this method starts assuming that the // raster and platform queues have a given thread configuration, but then the // configuration is changed by a task, and the assumption is no longer true. // // This incorrect assumption can lead to deadlock. // See `should_post_raster_task` for more. rasterizer_->DisableThreadMergerIfNeeded(); // The normal flow executed by this method is that the platform thread is // starting the sequence and waiting on the latch. Later the UI thread posts // raster_task to the raster thread which signals the latch. If the raster and // the platform threads are the same this results in a deadlock as the // raster_task will never be posted to the platform/raster thread that is // blocked on a latch. To avoid the described deadlock, if the raster and the // platform threads are the same, should_post_raster_task will be false, and // then instead of posting a task to the raster thread, the ui thread just // signals the latch and the platform/raster thread follows with executing // raster_task. const bool should_post_raster_task = !task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread(); fml::AutoResetWaitableEvent latch; auto raster_task = fml::MakeCopyable([&waiting_for_first_frame = waiting_for_first_frame_, rasterizer = rasterizer_->GetWeakPtr(), // surface = std::move(surface)]() mutable { if (rasterizer) { // Enables the thread merger which may be used by the external view // embedder. rasterizer->EnableThreadMergerIfNeeded(); rasterizer->Setup(std::move(surface)); } waiting_for_first_frame.store(true); }); // TODO(91717): This probably isn't necessary. The engine should be able to // handle things here via normal lifecycle messages. // https://github.com/flutter/flutter/issues/91717 auto ui_task = [engine = engine_->GetWeakPtr()] { if (engine) { engine->OnOutputSurfaceCreated(); } }; // Threading: Capture platform view by raw pointer and not the weak pointer. // We are going to use the pointer on the IO thread which is not safe with a // weak pointer. However, we are preventing the platform view from being // collected by using a latch. auto* platform_view = platform_view_.get(); FML_DCHECK(platform_view); auto io_task = [io_manager = io_manager_->GetWeakPtr(), platform_view, ui_task_runner = task_runners_.GetUITaskRunner(), ui_task, shared_resource_context = shared_resource_context_, raster_task_runner = task_runners_.GetRasterTaskRunner(), raster_task, should_post_raster_task, &latch] { if (io_manager && !io_manager->GetResourceContext()) { sk_sp resource_context; if (shared_resource_context) { resource_context = shared_resource_context; } else { resource_context = platform_view->CreateResourceContext(); } io_manager->NotifyResourceContextAvailable(resource_context); } // Step 1: Post a task on the UI thread to tell the engine that it has // an output surface. fml::TaskRunner::RunNowOrPostTask(ui_task_runner, ui_task); // Step 2: Tell the raster thread that it should create a surface for // its rasterizer. if (should_post_raster_task) { fml::TaskRunner::RunNowOrPostTask(raster_task_runner, raster_task); } latch.Signal(); }; fml::TaskRunner::RunNowOrPostTask(task_runners_.GetIOTaskRunner(), io_task); latch.Wait(); if (!should_post_raster_task) { // See comment on should_post_raster_task, in this case the raster_task // wasn't executed, and we just run it here as the platform thread // is the raster thread. raster_task(); } } // |PlatformView::Delegate| void Shell::OnPlatformViewDestroyed() { TRACE_EVENT0(""flutter"", ""Shell::OnPlatformViewDestroyed""); FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); // Prevent any request to change the thread configuration for raster and // platform queues while the platform view is being destroyed. // // This prevents false positives such as this method starts assuming that the // raster and platform queues have a given thread configuration, but then the // configuration is changed by a task, and the assumption is no longer true. // // This incorrect assumption can lead to deadlock. rasterizer_->DisableThreadMergerIfNeeded(); // Note: // This is a synchronous operation because certain platforms depend on // setup/suspension of all activities that may be interacting with the GPU in // a synchronous fashion. // The UI thread does not need to be serialized here - there is sufficient // guardrailing in the rasterizer to allow the UI thread to post work to it // even after the surface has been torn down. fml::AutoResetWaitableEvent latch; auto io_task = [io_manager = io_manager_.get(), &latch]() { // Execute any pending Skia object deletions while GPU access is still // allowed. io_manager->GetIsGpuDisabledSyncSwitch()->Execute( fml::SyncSwitch::Handlers().SetIfFalse( [&] { io_manager->GetSkiaUnrefQueue()->Drain(); })); // Step 4: All done. Signal the latch that the platform thread is waiting // on. latch.Signal(); }; auto raster_task = [rasterizer = rasterizer_->GetWeakPtr(), io_task_runner = task_runners_.GetIOTaskRunner(), io_task]() { if (rasterizer) { // Enables the thread merger which is required prior tearing down the // rasterizer. If the raster and platform threads are merged, tearing down // the rasterizer unmerges the threads. rasterizer->EnableThreadMergerIfNeeded(); rasterizer->Teardown(); } // Step 3: Tell the IO thread to complete its remaining work. fml::TaskRunner::RunNowOrPostTask(io_task_runner, io_task); }; // TODO(91717): This probably isn't necessary. The engine should be able to // handle things here via normal lifecycle messages. // https://github.com/flutter/flutter/issues/91717 auto ui_task = [engine = engine_->GetWeakPtr()]() { if (engine) { engine->OnOutputSurfaceDestroyed(); } }; // Step 1: Post a task onto the UI thread to tell the engine that its output // surface is about to go away. fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), ui_task); // Step 2: Post a task to the Raster thread (possibly this thread) to tell the // rasterizer the output surface is going away. fml::TaskRunner::RunNowOrPostTask(task_runners_.GetRasterTaskRunner(), raster_task); latch.Wait(); } // |PlatformView::Delegate| void Shell::OnPlatformViewSetViewportMetrics(const ViewportMetrics& metrics) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); if (metrics.device_pixel_ratio <= 0 || metrics.physical_width <= 0 || metrics.physical_height <= 0) { FML_DLOG(ERROR) << ""Embedding reported invalid ViewportMetrics, ignoring update."" << ""\\nphysical_width: "" << metrics.physical_width << ""\\nphysical_height: "" << metrics.physical_height << ""\\ndevice_pixel_ratio: "" << metrics.device_pixel_ratio; return; } // This is the formula Android uses. // https://android.googlesource.com/platform/frameworks/base/+/master/libs/hwui/renderthread/CacheManager.cpp#41 size_t max_bytes = metrics.physical_width * metrics.physical_height * 12 * 4; task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), max_bytes] { if (rasterizer) { rasterizer->SetResourceCacheMaxBytes(max_bytes, false); } }); task_runners_.GetUITaskRunner()->PostTask( [engine = engine_->GetWeakPtr(), metrics]() { if (engine) { engine->SetViewportMetrics(metrics); } }); { std::scoped_lock lock(resize_mutex_); expected_frame_size_ = SkISize::Make(metrics.physical_width, metrics.physical_height); } } // |PlatformView::Delegate| void Shell::OnPlatformViewDispatchPlatformMessage( std::unique_ptr message) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask(fml::MakeCopyable( [engine = engine_->GetWeakPtr(), message = std::move(message)]() mutable { if (engine) { engine->DispatchPlatformMessage(std::move(message)); } })); } // |PlatformView::Delegate| void Shell::OnPlatformViewDispatchPointerDataPacket( std::unique_ptr packet) { TRACE_EVENT0(""flutter"", ""Shell::OnPlatformViewDispatchPointerDataPacket""); TRACE_FLOW_BEGIN(""flutter"", ""PointerEvent"", next_pointer_flow_id_); FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask( fml::MakeCopyable([engine = weak_engine_, packet = std::move(packet), flow_id = next_pointer_flow_id_]() mutable { if (engine) { engine->DispatchPointerDataPacket(std::move(packet), flow_id); } })); next_pointer_flow_id_++; } // |PlatformView::Delegate| void Shell::OnPlatformViewDispatchSemanticsAction(int32_t id, SemanticsAction action, fml::MallocMapping args) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask( fml::MakeCopyable([engine = engine_->GetWeakPtr(), id, action, args = std::move(args)]() mutable { if (engine) { engine->DispatchSemanticsAction(id, action, std::move(args)); } })); } // |PlatformView::Delegate| void Shell::OnPlatformViewSetSemanticsEnabled(bool enabled) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask( [engine = engine_->GetWeakPtr(), enabled] { if (engine) { engine->SetSemanticsEnabled(enabled); } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewSetAccessibilityFeatures(int32_t flags) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask( [engine = engine_->GetWeakPtr(), flags] { if (engine) { engine->SetAccessibilityFeatures(flags); } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewRegisterTexture( std::shared_ptr texture) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), texture] { if (rasterizer) { if (auto* registry = rasterizer->GetTextureRegistry()) { registry->RegisterTexture(texture); } } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewUnregisterTexture(int64_t texture_id) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), texture_id]() { if (rasterizer) { if (auto* registry = rasterizer->GetTextureRegistry()) { registry->UnregisterTexture(texture_id); } } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); // Tell the rasterizer that one of its textures has a new frame available. task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), texture_id]() { auto* registry = rasterizer->GetTextureRegistry(); if (!registry) { return; } auto texture = registry->GetTexture(texture_id); if (!texture) { return; } texture->MarkNewFrameAvailable(); }); // Schedule a new frame without having to rebuild the layer tree. task_runners_.GetUITaskRunner()->PostTask([engine = engine_->GetWeakPtr()]() { if (engine) { engine->ScheduleFrame(false); } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewSetNextFrameCallback(const fml::closure& closure) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), closure = closure]() { if (rasterizer) { rasterizer->SetNextFrameCallback(std::move(closure)); } }); } // |Animator::Delegate| void Shell::OnAnimatorBeginFrame(fml::TimePoint frame_target_time, uint64_t frame_number) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); // record the target time for use by rasterizer. { std::scoped_lock time_recorder_lock(time_recorder_mutex_); latest_frame_target_time_.emplace(frame_target_time); } if (engine_) { engine_->BeginFrame(frame_target_time, frame_number); } } // |Animator::Delegate| void Shell::OnAnimatorNotifyIdle(int64_t deadline) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (engine_) { engine_->NotifyIdle(deadline); volatile_path_tracker_->OnFrame(); } } // |Animator::Delegate| void Shell::OnAnimatorDraw( std::shared_ptr> pipeline, std::unique_ptr frame_timings_recorder) { FML_DCHECK(is_setup_); // record the target time for use by rasterizer. { std::scoped_lock time_recorder_lock(time_recorder_mutex_); const fml::TimePoint frame_target_time = frame_timings_recorder->GetVsyncTargetTime(); if (!latest_frame_target_time_) { latest_frame_target_time_ = frame_target_time; } else if (latest_frame_target_time_ < frame_target_time) { latest_frame_target_time_ = frame_target_time; } } auto discard_callback = [this](flutter::LayerTree& tree) { std::scoped_lock lock(resize_mutex_); return !expected_frame_size_.isEmpty() && tree.frame_size() != expected_frame_size_; }; task_runners_.GetRasterTaskRunner()->PostTask(fml::MakeCopyable( [&waiting_for_first_frame = waiting_for_first_frame_, &waiting_for_first_frame_condition = waiting_for_first_frame_condition_, rasterizer = rasterizer_->GetWeakPtr(), weak_pipeline = std::weak_ptr>(pipeline), discard_callback = std::move(discard_callback), frame_timings_recorder = std::move(frame_timings_recorder)]() mutable { if (rasterizer) { std::shared_ptr> pipeline = weak_pipeline.lock(); if (pipeline) { rasterizer->Draw(std::move(frame_timings_recorder), std::move(pipeline), std::move(discard_callback)); } if (waiting_for_first_frame.load()) { waiting_for_first_frame.store(false); waiting_for_first_frame_condition.notify_all(); } } })); } // |Animator::Delegate| void Shell::OnAnimatorDrawLastLayerTree( std::unique_ptr frame_timings_recorder) { FML_DCHECK(is_setup_); auto task = fml::MakeCopyable( [rasterizer = rasterizer_->GetWeakPtr(), frame_timings_recorder = std::move(frame_timings_recorder)]() mutable { if (rasterizer) { rasterizer->DrawLastLayerTree(std::move(frame_timings_recorder)); } }); task_runners_.GetRasterTaskRunner()->PostTask(task); } // |Engine::Delegate| void Shell::OnEngineUpdateSemantics(SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetPlatformTaskRunner()->PostTask( [view = platform_view_->GetWeakPtr(), update = std::move(update), actions = std::move(actions)] { if (view) { view->UpdateSemantics(std::move(update), std::move(actions)); } }); } // |Engine::Delegate| void Shell::OnEngineHandlePlatformMessage( std::unique_ptr message) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (message->channel() == kSkiaChannel) { HandleEngineSkiaMessage(std::move(message)); return; } if (platform_message_handler_) { platform_message_handler_->HandlePlatformMessage(std::move(message)); } else { task_runners_.GetPlatformTaskRunner()->PostTask( fml::MakeCopyable([view = platform_view_->GetWeakPtr(), message = std::move(message)]() mutable { if (view) { view->HandlePlatformMessage(std::move(message)); } })); } } void Shell::HandleEngineSkiaMessage(std::unique_ptr message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast(data.GetMapping()), data.GetSize()); if (document.HasParseError() || !document.IsObject()) { return; } auto root = document.GetObject(); auto method = root.FindMember(""method""); if (method->value != ""Skia.setResourceCacheMaxBytes"") { return; } auto args = root.FindMember(""args""); if (args == root.MemberEnd() || !args->value.IsInt()) { return; } task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), max_bytes = args->value.GetInt(), response = std::move(message->response())] { if (rasterizer) { rasterizer->SetResourceCacheMaxBytes(static_cast(max_bytes), true); } if (response) { // The framework side expects this to be valid json encoded as a list. // Return `[true]` to signal success. std::vector data = {'[', 't', 'r', 'u', 'e', ']'}; response->Complete( std::make_unique(std::move(data))); } }); } // |Engine::Delegate| void Shell::OnPreEngineRestart() { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetPlatformTaskRunner(), [view = platform_view_->GetWeakPtr(), &latch]() { if (view) { view->OnPreEngineRestart(); } latch.Signal(); }); // This is blocking as any embedded platform views has to be flushed before // we re-run the Dart code. latch.Wait(); } // |Engine::Delegate| void Shell::OnRootIsolateCreated() { if (is_added_to_service_protocol_) { return; } auto description = GetServiceProtocolDescription(); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetPlatformTaskRunner(), [self = weak_factory_.GetWeakPtr(), description = std::move(description)]() { if (self) { self->vm_->GetServiceProtocol()->AddHandler(self.get(), description); } }); is_added_to_service_protocol_ = true; } // |Engine::Delegate| void Shell::UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port) { Handler::Description description(isolate_port, isolate_name); vm_->GetServiceProtocol()->SetHandlerDescription(this, description); } void Shell::SetNeedsReportTimings(bool value) { needs_report_timings_ = value; } // |Engine::Delegate| std::unique_ptr> Shell::ComputePlatformResolvedLocale( const std::vector& supported_locale_data) { return platform_view_->ComputePlatformResolvedLocales(supported_locale_data); } void Shell::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr snapshot_data, std::unique_ptr snapshot_instructions) { task_runners_.GetUITaskRunner()->PostTask(fml::MakeCopyable( [engine = engine_->GetWeakPtr(), loading_unit_id, data = std::move(snapshot_data), instructions = std::move(snapshot_instructions)]() mutable { if (engine) { engine->LoadDartDeferredLibrary(loading_unit_id, std::move(data), std::move(instructions)); } })); } void Shell::LoadDartDeferredLibraryError(intptr_t loading_unit_id, const std::string error_message, bool transient) { engine_->LoadDartDeferredLibraryError(loading_unit_id, error_message, transient); } void Shell::UpdateAssetResolverByType( std::unique_ptr updated_asset_resolver, AssetResolver::AssetResolverType type) { engine_->GetAssetManager()->UpdateResolverByType( std::move(updated_asset_resolver), type); } // |Engine::Delegate| void Shell::RequestDartDeferredLibrary(intptr_t loading_unit_id) { task_runners_.GetPlatformTaskRunner()->PostTask( [view = platform_view_->GetWeakPtr(), loading_unit_id] { if (view) { view->RequestDartDeferredLibrary(loading_unit_id); } }); } void Shell::ReportTimings() { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); auto timings = std::move(unreported_timings_); unreported_timings_ = {}; task_runners_.GetUITaskRunner()->PostTask([timings, engine = weak_engine_] { if (engine) { engine->ReportTimings(std::move(timings)); } }); } size_t Shell::UnreportedFramesCount() const { // Check that this is running on the raster thread to avoid race conditions. FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); FML_DCHECK(unreported_timings_.size() % (FrameTiming::kStatisticsCount) == 0); return unreported_timings_.size() / (FrameTiming::kStatisticsCount); } void Shell::OnFrameRasterized(const FrameTiming& timing) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); // The C++ callback defined in settings.h and set by Flutter runner. This is // independent of the timings report to the Dart side. if (settings_.frame_rasterized_callback) { settings_.frame_rasterized_callback(timing); } if (!needs_report_timings_) { return; } size_t old_count = unreported_timings_.size(); (void)old_count; for (auto phase : FrameTiming::kPhases) { unreported_timings_.push_back( timing.Get(phase).ToEpochDelta().ToMicroseconds()); } unreported_timings_.push_back(timing.GetLayerCacheCount()); unreported_timings_.push_back(timing.GetLayerCacheBytes()); unreported_timings_.push_back(timing.GetPictureCacheCount()); unreported_timings_.push_back(timing.GetPictureCacheBytes()); unreported_timings_.push_back(timing.GetFrameNumber()); FML_DCHECK(unreported_timings_.size() == old_count + FrameTiming::kStatisticsCount); // In tests using iPhone 6S with profile mode, sending a batch of 1 frame or a // batch of 100 frames have roughly the same cost of less than 0.1ms. Sending // a batch of 500 frames costs about 0.2ms. The 1 second threshold usually // kicks in before we reaching the following 100 frames threshold. The 100 // threshold here is mainly for unit tests (so we don't have to write a // 1-second unit test), and make sure that our vector won't grow too big with // future 120fps, 240fps, or 1000fps displays. // // In the profile/debug mode, the timings are used by development tools which // require a latency of no more than 100ms. Hence we lower that 1-second // threshold to 100ms because performance overhead isn't that critical in // those cases. if (!first_frame_rasterized_ || UnreportedFramesCount() >= 100) { first_frame_rasterized_ = true; ReportTimings(); } else if (!frame_timings_report_scheduled_) { #if FLUTTER_RELEASE constexpr int kBatchTimeInMilliseconds = 1000; #else constexpr int kBatchTimeInMilliseconds = 100; #endif // Also make sure that frame times get reported with a max latency of 1 // second. Otherwise, the timings of last few frames of an animation may // never be reported until the next animation starts. frame_timings_report_scheduled_ = true; task_runners_.GetRasterTaskRunner()->PostDelayedTask( [self = weak_factory_gpu_->GetWeakPtr()]() { if (!self) { return; } self->frame_timings_report_scheduled_ = false; if (self->UnreportedFramesCount() > 0) { self->ReportTimings(); } }, fml::TimeDelta::FromMilliseconds(kBatchTimeInMilliseconds)); } } fml::Milliseconds Shell::GetFrameBudget() { double display_refresh_rate = display_manager_->GetMainDisplayRefreshRate(); if (display_refresh_rate > 0) { return fml::RefreshRateToFrameBudget(display_refresh_rate); } else { return fml::kDefaultFrameBudget; } } fml::TimePoint Shell::GetLatestFrameTargetTime() const { std::scoped_lock time_recorder_lock(time_recorder_mutex_); FML_CHECK(latest_frame_target_time_.has_value()) << ""GetLatestFrameTargetTime called before OnAnimatorBeginFrame""; return latest_frame_target_time_.value(); } // |ServiceProtocol::Handler| fml::RefPtr Shell::GetServiceProtocolHandlerTaskRunner( std::string_view method) const { FML_DCHECK(is_setup_); auto found = service_protocol_handlers_.find(method); if (found != service_protocol_handlers_.end()) { return found->second.first; } return task_runners_.GetUITaskRunner(); } // |ServiceProtocol::Handler| bool Shell::HandleServiceProtocolMessage( std::string_view method, // one if the extension names specified above. const ServiceProtocolMap& params, rapidjson::Document* response) { auto found = service_protocol_handlers_.find(method); if (found != service_protocol_handlers_.end()) { return found->second.second(params, response); } return false; } // |ServiceProtocol::Handler| ServiceProtocol::Handler::Description Shell::GetServiceProtocolDescription() const { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (!weak_engine_) { return ServiceProtocol::Handler::Description(); } return { weak_engine_->GetUIIsolateMainPort(), weak_engine_->GetUIIsolateName(), }; } static void ServiceProtocolParameterError(rapidjson::Document* response, std::string error_details) { auto& allocator = response->GetAllocator(); response->SetObject(); const int64_t kInvalidParams = -32602; response->AddMember(""code"", kInvalidParams, allocator); response->AddMember(""message"", ""Invalid params"", allocator); { rapidjson::Value details(rapidjson::kObjectType); details.AddMember(""details"", error_details, allocator); response->AddMember(""data"", details, allocator); } } static void ServiceProtocolFailureError(rapidjson::Document* response, std::string message) { auto& allocator = response->GetAllocator(); response->SetObject(); const int64_t kJsonServerError = -32000; response->AddMember(""code"", kJsonServerError, allocator); response->AddMember(""message"", message, allocator); } // Service protocol handler bool Shell::OnServiceProtocolScreenshot( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); auto screenshot = rasterizer_->ScreenshotLastLayerTree( Rasterizer::ScreenshotType::CompressedImage, true); if (screenshot.data) { response->SetObject(); auto& allocator = response->GetAllocator(); response->AddMember(""type"", ""Screenshot"", allocator); rapidjson::Value image; image.SetString(static_cast(screenshot.data->data()), screenshot.data->size(), allocator); response->AddMember(""screenshot"", image, allocator); return true; } ServiceProtocolFailureError(response, ""Could not capture image screenshot.""); return false; } // Service protocol handler bool Shell::OnServiceProtocolScreenshotSKP( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); auto screenshot = rasterizer_->ScreenshotLastLayerTree( Rasterizer::ScreenshotType::SkiaPicture, true); if (screenshot.data) { response->SetObject(); auto& allocator = response->GetAllocator(); response->AddMember(""type"", ""ScreenshotSkp"", allocator); rapidjson::Value skp; skp.SetString(static_cast(screenshot.data->data()), screenshot.data->size(), allocator); response->AddMember(""skp"", skp, allocator); return true; } ServiceProtocolFailureError(response, ""Could not capture SKP screenshot.""); return false; } // Service protocol handler bool Shell::OnServiceProtocolRunInView( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (params.count(""mainScript"") == 0) { ServiceProtocolParameterError(response, ""'mainScript' parameter is missing.""); return false; } if (params.count(""assetDirectory"") == 0) { ServiceProtocolParameterError(response, ""'assetDirectory' parameter is missing.""); return false; } std::string main_script_path = fml::paths::FromURI(params.at(""mainScript"").data()); std::string asset_directory_path = fml::paths::FromURI(params.at(""assetDirectory"").data()); auto main_script_file_mapping = std::make_unique(fml::OpenFile( main_script_path.c_str(), false, fml::FilePermission::kRead)); auto isolate_configuration = IsolateConfiguration::CreateForKernel( std::move(main_script_file_mapping)); RunConfiguration configuration(std::move(isolate_configuration)); configuration.SetEntrypointAndLibrary(engine_->GetLastEntrypoint(), engine_->GetLastEntrypointLibrary()); configuration.SetEntrypointArgs(engine_->GetLastEntrypointArgs()); configuration.AddAssetResolver(std::make_unique( fml::OpenDirectory(asset_directory_path.c_str(), false, fml::FilePermission::kRead), false)); // Preserve any original asset resolvers to avoid syncing unchanged assets // over the DevFS connection. auto old_asset_manager = engine_->GetAssetManager(); if (old_asset_manager != nullptr) { for (auto& old_resolver : old_asset_manager->TakeResolvers()) { if (old_resolver->IsValidAfterAssetManagerChange()) { configuration.AddAssetResolver(std::move(old_resolver)); } } } auto& allocator = response->GetAllocator(); response->SetObject(); if (engine_->Restart(std::move(configuration))) { response->AddMember(""type"", ""Success"", allocator); auto new_description = GetServiceProtocolDescription(); rapidjson::Value view(rapidjson::kObjectType); new_description.Write(this, view, allocator); response->AddMember(""view"", view, allocator); return true; } else { FML_DLOG(ERROR) << ""Could not run configuration in engine.""; ServiceProtocolFailureError(response, ""Could not run configuration in engine.""); return false; } FML_DCHECK(false); return false; } // Service protocol handler bool Shell::OnServiceProtocolFlushUIThreadTasks( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); // This API should not be invoked by production code. // It can potentially starve the service isolate if the main isolate pauses // at a breakpoint or is in an infinite loop. // // It should be invoked from the VM Service and and blocks it until UI thread // tasks are processed. response->SetObject(); response->AddMember(""type"", ""Success"", response->GetAllocator()); return true; } bool Shell::OnServiceProtocolGetDisplayRefreshRate( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); response->SetObject(); response->AddMember(""type"", ""DisplayRefreshRate"", response->GetAllocator()); response->AddMember(""fps"", display_manager_->GetMainDisplayRefreshRate(), response->GetAllocator()); return true; } double Shell::GetMainDisplayRefreshRate() { return display_manager_->GetMainDisplayRefreshRate(); } void Shell::RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority) { FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); FML_DCHECK(is_setup_); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), [engine = engine_->GetWeakPtr(), factory = std::move(factory), priority]() { if (engine) { engine->GetImageGeneratorRegistry()->AddFactory(factory, priority); } }); } bool Shell::OnServiceProtocolGetSkSLs( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetIOTaskRunner()->RunsTasksOnCurrentThread()); response->SetObject(); response->AddMember(""type"", ""GetSkSLs"", response->GetAllocator()); rapidjson::Value shaders_json(rapidjson::kObjectType); PersistentCache* persistent_cache = PersistentCache::GetCacheForProcess(); std::vector sksls = persistent_cache->LoadSkSLs(); for (const auto& sksl : sksls) { size_t b64_size = SkBase64::Encode(sksl.value->data(), sksl.value->size(), nullptr); sk_sp b64_data = SkData::MakeUninitialized(b64_size + 1); char* b64_char = static_cast(b64_data->writable_data()); SkBase64::Encode(sksl.value->data(), sksl.value->size(), b64_char); b64_char[b64_size] = 0; // make it null terminated for printing rapidjson::Value shader_value(b64_char, response->GetAllocator()); std::string_view key_view(reinterpret_cast(sksl.key->data()), sksl.key->size()); auto encode_result = fml::Base32Encode(key_view); if (!encode_result.first) { continue; } rapidjson::Value shader_key(encode_result.second, response->GetAllocator()); shaders_json.AddMember(shader_key, shader_value, response->GetAllocator()); } response->AddMember(""SkSLs"", shaders_json, response->GetAllocator()); return true; } bool Shell::OnServiceProtocolEstimateRasterCacheMemory( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); const auto& raster_cache = rasterizer_->compositor_context()->raster_cache(); response->SetObject(); response->AddMember(""type"", ""EstimateRasterCacheMemory"", response->GetAllocator()); response->AddMember(""layerBytes"", raster_cache.EstimateLayerCacheByteSize(), response->GetAllocator()); response->AddMember(""pictureBytes"", raster_cache.EstimatePictureCacheByteSize(), response->GetAllocator()); return true; } // Service protocol handler bool Shell::OnServiceProtocolSetAssetBundlePath( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (params.count(""assetDirectory"") == 0) { ServiceProtocolParameterError(response, ""'assetDirectory' parameter is missing.""); return false; } auto& allocator = response->GetAllocator(); response->SetObject(); auto asset_manager = std::make_shared(); asset_manager->PushFront(std::make_unique( fml::OpenDirectory(params.at(""assetDirectory"").data(), false, fml::FilePermission::kRead), false)); // Preserve any original asset resolvers to avoid syncing unchanged assets // over the DevFS connection. auto old_asset_manager = engine_->GetAssetManager(); if (old_asset_manager != nullptr) { for (auto& old_resolver : old_asset_manager->TakeResolvers()) { if (old_resolver->IsValidAfterAssetManagerChange()) { asset_manager->PushBack(std::move(old_resolver)); } } } if (engine_->UpdateAssetManager(std::move(asset_manager))) { response->AddMember(""type"", ""Success"", allocator); auto new_description = GetServiceProtocolDescription(); rapidjson::Value view(rapidjson::kObjectType); new_description.Write(this, view, allocator); response->AddMember(""view"", view, allocator); return true; } else { FML_DLOG(ERROR) << ""Could not update asset directory.""; ServiceProtocolFailureError(response, ""Could not update asset directory.""); return false; } FML_DCHECK(false); return false; } Rasterizer::Screenshot Shell::Screenshot( Rasterizer::ScreenshotType screenshot_type, bool base64_encode) { TRACE_EVENT0(""flutter"", ""Shell::Screenshot""); fml::AutoResetWaitableEvent latch; Rasterizer::Screenshot screenshot; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, // rasterizer = GetRasterizer(), // &screenshot, // screenshot_type, // base64_encode // ]() { if (rasterizer) { screenshot = rasterizer->ScreenshotLastLayerTree(screenshot_type, base64_encode); } latch.Signal(); }); latch.Wait(); return screenshot; } fml::Status Shell::WaitForFirstFrame(fml::TimeDelta timeout) { FML_DCHECK(is_setup_); if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() || task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) { return fml::Status(fml::StatusCode::kFailedPrecondition, ""WaitForFirstFrame called from thread that can't wait "" ""because it is responsible for generating the frame.""); } // Check for overflow. auto now = std::chrono::steady_clock::now(); auto max_duration = std::chrono::steady_clock::time_point::max() - now; auto desired_duration = std::chrono::milliseconds(timeout.ToMilliseconds()); auto duration = now + (desired_duration > max_duration ? max_duration : desired_duration); std::unique_lock lock(waiting_for_first_frame_mutex_); bool success = waiting_for_first_frame_condition_.wait_until( lock, duration, [&waiting_for_first_frame = waiting_for_first_frame_] { return !waiting_for_first_frame.load(); }); if (success) { return fml::Status(); } else { return fml::Status(fml::StatusCode::kDeadlineExceeded, ""timeout""); } } bool Shell::ReloadSystemFonts() { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); if (!engine_) { return false; } engine_->SetupDefaultFontManager(); engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache(); // After system fonts are reloaded, we send a system channel message // to notify flutter framework. rapidjson::Document document; document.SetObject(); auto& allocator = document.GetAllocator(); rapidjson::Value message_value; message_value.SetString(kFontChange, allocator); document.AddMember(kTypeKey, message_value, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); document.Accept(writer); std::string message = buffer.GetString(); std::unique_ptr fontsChangeMessage = std::make_unique( kSystemChannel, fml::MallocMapping::Copy(message.c_str(), message.length()), nullptr); OnPlatformViewDispatchPlatformMessage(std::move(fontsChangeMessage)); return true; } std::shared_ptr Shell::GetIsGpuDisabledSyncSwitch() const { return is_gpu_disabled_sync_switch_; } void Shell::SetGpuAvailability(GpuAvailability availability) { FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); switch (availability) { case GpuAvailability::kAvailable: is_gpu_disabled_sync_switch_->SetSwitch(false); return; case GpuAvailability::kFlushAndMakeUnavailable: { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetIOTaskRunner(), [io_manager = io_manager_.get(), &latch]() { io_manager->GetSkiaUnrefQueue()->Drain(); latch.Signal(); }); latch.Wait(); } // FALLTHROUGH case GpuAvailability::kUnavailable: is_gpu_disabled_sync_switch_->SetSwitch(true); return; default: FML_DCHECK(false); } } void Shell::OnDisplayUpdates(DisplayUpdateType update_type, std::vector> displays) { display_manager_->HandleDisplayUpdates(update_type, std::move(displays)); } fml::TimePoint Shell::GetCurrentTimePoint() { return fml::TimePoint::Now(); } const std::shared_ptr& Shell::GetPlatformMessageHandler() const { return platform_message_handler_; } } // namespace flutter ",16319,True,2934.1400241408323,median "/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include #include ""driver/dxgi/dxgi_common.h"" #include ""driver/ihv/amd/official/DXExt/AmdExtD3DCommandListMarkerApi.h"" #include ""d3d12_command_list.h"" #include ""d3d12_command_queue.h"" WRAPPED_POOL_INST(WrappedID3D12CommandQueue); WRAPPED_POOL_INST(WrappedID3D12GraphicsCommandList); template <> ID3D12GraphicsCommandList *Unwrap(ID3D12GraphicsCommandList *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal(); } ID3D12GraphicsCommandList *Unwrap(ID3D12GraphicsCommandList1 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal(); } ID3D12GraphicsCommandList *Unwrap(ID3D12GraphicsCommandList2 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal(); } ID3D12GraphicsCommandList *Unwrap(ID3D12GraphicsCommandList3 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal(); } ID3D12GraphicsCommandList *Unwrap(ID3D12GraphicsCommandList4 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal(); } ID3D12GraphicsCommandList *Unwrap(ID3D12GraphicsCommandList5 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal(); } ID3D12GraphicsCommandList1 *Unwrap1(ID3D12GraphicsCommandList1 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal1(); } ID3D12GraphicsCommandList2 *Unwrap2(ID3D12GraphicsCommandList2 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal2(); } ID3D12GraphicsCommandList3 *Unwrap3(ID3D12GraphicsCommandList3 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal3(); } ID3D12GraphicsCommandList4 *Unwrap4(ID3D12GraphicsCommandList4 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal4(); } ID3D12GraphicsCommandList5 *Unwrap5(ID3D12GraphicsCommandList5 *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal5(); } template <> ID3D12CommandList *Unwrap(ID3D12CommandList *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetReal(); } template <> ResourceId GetResID(ID3D12GraphicsCommandList *obj) { if(obj == NULL) return ResourceId(); return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceID(); } template <> ResourceId GetResID(ID3D12GraphicsCommandList1 *obj) { if(obj == NULL) return ResourceId(); return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceID(); } template <> ResourceId GetResID(ID3D12GraphicsCommandList2 *obj) { if(obj == NULL) return ResourceId(); return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceID(); } template <> ResourceId GetResID(ID3D12GraphicsCommandList3 *obj) { if(obj == NULL) return ResourceId(); return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceID(); } template <> ResourceId GetResID(ID3D12GraphicsCommandList4 *obj) { if(obj == NULL) return ResourceId(); return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceID(); } template <> ResourceId GetResID(ID3D12GraphicsCommandList5 *obj) { if(obj == NULL) return ResourceId(); return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceID(); } template <> ResourceId GetResID(ID3D12CommandList *obj) { if(obj == NULL) return ResourceId(); return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceID(); } template <> D3D12ResourceRecord *GetRecord(ID3D12GraphicsCommandList *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceRecord(); } template <> D3D12ResourceRecord *GetRecord(ID3D12CommandList *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12GraphicsCommandList *)obj)->GetResourceRecord(); } template <> ID3D12CommandQueue *Unwrap(ID3D12CommandQueue *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12CommandQueue *)obj)->GetReal(); } template <> ResourceId GetResID(ID3D12CommandQueue *obj) { if(obj == NULL) return ResourceId(); return ((WrappedID3D12CommandQueue *)obj)->GetResourceID(); } template <> D3D12ResourceRecord *GetRecord(ID3D12CommandQueue *obj) { if(obj == NULL) return NULL; return ((WrappedID3D12CommandQueue *)obj)->GetResourceRecord(); } WrappedID3D12GraphicsCommandList *GetWrapped(ID3D12GraphicsCommandList1 *obj) { return ((WrappedID3D12GraphicsCommandList *)obj); } WrappedID3D12GraphicsCommandList *GetWrapped(ID3D12GraphicsCommandList2 *obj) { return ((WrappedID3D12GraphicsCommandList *)obj); } WrappedID3D12GraphicsCommandList *GetWrapped(ID3D12GraphicsCommandList3 *obj) { return ((WrappedID3D12GraphicsCommandList *)obj); } WrappedID3D12GraphicsCommandList *GetWrapped(ID3D12GraphicsCommandList4 *obj) { return ((WrappedID3D12GraphicsCommandList *)obj); } WrappedID3D12GraphicsCommandList *GetWrapped(ID3D12GraphicsCommandList5 *obj) { return ((WrappedID3D12GraphicsCommandList *)obj); } ULONG STDMETHODCALLTYPE WrappedID3D12DebugCommandQueue::AddRef() { if(m_pQueue) m_pQueue->AddRef(); return 1; } ULONG STDMETHODCALLTYPE WrappedID3D12DebugCommandQueue::Release() { if(m_pQueue) m_pQueue->Release(); return 1; } ULONG STDMETHODCALLTYPE WrappedID3D12DebugCommandList::AddRef() { if(m_pList) m_pList->AddRef(); return 1; } ULONG STDMETHODCALLTYPE WrappedID3D12DebugCommandList::Release() { if(m_pList) m_pList->Release(); return 1; } HRESULT STDMETHODCALLTYPE WrappedDownlevelQueue::QueryInterface(REFIID riid, void **ppvObject) { return m_pQueue.QueryInterface(riid, ppvObject); } ULONG STDMETHODCALLTYPE WrappedDownlevelQueue::AddRef() { return m_pQueue.AddRef(); } ULONG STDMETHODCALLTYPE WrappedDownlevelQueue::Release() { return m_pQueue.Release(); } HRESULT STDMETHODCALLTYPE WrappedDownlevelQueue::Present(ID3D12GraphicsCommandList *pOpenCommandList, ID3D12Resource *pSourceTex2D, HWND hWindow, D3D12_DOWNLEVEL_PRESENT_FLAGS Flags) { return m_pQueue.Present(pOpenCommandList, pSourceTex2D, hWindow, Flags); } WrappedID3D12CommandQueue::WrappedID3D12CommandQueue(ID3D12CommandQueue *real, WrappedID3D12Device *device, CaptureState &state) : RefCounter12(real), m_pDevice(device), m_State(state), m_WrappedDownlevel(*this) { if(RenderDoc::Inst().GetCrashHandler()) RenderDoc::Inst().GetCrashHandler()->RegisterMemoryRegion(this, sizeof(WrappedID3D12CommandQueue)); m_WrappedDebug.m_pQueue = this; m_pDownlevel = NULL; if(m_pReal) { m_pReal->QueryInterface(__uuidof(ID3D12DebugCommandQueue), (void **)&m_WrappedDebug.m_pReal); m_pReal->QueryInterface(__uuidof(ID3D12CommandQueueDownlevel), (void **)&m_pDownlevel); } if(RenderDoc::Inst().IsReplayApp()) { m_ReplayList = new WrappedID3D12GraphicsCommandList(NULL, m_pDevice, state); m_ReplayList->SetCommandData(&m_Cmd); } // create a temporary and grab its resource ID m_ResourceID = ResourceIDGen::GetNewUniqueID(); m_QueueRecord = NULL; m_CreationRecord = NULL; m_Cmd.m_pDevice = m_pDevice; if(!RenderDoc::Inst().IsReplayApp()) { m_QueueRecord = m_pDevice->GetResourceManager()->AddResourceRecord(m_ResourceID); m_QueueRecord->type = Resource_CommandQueue; m_QueueRecord->DataInSerialiser = false; m_QueueRecord->InternalResource = true; m_QueueRecord->Length = 0; // a bit of a hack, we make a parallel resource record with the same lifetime as the command // queue. It will hold onto our create chunk and not get thrown away as we clear and re-fill // submissions into the queue record itself. We'll pull it into the capture by marking the // queues as referenced. m_CreationRecord = m_pDevice->GetResourceManager()->AddResourceRecord(ResourceIDGen::GetNewUniqueID()); m_CreationRecord->type = Resource_CommandQueue; m_CreationRecord->InternalResource = true; } m_pDevice->GetResourceManager()->AddCurrentResource(GetResourceID(), this); m_pDevice->SoftRef(); } WrappedID3D12CommandQueue::~WrappedID3D12CommandQueue() { SAFE_DELETE(m_FrameReader); if(m_CreationRecord) m_CreationRecord->Delete(m_pDevice->GetResourceManager()); if(m_QueueRecord) m_QueueRecord->Delete(m_pDevice->GetResourceManager()); m_pDevice->GetResourceManager()->ReleaseCurrentResource(GetResourceID()); m_pDevice->RemoveQueue(this); SAFE_RELEASE(m_pDownlevel); for(size_t i = 0; i < m_Cmd.m_IndirectBuffers.size(); i++) SAFE_RELEASE(m_Cmd.m_IndirectBuffers[i]); SAFE_RELEASE(m_WrappedDebug.m_pReal); SAFE_RELEASE(m_pReal); } HRESULT STDMETHODCALLTYPE WrappedID3D12CommandQueue::QueryInterface(REFIID riid, void **ppvObject) { if(riid == __uuidof(IUnknown)) { *ppvObject = (IUnknown *)(ID3D12CommandQueue *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12CommandQueue)) { *ppvObject = (ID3D12CommandQueue *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12DebugCommandQueue)) { if(m_WrappedDebug.m_pReal) { AddRef(); *ppvObject = (ID3D12DebugCommandQueue *)&m_WrappedDebug; return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12Pageable)) { *ppvObject = (ID3D12Pageable *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12DeviceChild)) { *ppvObject = (ID3D12DeviceChild *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12Object)) { *ppvObject = (ID3D12DeviceChild *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12CommandQueueDownlevel)) { if(m_pDownlevel) { *ppvObject = &m_WrappedDownlevel; AddRef(); return S_OK; } else { return E_NOINTERFACE; } } else { WarnUnknownGUID(""ID3D12CommandQueue"", riid); } return RefCounter12::QueryInterface(riid, ppvObject); } void WrappedID3D12CommandQueue::ClearAfterCapture() { // delete cmd buffers now - had to keep them alive until after serialiser flush. for(size_t i = 0; i < m_CmdListRecords.size(); i++) m_CmdListRecords[i]->Delete(GetResourceManager()); m_CmdListRecords.clear(); m_QueueRecord->DeleteChunks(); } WriteSerialiser &WrappedID3D12CommandQueue::GetThreadSerialiser() { return m_pDevice->GetThreadSerialiser(); } rdcstr WrappedID3D12CommandQueue::GetChunkName(uint32_t idx) { if((SystemChunk)idx < SystemChunk::FirstDriverChunk) return ToStr((SystemChunk)idx); return ToStr((D3D12Chunk)idx); } const APIEvent &WrappedID3D12CommandQueue::GetEvent(uint32_t eventId) { // start at where the requested eventId would be size_t idx = eventId; // find the next valid event (some may be skipped) while(idx < m_Cmd.m_Events.size() - 1 && m_Cmd.m_Events[idx].eventId == 0) idx++; return m_Cmd.m_Events[RDCMIN(idx, m_Cmd.m_Events.size() - 1)]; } bool WrappedID3D12CommandQueue::ProcessChunk(ReadSerialiser &ser, D3D12Chunk chunk) { m_Cmd.m_AddedDrawcall = false; bool ret = false; switch(chunk) { case D3D12Chunk::Device_CreateConstantBufferView: case D3D12Chunk::Device_CreateShaderResourceView: case D3D12Chunk::Device_CreateUnorderedAccessView: case D3D12Chunk::Device_CreateRenderTargetView: case D3D12Chunk::Device_CreateDepthStencilView: case D3D12Chunk::Device_CreateSampler: ret = m_pDevice->Serialise_DynamicDescriptorWrite(ser, NULL); break; case D3D12Chunk::Device_CopyDescriptors: case D3D12Chunk::Device_CopyDescriptorsSimple: ret = m_pDevice->Serialise_DynamicDescriptorCopies(ser, rdcarray()); break; case D3D12Chunk::Queue_ExecuteCommandLists: ret = Serialise_ExecuteCommandLists(ser, 0, NULL); break; case D3D12Chunk::Queue_Signal: ret = Serialise_Signal(ser, NULL, 0); break; case D3D12Chunk::Queue_Wait: ret = Serialise_Wait(ser, NULL, 0); break; case D3D12Chunk::Queue_UpdateTileMappings: ret = Serialise_UpdateTileMappings(ser, NULL, 0, NULL, NULL, NULL, 0, NULL, NULL, NULL, D3D12_TILE_MAPPING_FLAGS(0)); break; case D3D12Chunk::Queue_CopyTileMappings: ret = Serialise_CopyTileMappings(ser, NULL, NULL, NULL, NULL, NULL, D3D12_TILE_MAPPING_FLAGS(0)); break; case D3D12Chunk::Queue_BeginEvent: ret = Serialise_BeginEvent(ser, 0, NULL, 0); break; case D3D12Chunk::Queue_SetMarker: ret = Serialise_SetMarker(ser, 0, NULL, 0); break; case D3D12Chunk::Queue_EndEvent: ret = Serialise_EndEvent(ser); break; case D3D12Chunk::List_Close: ret = m_ReplayList->Serialise_Close(ser); break; case D3D12Chunk::List_Reset: ret = m_ReplayList->Serialise_Reset(ser, NULL, NULL); break; case D3D12Chunk::List_ResourceBarrier: ret = m_ReplayList->Serialise_ResourceBarrier(ser, 0, NULL); break; case D3D12Chunk::List_BeginQuery: ret = m_ReplayList->Serialise_BeginQuery(ser, NULL, D3D12_QUERY_TYPE(0), 0); break; case D3D12Chunk::List_EndQuery: ret = m_ReplayList->Serialise_EndQuery(ser, NULL, D3D12_QUERY_TYPE(0), 0); break; case D3D12Chunk::List_ResolveQueryData: ret = m_ReplayList->Serialise_ResolveQueryData(ser, NULL, D3D12_QUERY_TYPE(0), 0, 0, NULL, 0); break; case D3D12Chunk::List_SetPredication: ret = m_ReplayList->Serialise_SetPredication(ser, NULL, 0, D3D12_PREDICATION_OP(0)); break; case D3D12Chunk::List_DrawIndexedInstanced: ret = m_ReplayList->Serialise_DrawIndexedInstanced(ser, 0, 0, 0, 0, 0); break; case D3D12Chunk::List_DrawInstanced: ret = m_ReplayList->Serialise_DrawInstanced(ser, 0, 0, 0, 0); break; case D3D12Chunk::List_Dispatch: ret = m_ReplayList->Serialise_Dispatch(ser, 0, 0, 0); break; case D3D12Chunk::List_ExecuteIndirect: ret = m_ReplayList->Serialise_ExecuteIndirect(ser, NULL, 0, NULL, 0, NULL, 0); break; case D3D12Chunk::List_ExecuteBundle: ret = m_ReplayList->Serialise_ExecuteBundle(ser, NULL); break; case D3D12Chunk::List_CopyBufferRegion: ret = m_ReplayList->Serialise_CopyBufferRegion(ser, NULL, 0, NULL, 0, 0); break; case D3D12Chunk::List_CopyTextureRegion: ret = m_ReplayList->Serialise_CopyTextureRegion(ser, NULL, 0, 0, 0, NULL, NULL); break; case D3D12Chunk::List_CopyResource: ret = m_ReplayList->Serialise_CopyResource(ser, NULL, NULL); break; case D3D12Chunk::List_ResolveSubresource: ret = m_ReplayList->Serialise_ResolveSubresource(ser, NULL, 0, NULL, 0, DXGI_FORMAT_UNKNOWN); break; case D3D12Chunk::List_ClearRenderTargetView: ret = m_ReplayList->Serialise_ClearRenderTargetView(ser, D3D12_CPU_DESCRIPTOR_HANDLE(), (FLOAT *)NULL, 0, NULL); break; case D3D12Chunk::List_ClearDepthStencilView: ret = m_ReplayList->Serialise_ClearDepthStencilView(ser, D3D12_CPU_DESCRIPTOR_HANDLE(), D3D12_CLEAR_FLAGS(0), 0.0f, 0, 0, NULL); break; case D3D12Chunk::List_ClearUnorderedAccessViewUint: ret = m_ReplayList->Serialise_ClearUnorderedAccessViewUint( ser, D3D12_GPU_DESCRIPTOR_HANDLE(), D3D12_CPU_DESCRIPTOR_HANDLE(), NULL, NULL, 0, NULL); break; case D3D12Chunk::List_ClearUnorderedAccessViewFloat: ret = m_ReplayList->Serialise_ClearUnorderedAccessViewFloat( ser, D3D12_GPU_DESCRIPTOR_HANDLE(), D3D12_CPU_DESCRIPTOR_HANDLE(), NULL, NULL, 0, NULL); break; case D3D12Chunk::List_DiscardResource: ret = m_ReplayList->Serialise_DiscardResource(ser, NULL, NULL); break; case D3D12Chunk::List_IASetPrimitiveTopology: ret = m_ReplayList->Serialise_IASetPrimitiveTopology(ser, D3D_PRIMITIVE_TOPOLOGY_UNDEFINED); break; case D3D12Chunk::List_IASetIndexBuffer: ret = m_ReplayList->Serialise_IASetIndexBuffer(ser, NULL); break; case D3D12Chunk::List_IASetVertexBuffers: ret = m_ReplayList->Serialise_IASetVertexBuffers(ser, 0, 0, NULL); break; case D3D12Chunk::List_SOSetTargets: ret = m_ReplayList->Serialise_SOSetTargets(ser, 0, 0, NULL); break; case D3D12Chunk::List_RSSetViewports: ret = m_ReplayList->Serialise_RSSetViewports(ser, 0, NULL); break; case D3D12Chunk::List_RSSetScissorRects: ret = m_ReplayList->Serialise_RSSetScissorRects(ser, 0, NULL); break; case D3D12Chunk::List_SetPipelineState: ret = m_ReplayList->Serialise_SetPipelineState(ser, NULL); break; case D3D12Chunk::List_SetDescriptorHeaps: ret = m_ReplayList->Serialise_SetDescriptorHeaps(ser, 0, NULL); break; case D3D12Chunk::List_OMSetRenderTargets: ret = m_ReplayList->Serialise_OMSetRenderTargets(ser, 0, NULL, FALSE, NULL); break; case D3D12Chunk::List_OMSetStencilRef: ret = m_ReplayList->Serialise_OMSetStencilRef(ser, 0); break; case D3D12Chunk::List_OMSetBlendFactor: ret = m_ReplayList->Serialise_OMSetBlendFactor(ser, NULL); break; case D3D12Chunk::List_SetGraphicsRootDescriptorTable: ret = m_ReplayList->Serialise_SetGraphicsRootDescriptorTable(ser, 0, D3D12_GPU_DESCRIPTOR_HANDLE()); break; case D3D12Chunk::List_SetGraphicsRootSignature: ret = m_ReplayList->Serialise_SetGraphicsRootSignature(ser, NULL); break; case D3D12Chunk::List_SetGraphicsRoot32BitConstant: ret = m_ReplayList->Serialise_SetGraphicsRoot32BitConstant(ser, 0, 0, 0); break; case D3D12Chunk::List_SetGraphicsRoot32BitConstants: ret = m_ReplayList->Serialise_SetGraphicsRoot32BitConstants(ser, 0, 0, NULL, 0); break; case D3D12Chunk::List_SetGraphicsRootConstantBufferView: ret = m_ReplayList->Serialise_SetGraphicsRootConstantBufferView(ser, 0, D3D12_GPU_VIRTUAL_ADDRESS()); break; case D3D12Chunk::List_SetGraphicsRootShaderResourceView: ret = m_ReplayList->Serialise_SetGraphicsRootShaderResourceView(ser, 0, D3D12_GPU_VIRTUAL_ADDRESS()); break; case D3D12Chunk::List_SetGraphicsRootUnorderedAccessView: ret = m_ReplayList->Serialise_SetGraphicsRootUnorderedAccessView(ser, 0, D3D12_GPU_VIRTUAL_ADDRESS()); break; case D3D12Chunk::List_SetComputeRootDescriptorTable: ret = m_ReplayList->Serialise_SetComputeRootDescriptorTable(ser, 0, D3D12_GPU_DESCRIPTOR_HANDLE()); break; case D3D12Chunk::List_SetComputeRootSignature: ret = m_ReplayList->Serialise_SetComputeRootSignature(ser, NULL); break; case D3D12Chunk::List_SetComputeRoot32BitConstant: ret = m_ReplayList->Serialise_SetComputeRoot32BitConstant(ser, 0, 0, 0); break; case D3D12Chunk::List_SetComputeRoot32BitConstants: ret = m_ReplayList->Serialise_SetComputeRoot32BitConstants(ser, 0, 0, NULL, 0); break; case D3D12Chunk::List_SetComputeRootConstantBufferView: ret = m_ReplayList->Serialise_SetComputeRootConstantBufferView(ser, 0, D3D12_GPU_VIRTUAL_ADDRESS()); break; case D3D12Chunk::List_SetComputeRootShaderResourceView: ret = m_ReplayList->Serialise_SetComputeRootShaderResourceView(ser, 0, D3D12_GPU_VIRTUAL_ADDRESS()); break; case D3D12Chunk::List_SetComputeRootUnorderedAccessView: ret = m_ReplayList->Serialise_SetComputeRootUnorderedAccessView(ser, 0, D3D12_GPU_VIRTUAL_ADDRESS()); break; case D3D12Chunk::List_CopyTiles: ret = m_ReplayList->Serialise_CopyTiles(ser, NULL, NULL, NULL, NULL, 0, D3D12_TILE_COPY_FLAGS(0)); break; case D3D12Chunk::List_AtomicCopyBufferUINT: ret = m_ReplayList->Serialise_AtomicCopyBufferUINT(ser, NULL, 0, NULL, 0, 0, NULL, NULL); break; case D3D12Chunk::List_AtomicCopyBufferUINT64: ret = m_ReplayList->Serialise_AtomicCopyBufferUINT64(ser, NULL, 0, NULL, 0, 0, NULL, NULL); break; case D3D12Chunk::List_OMSetDepthBounds: ret = m_ReplayList->Serialise_OMSetDepthBounds(ser, 0.0f, 0.0f); break; case D3D12Chunk::List_ResolveSubresourceRegion: ret = m_ReplayList->Serialise_ResolveSubresourceRegion( ser, NULL, 0, 0, 0, NULL, 0, NULL, DXGI_FORMAT_UNKNOWN, D3D12_RESOLVE_MODE_DECOMPRESS); break; case D3D12Chunk::List_SetSamplePositions: ret = m_ReplayList->Serialise_SetSamplePositions(ser, 0, NULL, NULL); break; case D3D12Chunk::List_SetViewInstanceMask: ret = m_ReplayList->Serialise_SetViewInstanceMask(ser, 0); break; case D3D12Chunk::List_WriteBufferImmediate: ret = m_ReplayList->Serialise_WriteBufferImmediate(ser, 0, NULL, NULL); break; case D3D12Chunk::List_BeginRenderPass: ret = m_ReplayList->Serialise_BeginRenderPass(ser, 0, NULL, NULL, D3D12_RENDER_PASS_FLAG_NONE); break; case D3D12Chunk::List_EndRenderPass: ret = m_ReplayList->Serialise_EndRenderPass(ser); break; case D3D12Chunk::List_RSSetShadingRate: ret = m_ReplayList->Serialise_RSSetShadingRate(ser, D3D12_SHADING_RATE_1X1, NULL); break; case D3D12Chunk::List_RSSetShadingRateImage: ret = m_ReplayList->Serialise_RSSetShadingRateImage(ser, NULL); break; case D3D12Chunk::PushMarker: ret = m_ReplayList->Serialise_BeginEvent(ser, 0, NULL, 0); break; case D3D12Chunk::PopMarker: ret = m_ReplayList->Serialise_EndEvent(ser); break; case D3D12Chunk::SetMarker: ret = m_ReplayList->Serialise_SetMarker(ser, 0, NULL, 0); break; case D3D12Chunk::Resource_Unmap: ret = m_pDevice->Serialise_MapDataWrite(ser, NULL, 0, NULL, D3D12_RANGE()); break; case D3D12Chunk::Resource_WriteToSubresource: ret = m_pDevice->Serialise_WriteToSubresource(ser, NULL, 0, NULL, NULL, 0, 0); break; case D3D12Chunk::List_IndirectSubCommand: // this is a fake chunk generated at runtime as part of indirect draws. // Just in case it gets exported and imported, completely ignore it. return true; case D3D12Chunk::Swapchain_Present: ret = m_pDevice->Serialise_Present(ser, NULL, 0, 0); break; case D3D12Chunk::List_ClearState: ret = m_ReplayList->Serialise_ClearState(ser, NULL); break; // in order to get a warning if we miss a case, we explicitly handle the device creation chunks // here. If we actually encounter one it's an error (we shouldn't see these inside the captured // frame itself) case D3D12Chunk::Device_CreateCommandQueue: case D3D12Chunk::Device_CreateCommandAllocator: case D3D12Chunk::Device_CreateCommandList: case D3D12Chunk::Device_CreateGraphicsPipeline: case D3D12Chunk::Device_CreateComputePipeline: case D3D12Chunk::Device_CreateDescriptorHeap: case D3D12Chunk::Device_CreateRootSignature: case D3D12Chunk::Device_CreateCommandSignature: case D3D12Chunk::Device_CreateHeap: case D3D12Chunk::Device_CreateCommittedResource: case D3D12Chunk::Device_CreatePlacedResource: case D3D12Chunk::Device_CreateReservedResource: case D3D12Chunk::Device_CreateQueryHeap: case D3D12Chunk::Device_CreateFence: case D3D12Chunk::SetName: case D3D12Chunk::SetShaderDebugPath: case D3D12Chunk::CreateSwapBuffer: case D3D12Chunk::Device_CreatePipelineState: case D3D12Chunk::Device_CreateHeapFromAddress: case D3D12Chunk::Device_CreateHeapFromFileMapping: case D3D12Chunk::Device_OpenSharedHandle: case D3D12Chunk::Device_CreateCommandList1: case D3D12Chunk::Device_CreateCommittedResource1: case D3D12Chunk::Device_CreateHeap1: case D3D12Chunk::Device_ExternalDXGIResource: RDCERR(""Unexpected chunk while processing frame: %s"", ToStr(chunk).c_str()); return false; // no explicit default so that we have compiler warnings if a chunk isn't explicitly handled. case D3D12Chunk::Max: break; } { SystemChunk system = (SystemChunk)chunk; if(system == SystemChunk::CaptureEnd) { SERIALISE_ELEMENT_LOCAL(PresentedImage, ResourceId()).TypedAs(""ID3D12Resource *""_lit); SERIALISE_CHECK_READ_ERRORS(); if(PresentedImage != ResourceId()) m_Cmd.m_LastPresentedImage = PresentedImage; if(IsLoading(m_State) && m_Cmd.m_LastChunk != D3D12Chunk::Swapchain_Present) { m_Cmd.AddEvent(); DrawcallDescription draw; draw.name = ""End of Capture""; draw.flags |= DrawFlags::Present; draw.copyDestination = m_Cmd.m_LastPresentedImage; m_Cmd.AddDrawcall(draw, true); } ret = true; } else if(!ret) { RDCERR(""Unrecognised Chunk type %s"", ToStr(chunk).c_str()); return false; } } if(IsLoading(m_State)) { if(chunk == D3D12Chunk::List_Reset || chunk == D3D12Chunk::List_Close) { // don't add these events - they will be handled when inserted in-line into queue submit } else if(chunk == D3D12Chunk::Queue_EndEvent) { // also ignore, this just pops the drawcall stack } else { if(!m_Cmd.m_AddedDrawcall) m_Cmd.AddEvent(); } } m_Cmd.m_AddedDrawcall = false; return ret; } ReplayStatus WrappedID3D12CommandQueue::ReplayLog(CaptureState readType, uint32_t startEventID, uint32_t endEventID, bool partial) { m_State = readType; if(!m_FrameReader) { RDCERR(""Can't replay context capture without frame reader""); return ReplayStatus::InternalError; } m_FrameReader->SetOffset(0); ReadSerialiser ser(m_FrameReader, Ownership::Nothing); ser.SetStringDatabase(&m_StringDB); ser.SetUserData(GetResourceManager()); ser.SetVersion(m_pDevice->GetLogVersion()); if(IsLoading(m_State) || IsStructuredExporting(m_State)) { ser.ConfigureStructuredExport(&GetChunkName, IsStructuredExporting(m_State)); ser.GetStructuredFile().Swap(m_pDevice->GetStructuredFile()); m_StructuredFile = &ser.GetStructuredFile(); } else { m_StructuredFile = &m_pDevice->GetStructuredFile(); } m_Cmd.m_StructuredFile = m_StructuredFile; SystemChunk header = ser.ReadChunk(); RDCASSERTEQUAL(header, SystemChunk::CaptureBegin); if(partial) ser.SkipCurrentChunk(); else m_pDevice->Serialise_BeginCaptureFrame(ser); ser.EndChunk(); m_Cmd.m_RootEvents.clear(); if(IsLoading(m_State)) { m_pDevice->ApplyInitialContents(); m_pDevice->ExecuteLists(); m_pDevice->FlushLists(); } if(IsActiveReplaying(m_State)) { APIEvent ev = GetEvent(startEventID); m_Cmd.m_RootEventID = ev.eventId; // if not partial, we need to be sure to replay // past the command list records, so can't // skip to the file offset of the first event if(partial) { ser.GetReader()->SetOffset(ev.fileOffset); D3D12CommandData::DrawcallUse use(ev.fileOffset, 0); auto it = std::lower_bound(m_Cmd.m_DrawcallUses.begin(), m_Cmd.m_DrawcallUses.end(), use); if(it != m_Cmd.m_DrawcallUses.end()) { BakedCmdListInfo &cmdInfo = m_Cmd.m_BakedCmdListInfo[it->cmdList]; cmdInfo.curEventID = it->relativeEID; } } m_Cmd.m_FirstEventID = startEventID; m_Cmd.m_LastEventID = endEventID; } else { m_Cmd.m_RootEventID = 1; m_Cmd.m_RootDrawcallID = 1; m_Cmd.m_FirstEventID = 0; m_Cmd.m_LastEventID = ~0U; } uint64_t startOffset = ser.GetReader()->GetOffset(); for(;;) { if(IsActiveReplaying(m_State) && m_Cmd.m_RootEventID > endEventID) { // we can just break out if we've done all the events desired. // note that the command list events aren't 'real' and we just blaze through them break; } m_Cmd.m_CurChunkOffset = ser.GetReader()->GetOffset(); D3D12Chunk context = ser.ReadChunk(); if(ser.GetReader()->IsErrored()) return ReplayStatus::APIDataCorrupted; m_Cmd.m_ChunkMetadata = ser.ChunkMetadata(); m_Cmd.m_LastCmdListID = ResourceId(); bool success = ProcessChunk(ser, context); ser.EndChunk(); if(ser.GetReader()->IsErrored()) return ReplayStatus::APIDataCorrupted; // if there wasn't a serialisation error, but the chunk didn't succeed, then it's an API replay // failure. if(!success) return m_FailedReplayStatus; RenderDoc::Inst().SetProgress( LoadProgress::FrameEventsRead, float(m_Cmd.m_CurChunkOffset - startOffset) / float(ser.GetReader()->GetSize())); if((SystemChunk)context == SystemChunk::CaptureEnd || ser.GetReader()->AtEnd()) break; // break out if we were only executing one event if(IsActiveReplaying(m_State) && startEventID == endEventID) break; m_Cmd.m_LastChunk = context; // increment root event ID either if we didn't just replay a cmd // buffer event, OR if we are doing a frame sub-section replay, // in which case it's up to the calling code to make sure we only // replay inside a command list (if we crossed command list // boundaries, the event IDs would no longer match up). if(m_Cmd.m_LastCmdListID == ResourceId() || startEventID > 1) { m_Cmd.m_RootEventID++; if(startEventID > 1) ser.GetReader()->SetOffset(GetEvent(m_Cmd.m_RootEventID).fileOffset); } else { m_Cmd.m_BakedCmdListInfo[m_Cmd.m_LastCmdListID].curEventID++; } } // swap the structure back now that we've accumulated the frame as well. if(IsLoading(m_State) || IsStructuredExporting(m_State)) ser.GetStructuredFile().Swap(m_pDevice->GetStructuredFile()); m_StructuredFile = NULL; for(size_t i = 0; i < m_Cmd.m_RerecordCmdList.size(); i++) SAFE_RELEASE(m_Cmd.m_RerecordCmdList[i]); m_Cmd.m_RerecordCmds.clear(); m_Cmd.m_RerecordCmdList.clear(); return ReplayStatus::Succeeded; } WrappedID3D12GraphicsCommandList::WrappedID3D12GraphicsCommandList(ID3D12GraphicsCommandList *real, WrappedID3D12Device *device, CaptureState &state) : m_RefCounter(real, false), m_pList(real), m_pDevice(device), m_State(state) { if(RenderDoc::Inst().GetCrashHandler()) RenderDoc::Inst().GetCrashHandler()->RegisterMemoryRegion( this, sizeof(WrappedID3D12GraphicsCommandList)); m_pList1 = NULL; m_pList2 = NULL; m_pList3 = NULL; m_pList4 = NULL; m_pList5 = NULL; m_WrappedDebug.m_pList = this; if(m_pList) { m_pList->QueryInterface(__uuidof(ID3D12DebugCommandList), (void **)&m_WrappedDebug.m_pReal); m_pList->QueryInterface(__uuidof(ID3D12DebugCommandList1), (void **)&m_WrappedDebug.m_pReal1); m_pList->QueryInterface(__uuidof(ID3D12DebugCommandList2), (void **)&m_WrappedDebug.m_pReal2); m_pList->QueryInterface(__uuidof(ID3D12GraphicsCommandList1), (void **)&m_pList1); m_pList->QueryInterface(__uuidof(ID3D12GraphicsCommandList2), (void **)&m_pList2); m_pList->QueryInterface(__uuidof(ID3D12GraphicsCommandList3), (void **)&m_pList3); m_pList->QueryInterface(__uuidof(ID3D12GraphicsCommandList4), (void **)&m_pList4); m_pList->QueryInterface(__uuidof(ID3D12GraphicsCommandList5), (void **)&m_pList5); } // create a temporary and grab its resource ID m_ResourceID = ResourceIDGen::GetNewUniqueID(); RDCEraseEl(m_Init); m_ListRecord = NULL; m_CreationRecord = NULL; m_Cmd = NULL; m_CurGfxRootSig = NULL; m_CurCompRootSig = NULL; if(!RenderDoc::Inst().IsReplayApp()) { m_ListRecord = m_pDevice->GetResourceManager()->AddResourceRecord(m_ResourceID); m_ListRecord->type = Resource_GraphicsCommandList; m_ListRecord->DataInSerialiser = false; m_ListRecord->InternalResource = true; m_ListRecord->Length = 0; m_ListRecord->cmdInfo = new CmdListRecordingInfo(); // this is set up in the implicit Reset() right after creation m_ListRecord->bakedCommands = NULL; // a bit of a hack, we make a parallel resource record with the same lifetime as the command // list and make it a parent, so it will hold onto our create chunk and not try to // record it (and throw it away with baked commands that are unused), then it'll be pulled // into the capture. m_CreationRecord = m_pDevice->GetResourceManager()->AddResourceRecord(ResourceIDGen::GetNewUniqueID()); m_CreationRecord->type = Resource_GraphicsCommandList; m_CreationRecord->InternalResource = true; m_ListRecord->AddParent(m_CreationRecord); } else { m_Cmd = m_pDevice->GetQueue()->GetCommandData(); } if(m_pList) { bool ret = m_pDevice->GetResourceManager()->AddWrapper(this, m_pList); if(!ret) RDCERR(""Error adding wrapper for ID3D12GraphicsCommandList""); } m_pDevice->GetResourceManager()->AddCurrentResource(GetResourceID(), this); m_pDevice->SoftRef(); } WrappedID3D12GraphicsCommandList::~WrappedID3D12GraphicsCommandList() { SAFE_RELEASE(m_AMDMarkers); if(m_pList) m_pDevice->GetResourceManager()->RemoveWrapper(m_pList); if(m_CreationRecord) m_CreationRecord->Delete(m_pDevice->GetResourceManager()); if(m_ListRecord && m_ListRecord->bakedCommands) m_ListRecord->bakedCommands->Delete(m_pDevice->GetResourceManager()); if(m_ListRecord) m_ListRecord->Delete(m_pDevice->GetResourceManager()); m_pDevice->GetResourceManager()->ReleaseCurrentResource(GetResourceID()); SAFE_RELEASE(m_WrappedDebug.m_pReal); SAFE_RELEASE(m_WrappedDebug.m_pReal1); SAFE_RELEASE(m_WrappedDebug.m_pReal2); SAFE_RELEASE(m_pList5); SAFE_RELEASE(m_pList4); SAFE_RELEASE(m_pList3); SAFE_RELEASE(m_pList2); SAFE_RELEASE(m_pList1); SAFE_RELEASE(m_pList); } bool WrappedID3D12GraphicsCommandList::ValidateRootGPUVA(D3D12_GPU_VIRTUAL_ADDRESS buffer) { if(buffer == 0) { // abort, we don't have this buffer. Print errors while reading if(IsLoading(m_State)) { m_pDevice->AddDebugMessage(MessageCategory::Resource_Manipulation, MessageSeverity::Medium, MessageSource::IncorrectAPIUse, ""Binding 0 as a GPU Virtual Address in a root constant is "" ""invalid. This call will be dropped during replay.""); } return true; } return false; } WriteSerialiser &WrappedID3D12GraphicsCommandList::GetThreadSerialiser() { return m_pDevice->GetThreadSerialiser(); } rdcstr WrappedID3D12GraphicsCommandList::GetChunkName(uint32_t idx) { if((SystemChunk)idx < SystemChunk::FirstDriverChunk) return ToStr((SystemChunk)idx); return ToStr((D3D12Chunk)idx); } HRESULT STDMETHODCALLTYPE WrappedID3D12GraphicsCommandList::QueryInterface(REFIID riid, void **ppvObject) { if(riid == __uuidof(IUnknown)) { *ppvObject = (IUnknown *)(ID3D12GraphicsCommandList *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12GraphicsCommandList)) { *ppvObject = (ID3D12GraphicsCommandList *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12DebugCommandList)) { if(m_WrappedDebug.m_pReal) { AddRef(); *ppvObject = (ID3D12DebugCommandList *)&m_WrappedDebug; return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12DebugCommandList1)) { if(m_WrappedDebug.m_pReal1) { AddRef(); *ppvObject = (ID3D12DebugCommandList1 *)&m_WrappedDebug; return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12DebugCommandList2)) { if(m_WrappedDebug.m_pReal2) { AddRef(); *ppvObject = (ID3D12DebugCommandList2 *)&m_WrappedDebug; return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12GraphicsCommandList1)) { if(m_pList1) { *ppvObject = (ID3D12GraphicsCommandList1 *)this; AddRef(); return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12GraphicsCommandList2)) { if(m_pList2) { *ppvObject = (ID3D12GraphicsCommandList2 *)this; AddRef(); return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12GraphicsCommandList3)) { if(m_pList3) { *ppvObject = (ID3D12GraphicsCommandList3 *)this; AddRef(); return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12GraphicsCommandList4)) { if(m_pList4) { *ppvObject = (ID3D12GraphicsCommandList4 *)this; AddRef(); return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12GraphicsCommandList5)) { if(m_pList5) { *ppvObject = (ID3D12GraphicsCommandList5 *)this; AddRef(); return S_OK; } else { return E_NOINTERFACE; } } else if(riid == __uuidof(ID3D12GraphicsCommandList6)) { return E_NOINTERFACE; } else if(riid == __uuidof(ID3D12CommandList)) { *ppvObject = (ID3D12CommandList *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12Pageable)) { *ppvObject = (ID3D12Pageable *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12DeviceChild)) { *ppvObject = (ID3D12DeviceChild *)this; AddRef(); return S_OK; } else if(riid == __uuidof(ID3D12Object)) { *ppvObject = (ID3D12DeviceChild *)this; AddRef(); return S_OK; } else { WarnUnknownGUID(""ID3D12GraphicsCommandList"", riid); } return m_RefCounter.QueryInterface(riid, ppvObject); } void BakedCmdListInfo::ShiftForRemoved(uint32_t shiftDrawID, uint32_t shiftEID, size_t idx) { rdcarray &draws = draw->children; drawCount -= shiftDrawID; eventCount -= shiftEID; if(idx < draws.size()) { for(size_t i = idx; i < draws.size(); i++) { // should have no children as we don't push in for markers since they // can cross command list boundaries. RDCASSERT(draws[i].children.empty()); draws[i].draw.eventId -= shiftEID; draws[i].draw.drawcallId -= shiftDrawID; for(APIEvent &ev : draws[i].draw.events) ev.eventId -= shiftEID; } uint32_t lastEID = draws[idx].draw.eventId; // shift any resource usage for drawcalls after the removed section for(size_t i = 0; i < draw->resourceUsage.size(); i++) { if(draw->resourceUsage[i].second.eventId >= lastEID) draw->resourceUsage[i].second.eventId -= shiftEID; } // patch any subsequent executes for(size_t i = 0; i < executeEvents.size(); i++) { if(executeEvents[i].baseEvent >= lastEID) { executeEvents[i].baseEvent -= shiftEID; if(executeEvents[i].lastEvent > 0) executeEvents[i].lastEvent -= shiftEID; } } } } D3D12CommandData::D3D12CommandData() { m_CurChunkOffset = 0; m_IndirectOffset = 0; m_RootEventID = 1; m_RootDrawcallID = 1; m_FirstEventID = 0; m_LastEventID = ~0U; m_StructuredFile = NULL; m_pDevice = NULL; m_DrawcallCallback = NULL; m_AddedDrawcall = false; m_RootDrawcallStack.push_back(&m_ParentDrawcall); } void D3D12CommandData::GetIndirectBuffer(size_t size, ID3D12Resource **buf, uint64_t *offs) { // check if we need to allocate a new buffer if(m_IndirectBuffers.empty() || m_IndirectOffset + size > m_IndirectSize) { D3D12_RESOURCE_DESC indirectDesc; indirectDesc.Alignment = 0; indirectDesc.DepthOrArraySize = 1; indirectDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; indirectDesc.Flags = D3D12_RESOURCE_FLAG_NONE; indirectDesc.Format = DXGI_FORMAT_UNKNOWN; indirectDesc.Height = 1; indirectDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; indirectDesc.MipLevels = 1; indirectDesc.SampleDesc.Count = 1; indirectDesc.SampleDesc.Quality = 0; indirectDesc.Width = m_IndirectSize; // create a custom heap that sits in CPU memory and is mappable, but we can // use for indirect args (unlike upload and readback). D3D12_HEAP_PROPERTIES heapProps; heapProps.Type = D3D12_HEAP_TYPE_CUSTOM; heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE; heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; heapProps.CreationNodeMask = 1; heapProps.VisibleNodeMask = 1; ID3D12Resource *argbuf = NULL; HRESULT hr = m_pDevice->CreateCommittedResource(&heapProps, D3D12_HEAP_FLAG_NONE, &indirectDesc, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, NULL, __uuidof(ID3D12Resource), (void **)&argbuf); SetObjName(argbuf, StringFormat::Fmt(""Indirect Arg Buf (%llu bytes)"", (uint64_t)size)); if(FAILED(hr)) RDCERR(""Failed to create indirect buffer, HRESULT: %s"", ToStr(hr).c_str()); m_IndirectBuffers.push_back(argbuf); m_IndirectOffset = 0; } *buf = m_IndirectBuffers.back(); *offs = m_IndirectOffset; m_IndirectOffset = AlignUp16(m_IndirectOffset + size); } uint32_t D3D12CommandData::HandlePreCallback(ID3D12GraphicsCommandListX *list, bool dispatch, uint32_t multiDrawOffset) { if(!m_DrawcallCallback) return 0; // look up the EID this drawcall came from DrawcallUse use(m_CurChunkOffset, 0); auto it = std::lower_bound(m_DrawcallUses.begin(), m_DrawcallUses.end(), use); if(it == m_DrawcallUses.end()) { RDCERR(""Couldn't find drawcall use entry for %llu"", m_CurChunkOffset); return 0; } uint32_t eventId = it->eventId; RDCASSERT(eventId != 0); // handle all aliases of this drawcall as long as it's not a multidraw const DrawcallDescription *draw = m_pDevice->GetDrawcall(eventId); if(draw == NULL || !(draw->flags & DrawFlags::MultiDraw)) { ++it; while(it != m_DrawcallUses.end() && it->fileOffset == m_CurChunkOffset) { m_DrawcallCallback->AliasEvent(eventId, it->eventId); ++it; } } eventId += multiDrawOffset; if(dispatch) m_DrawcallCallback->PreDispatch(eventId, list); else m_DrawcallCallback->PreDraw(eventId, list); return eventId; } bool D3D12CommandData::InRerecordRange(ResourceId cmdid) { // if we have an outside command list, assume the range is valid and we're replaying all events // onto it. if(m_OutsideCmdList != NULL) return true; // if not, check if we're one of the actual partial command buffers and check to see if we're in // the range for their partial replay. for(int p = 0; p < ePartialNum; p++) { if(cmdid == m_Partial[p].partialParent) { return m_BakedCmdListInfo[m_Partial[p].partialParent].curEventID <= m_LastEventID - m_Partial[p].baseEvent; } } // otherwise just check if we have a re-record command list for this, as then we're doing a full // re-record and replay return m_RerecordCmds.find(cmdid) != m_RerecordCmds.end(); } bool D3D12CommandData::HasRerecordCmdList(ResourceId cmdid) { if(m_OutsideCmdList != NULL) return true; return m_RerecordCmds.find(cmdid) != m_RerecordCmds.end(); } bool D3D12CommandData::IsPartialCmdList(ResourceId cmdid) { if(m_OutsideCmdList != NULL) return true; for(int p = 0; p < ePartialNum; p++) if(cmdid == m_Partial[p].partialParent) return true; return false; } ID3D12GraphicsCommandListX *D3D12CommandData::RerecordCmdList(ResourceId cmdid, PartialReplayIndex partialType) { if(m_OutsideCmdList != NULL) return m_OutsideCmdList; auto it = m_RerecordCmds.find(cmdid); if(it == m_RerecordCmds.end()) { RDCERR(""Didn't generate re-record command for %s"", ToStr(cmdid).c_str()); return NULL; } return it->second; } bool D3D12CommandData::HasNonMarkerEvents(ResourceId cmdBuffer) { for(const APIEvent &ev : m_BakedCmdListInfo[cmdBuffer].curEvents) { D3D12Chunk chunk = (D3D12Chunk)m_StructuredFile->chunks[ev.chunkIndex]->metadata.chunkID; if(chunk != D3D12Chunk::PushMarker && chunk != D3D12Chunk::PopMarker) return true; } return false; } void D3D12CommandData::AddEvent() { APIEvent apievent; apievent.fileOffset = m_CurChunkOffset; apievent.eventId = m_LastCmdListID != ResourceId() ? m_BakedCmdListInfo[m_LastCmdListID].curEventID : m_RootEventID; apievent.chunkIndex = uint32_t(m_StructuredFile->chunks.size() - 1); apievent.callstack = m_ChunkMetadata.callstack; // if we're using replay-time debug messages, fetch them now since we can do better to correlate // to events on replay if(m_pDevice->GetReplayOptions().apiValidation) m_EventMessages = m_pDevice->GetDebugMessages(); for(size_t i = 0; i < m_EventMessages.size(); i++) m_EventMessages[i].eventId = apievent.eventId; if(m_LastCmdListID != ResourceId()) { m_BakedCmdListInfo[m_LastCmdListID].curEvents.push_back(apievent); rdcarray &msgs = m_BakedCmdListInfo[m_LastCmdListID].debugMessages; msgs.append(m_EventMessages); } else { m_RootEvents.push_back(apievent); m_Events.resize(apievent.eventId + 1); m_Events[apievent.eventId] = apievent; for(auto it = m_EventMessages.begin(); it != m_EventMessages.end(); ++it) m_pDevice->AddDebugMessage(*it); } m_EventMessages.clear(); } void D3D12CommandData::AddUsage(D3D12DrawcallTreeNode &drawNode, ResourceId id, uint32_t EID, ResourceUsage usage) { if(id == ResourceId()) return; drawNode.resourceUsage.push_back(make_rdcpair(id, EventUsage(EID, usage))); } void D3D12CommandData::AddUsage(ResourceId id, ResourceUsage usage) { m_ResourceUses[id].push_back(EventUsage(m_RootEventID, usage)); } void D3D12CommandData::AddUsage(const D3D12RenderState &state, D3D12DrawcallTreeNode &drawNode) { DrawcallDescription &d = drawNode.draw; uint32_t e = d.eventId; DrawFlags DrawMask = DrawFlags::Drawcall | DrawFlags::Dispatch; if(!(d.flags & DrawMask)) return; static bool hugeRangeWarned = false; const D3D12RenderState::RootSignature *rootdata = NULL; if((d.flags & DrawFlags::Dispatch) && state.compute.rootsig != ResourceId()) { rootdata = &state.compute; } else if(state.graphics.rootsig != ResourceId()) { rootdata = &state.graphics; if(d.flags & DrawFlags::Indexed && state.ibuffer.buf != ResourceId()) drawNode.resourceUsage.push_back( make_rdcpair(state.ibuffer.buf, EventUsage(e, ResourceUsage::IndexBuffer))); for(size_t i = 0; i < state.vbuffers.size(); i++) { if(state.vbuffers[i].buf != ResourceId()) drawNode.resourceUsage.push_back( make_rdcpair(state.vbuffers[i].buf, EventUsage(e, ResourceUsage::VertexBuffer))); } for(size_t i = 0; i < state.streamouts.size(); i++) { if(state.streamouts[i].buf != ResourceId()) drawNode.resourceUsage.push_back( make_rdcpair(state.streamouts[i].buf, EventUsage(e, ResourceUsage::StreamOut))); if(state.streamouts[i].countbuf != ResourceId()) drawNode.resourceUsage.push_back( make_rdcpair(state.streamouts[i].countbuf, EventUsage(e, ResourceUsage::StreamOut))); } rdcarray rts = state.GetRTVIDs(); for(size_t i = 0; i < rts.size(); i++) { if(rts[i] != ResourceId()) drawNode.resourceUsage.push_back( make_rdcpair(rts[i], EventUsage(e, ResourceUsage::ColorTarget))); } ResourceId id = state.GetDSVID(); if(id != ResourceId()) drawNode.resourceUsage.push_back( make_rdcpair(id, EventUsage(e, ResourceUsage::DepthStencilTarget))); } if(rootdata) { WrappedID3D12RootSignature *sig = m_pDevice->GetResourceManager()->GetCurrentAs(rootdata->rootsig); for(size_t rootEl = 0; rootEl < sig->sig.Parameters.size(); rootEl++) { if(rootEl >= rootdata->sigelems.size()) break; const D3D12RootSignatureParameter &p = sig->sig.Parameters[rootEl]; const D3D12RenderState::SignatureElement &el = rootdata->sigelems[rootEl]; ResourceUsage cb = ResourceUsage::CS_Constants; ResourceUsage ro = ResourceUsage::CS_Resource; ResourceUsage rw = ResourceUsage::CS_RWResource; if(rootdata == &state.graphics) { if(p.ShaderVisibility == D3D12_SHADER_VISIBILITY_ALL) { cb = ResourceUsage::All_Constants; ro = ResourceUsage::All_Resource; rw = ResourceUsage::All_RWResource; } else { cb = CBUsage(p.ShaderVisibility - D3D12_SHADER_VISIBILITY_VERTEX); ro = ResUsage(p.ShaderVisibility - D3D12_SHADER_VISIBILITY_VERTEX); rw = RWResUsage(p.ShaderVisibility - D3D12_SHADER_VISIBILITY_VERTEX); } } if(p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV && el.type == eRootCBV) { AddUsage(drawNode, el.id, e, cb); } else if(p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV && el.type == eRootSRV) { AddUsage(drawNode, el.id, e, ro); } else if(p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV && el.type == eRootUAV) { AddUsage(drawNode, el.id, e, rw); } else if(p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE && el.type == eRootTable) { WrappedID3D12DescriptorHeap *heap = m_pDevice->GetResourceManager()->GetCurrentAs(el.id); if(heap == NULL) continue; UINT prevTableOffset = 0; for(size_t r = 0; r < p.ranges.size(); r++) { const D3D12_DESCRIPTOR_RANGE1 &range = p.ranges[r]; UINT offset = range.OffsetInDescriptorsFromTableStart; if(range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) offset = prevTableOffset; D3D12Descriptor *desc = (D3D12Descriptor *)heap->GetCPUDescriptorHandleForHeapStart().ptr; desc += el.offset; desc += offset; UINT num = range.NumDescriptors; if(num == UINT_MAX) { // find out how many descriptors are left after num = heap->GetNumDescriptors() - offset - UINT(el.offset); } prevTableOffset = offset + num; if(range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) { EventUsage usage(e, cb); if(num > 1000) { if(!hugeRangeWarned) RDCWARN(""Skipping large, most likely 'bindless', descriptor range""); hugeRangeWarned = true; } else { for(UINT i = 0; i < num; i++) { ResourceId id = WrappedID3D12Resource1::GetResIDFromAddr(desc->GetCBV().BufferLocation); AddUsage(drawNode, id, e, cb); desc++; } } } else if(range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) { ResourceUsage usage = range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV ? ro : rw; if(num > 1000) { if(!hugeRangeWarned) RDCWARN(""Skipping large, most likely 'bindless', descriptor range""); hugeRangeWarned = true; } else { for(UINT i = 0; i < num; i++) { AddUsage(drawNode, desc->GetResResourceId(), e, usage); desc++; } } } } } } } } void D3D12CommandData::AddDrawcall(const DrawcallDescription &d, bool hasEvents, bool addUsage) { m_AddedDrawcall = true; DrawcallDescription draw = d; draw.eventId = m_LastCmdListID != ResourceId() ? m_BakedCmdListInfo[m_LastCmdListID].curEventID : m_RootEventID; draw.drawcallId = m_LastCmdListID != ResourceId() ? m_BakedCmdListInfo[m_LastCmdListID].drawCount : m_RootDrawcallID; for(int i = 0; i < 8; i++) draw.outputs[i] = ResourceId(); draw.depthOut = ResourceId(); draw.indexByteWidth = 0; draw.topology = Topology::Unknown; if(m_LastCmdListID != ResourceId()) { draw.topology = MakePrimitiveTopology(m_BakedCmdListInfo[m_LastCmdListID].state.topo); draw.indexByteWidth = m_BakedCmdListInfo[m_LastCmdListID].state.ibuffer.bytewidth; rdcarray rts = m_BakedCmdListInfo[m_LastCmdListID].state.GetRTVIDs(); for(size_t i = 0; i < ARRAY_COUNT(draw.outputs); i++) { if(i < rts.size()) draw.outputs[i] = m_pDevice->GetResourceManager()->GetOriginalID(rts[i]); else draw.outputs[i] = ResourceId(); } draw.depthOut = m_pDevice->GetResourceManager()->GetOriginalID( m_BakedCmdListInfo[m_LastCmdListID].state.GetDSVID()); } // markers don't increment drawcall ID DrawFlags MarkerMask = DrawFlags::SetMarker | DrawFlags::PushMarker | DrawFlags::PassBoundary; if(!(draw.flags & MarkerMask)) { if(m_LastCmdListID != ResourceId()) m_BakedCmdListInfo[m_LastCmdListID].drawCount++; else m_RootDrawcallID++; } if(hasEvents) { rdcarray &srcEvents = m_LastCmdListID != ResourceId() ? m_BakedCmdListInfo[m_LastCmdListID].curEvents : m_RootEvents; draw.events = srcEvents; srcEvents.clear(); } // should have at least the root drawcall here, push this drawcall // onto the back's children list. if(!GetDrawcallStack().empty()) { D3D12DrawcallTreeNode node(draw); node.resourceUsage.swap(m_BakedCmdListInfo[m_LastCmdListID].resourceUsage); if(m_LastCmdListID != ResourceId() && addUsage) AddUsage(m_BakedCmdListInfo[m_LastCmdListID].state, node); for(const DrawcallDescription &child : draw.children) node.children.push_back(D3D12DrawcallTreeNode(child)); GetDrawcallStack().back()->children.push_back(node); } else RDCERR(""Somehow lost drawcall stack!""); } void D3D12CommandData::InsertDrawsAndRefreshIDs(ResourceId cmd, rdcarray &cmdBufNodes) { // assign new drawcall IDs for(size_t i = 0; i < cmdBufNodes.size(); i++) { if(cmdBufNodes[i].draw.flags & DrawFlags::PopMarker) { if(GetDrawcallStack().size() > 1) GetDrawcallStack().pop_back(); // Skip - pop marker draws aren't processed otherwise, we just apply them to the drawcall // stack. continue; } D3D12DrawcallTreeNode n = cmdBufNodes[i]; n.draw.eventId += m_RootEventID; n.draw.drawcallId += m_RootDrawcallID; for(APIEvent &ev : n.draw.events) { ev.eventId += m_RootEventID; m_Events.resize(ev.eventId + 1); m_Events[ev.eventId] = ev; } DrawcallUse use(m_Events.back().fileOffset, n.draw.eventId, cmd, cmdBufNodes[i].draw.eventId); // insert in sorted location auto drawit = std::lower_bound(m_DrawcallUses.begin(), m_DrawcallUses.end(), use); m_DrawcallUses.insert(drawit - m_DrawcallUses.begin(), use); RDCASSERT(n.children.empty()); for(auto it = n.resourceUsage.begin(); it != n.resourceUsage.end(); ++it) { EventUsage u = it->second; u.eventId += m_RootEventID; m_ResourceUses[it->first].push_back(u); } GetDrawcallStack().back()->children.push_back(n); // if this is a push marker too, step down the drawcall stack if(cmdBufNodes[i].draw.flags & DrawFlags::PushMarker) GetDrawcallStack().push_back(&GetDrawcallStack().back()->children.back()); } } ",16299,True,2728.4120248842933,median "/* Copyright (c) 2010-2016, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file ispc.cpp @brief ispc global definitions */ #include ""ispc.h"" #include ""llvmutil.h"" #include ""module.h"" #include ""util.h"" #include #include /* va_list, va_start, va_arg, va_end */ #include #ifdef ISPC_IS_WINDOWS #include #include #define strcasecmp stricmp #if ISPC_LLVM_VERSION >= ISPC_LLVM_7_0 #include #endif #else #include #include #endif #if ISPC_LLVM_VERSION == ISPC_LLVM_3_2 #include #include #include #else /* 3.3+ */ #include #include #include #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_6 // LLVM 3.6+ #if ISPC_LLVM_VERSION >= ISPC_LLVM_6_0 #include #include #else #include #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ #include #endif #endif #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_5 // LLVM 3.5+ #include #include #else // LLVM 3.2, 3.3, 3.4 #include #include #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_5_0 // LLVM 5.0+ #include #else // LLVM up to 4.x #include #endif #include #include #if ISPC_LLVM_VERSION == ISPC_LLVM_3_2 #include #else // LLVM 3.3+ #include #include #endif #include #include #include #include Globals *g; Module *m; /////////////////////////////////////////////////////////////////////////// // Target #if !defined(ISPC_IS_WINDOWS) && !defined(__arm__) static void __cpuid(int info[4], int infoType) { __asm__ __volatile__(""cpuid"" : ""=a""(info[0]), ""=b""(info[1]), ""=c""(info[2]), ""=d""(info[3]) : ""0""(infoType)); } /* Save %ebx in case it's the PIC register */ static void __cpuidex(int info[4], int level, int count) { __asm__ __volatile__(""xchg{l}\\t{%%}ebx, %1\\n\\t"" ""cpuid\\n\\t"" ""xchg{l}\\t{%%}ebx, %1\\n\\t"" : ""=a""(info[0]), ""=r""(info[1]), ""=c""(info[2]), ""=d""(info[3]) : ""0""(level), ""2""(count)); } #endif // !ISPC_IS_WINDOWS && !__ARM__ #if !defined(__arm__) static bool __os_has_avx_support() { #if defined(ISPC_IS_WINDOWS) // Check if the OS will save the YMM registers unsigned long long xcrFeatureMask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK); return (xcrFeatureMask & 6) == 6; #else // !defined(ISPC_IS_WINDOWS) // Check xgetbv; this uses a .byte sequence instead of the instruction // directly because older assemblers do not include support for xgetbv and // there is no easy way to conditionally compile based on the assembler used. int rEAX, rEDX; __asm__ __volatile__("".byte 0x0f, 0x01, 0xd0"" : ""=a""(rEAX), ""=d""(rEDX) : ""c""(0)); return (rEAX & 6) == 6; #endif // !defined(ISPC_IS_WINDOWS) } static bool __os_has_avx512_support() { #if defined(ISPC_IS_WINDOWS) // Check if the OS saves the XMM, YMM and ZMM registers, i.e. it supports AVX2 and AVX512. // See section 2.1 of software.intel.com/sites/default/files/managed/0d/53/319433-022.pdf unsigned long long xcrFeatureMask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK); return (xcrFeatureMask & 0xE6) == 0xE6; #else // !defined(ISPC_IS_WINDOWS) // Check xgetbv; this uses a .byte sequence instead of the instruction // directly because older assemblers do not include support for xgetbv and // there is no easy way to conditionally compile based on the assembler used. int rEAX, rEDX; __asm__ __volatile__("".byte 0x0f, 0x01, 0xd0"" : ""=a""(rEAX), ""=d""(rEDX) : ""c""(0)); return (rEAX & 0xE6) == 0xE6; #endif // !defined(ISPC_IS_WINDOWS) } #endif // !__arm__ static const char *lGetSystemISA() { #ifdef __arm__ return ""neon-i32x4""; #else int info[4]; __cpuid(info, 1); int info2[4]; // Call cpuid with eax=7, ecx=0 __cpuidex(info2, 7, 0); if ((info[2] & (1 << 27)) != 0 && // OSXSAVE (info2[1] & (1 << 5)) != 0 && // AVX2 (info2[1] & (1 << 16)) != 0 && // AVX512 F __os_has_avx512_support()) { // We need to verify that AVX2 is also available, // as well as AVX512, because our targets are supposed // to use both. if ((info2[1] & (1 << 17)) != 0 && // AVX512 DQ (info2[1] & (1 << 28)) != 0 && // AVX512 CDI (info2[1] & (1 << 30)) != 0 && // AVX512 BW (info2[1] & (1 << 31)) != 0) { // AVX512 VL return ""avx512skx-i32x16""; } else if ((info2[1] & (1 << 26)) != 0 && // AVX512 PF (info2[1] & (1 << 27)) != 0 && // AVX512 ER (info2[1] & (1 << 28)) != 0) { // AVX512 CDI return ""avx512knl-i32x16""; } // If it's unknown AVX512 target, fall through and use AVX2 // or whatever is available in the machine. } if ((info[2] & (1 << 27)) != 0 && // OSXSAVE (info[2] & (1 << 28)) != 0 && __os_has_avx_support()) { // AVX // AVX1 for sure.... // Ivy Bridge? if ((info[2] & (1 << 29)) != 0 && // F16C (info[2] & (1 << 30)) != 0) { // RDRAND // So far, so good. AVX2? if ((info2[1] & (1 << 5)) != 0) return ""avx2-i32x8""; else return ""avx1.1-i32x8""; } // Regular AVX return ""avx1-i32x8""; } else if ((info[2] & (1 << 19)) != 0) return ""sse4-i32x4""; else if ((info[3] & (1 << 26)) != 0) return ""sse2-i32x4""; else { Error(SourcePos(), ""Unable to detect supported SSE/AVX ISA. Exiting.""); exit(1); } #endif } typedef enum { // Special value, indicates that no CPU is present. CPU_None = 0, // 'Generic' CPU without any hardware SIMD capabilities. CPU_Generic = 1, // A generic 64-bit specific x86 processor model which tries to be good // for modern chips without enabling instruction set encodings past the // basic SSE2 and 64-bit ones CPU_x86_64, // Early Atom CPU. Supports SSSE3. CPU_Bonnell, // Generic Core2-like. Supports SSSE3. Isn`t quite compatible with Bonnell, // but for ISPC the difference is negligible; ISPC doesn`t make use of it. CPU_Core2, // Core2 Solo/Duo/Quad/Extreme. Supports SSE 4.1 (but not 4.2). CPU_Penryn, // Late Core2-like. Supports SSE 4.2 + POPCNT/LZCNT. CPU_Nehalem, // Sandy Bridge. Supports AVX 1. CPU_SandyBridge, // Ivy Bridge. Supports AVX 1 + RDRAND. CPU_IvyBridge, // Haswell. Supports AVX 2. CPU_Haswell, #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_6 // LLVM 3.6+ // Broadwell. Supports AVX 2 + ADX/RDSEED/SMAP. CPU_Broadwell, #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ // Knights Landing - Xeon Phi. // Supports AVX-512F: All the key AVX-512 features: masking, broadcast... ; // AVX-512CDI: Conflict Detection; // AVX-512ERI & PRI: 28-bit precision RCP, RSQRT and EXP transcendentals, // new prefetch instructions. CPU_KNL, #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ // Skylake Xeon. // Supports AVX-512F: All the key AVX-512 features: masking, broadcast... ; // AVX-512CDI: Conflict Detection; // AVX-512VL: Vector Length Orthogonality; // AVX-512DQ: New HPC ISA (vs AVX512F); // AVX-512BW: Byte and Word Support. CPU_SKX, #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_4 // LLVM 3.4+ // Late Atom-like design. Supports SSE 4.2 + POPCNT/LZCNT. CPU_Silvermont, #endif // FIXME: LLVM supports a ton of different ARM CPU variants--not just // cortex-a9 and a15. We should be able to handle any of them that also // have NEON support. #ifdef ISPC_ARM_ENABLED // ARM Cortex A15. Supports NEON VFPv4. CPU_CortexA15, // ARM Cortex A9. Supports NEON VFPv3. CPU_CortexA9, #endif #ifdef ISPC_NVPTX_ENABLED // NVidia CUDA-compatible SM-35 architecture. CPU_SM35, #endif sizeofCPUtype } CPUtype; class AllCPUs { private: std::vector> names; std::vector> compat; std::set Set(int type, ...) { std::set retn; va_list args; retn.insert((CPUtype)type); va_start(args, type); while ((type = va_arg(args, int)) != CPU_None) retn.insert((CPUtype)type); va_end(args); return retn; } public: AllCPUs() { names = std::vector>(sizeofCPUtype); compat = std::vector>(sizeofCPUtype); names[CPU_None].push_back(""""); names[CPU_Generic].push_back(""generic""); names[CPU_x86_64].push_back(""x86-64""); names[CPU_Bonnell].push_back(""atom""); names[CPU_Bonnell].push_back(""bonnell""); names[CPU_Core2].push_back(""core2""); names[CPU_Penryn].push_back(""penryn""); #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_4 // LLVM 3.4+ names[CPU_Silvermont].push_back(""slm""); names[CPU_Silvermont].push_back(""silvermont""); #endif names[CPU_Nehalem].push_back(""corei7""); names[CPU_Nehalem].push_back(""nehalem""); names[CPU_SandyBridge].push_back(""corei7-avx""); names[CPU_SandyBridge].push_back(""sandybridge""); names[CPU_IvyBridge].push_back(""core-avx-i""); names[CPU_IvyBridge].push_back(""ivybridge""); names[CPU_Haswell].push_back(""core-avx2""); names[CPU_Haswell].push_back(""haswell""); #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_6 // LLVM 3.6+ names[CPU_Broadwell].push_back(""broadwell""); #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ names[CPU_KNL].push_back(""knl""); #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ names[CPU_SKX].push_back(""skx""); #endif #ifdef ISPC_ARM_ENABLED names[CPU_CortexA15].push_back(""cortex-a15""); names[CPU_CortexA9].push_back(""cortex-a9""); #endif #ifdef ISPC_NVPTX_ENABLED names[CPU_SM35].push_back(""sm_35""); #endif #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_3 // LLVM 3.2 or 3.3 #define CPU_Silvermont CPU_Nehalem #else /* LLVM 3.4+ */ compat[CPU_Silvermont] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_None); #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ compat[CPU_KNL] = Set(CPU_KNL, CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_SandyBridge, CPU_IvyBridge, CPU_Haswell, CPU_Broadwell, CPU_None); #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ compat[CPU_SKX] = Set(CPU_SKX, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_SandyBridge, CPU_IvyBridge, CPU_Haswell, CPU_Broadwell, CPU_None); #endif #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_5 // LLVM 3.2, 3.3, 3.4 or 3.5 #define CPU_Broadwell CPU_Haswell #else /* LLVM 3.6+ */ compat[CPU_Broadwell] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_SandyBridge, CPU_IvyBridge, CPU_Haswell, CPU_Broadwell, CPU_None); #endif compat[CPU_Haswell] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_SandyBridge, CPU_IvyBridge, CPU_Haswell, CPU_Broadwell, CPU_None); compat[CPU_IvyBridge] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_SandyBridge, CPU_IvyBridge, CPU_None); compat[CPU_SandyBridge] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_SandyBridge, CPU_None); compat[CPU_Nehalem] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_None); compat[CPU_Penryn] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Penryn, CPU_Core2, CPU_Nehalem, CPU_Silvermont, CPU_None); compat[CPU_Core2] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Core2, CPU_None); compat[CPU_Bonnell] = Set(CPU_Generic, CPU_x86_64, CPU_Bonnell, CPU_Core2, CPU_None); compat[CPU_Generic] = Set(CPU_Generic, CPU_None); compat[CPU_x86_64] = Set(CPU_Generic, CPU_x86_64, CPU_None); #ifdef ISPC_ARM_ENABLED compat[CPU_CortexA15] = Set(CPU_Generic, CPU_CortexA9, CPU_CortexA15, CPU_None); compat[CPU_CortexA9] = Set(CPU_Generic, CPU_CortexA9, CPU_None); #endif #ifdef ISPC_NVPTX_ENABLED compat[CPU_SM35] = Set(CPU_Generic, CPU_SM35, CPU_None); #endif } std::string HumanReadableListOfNames() { std::stringstream CPUs; for (int i = CPU_Generic; i < sizeofCPUtype; i++) { CPUs << names[i][0]; if (names[i].size() > 1) { CPUs << "" (synonyms: "" << names[i][1]; for (int j = 2, je = names[i].size(); j < je; j++) CPUs << "", "" << names[i][j]; CPUs << "")""; } if (i < sizeofCPUtype - 1) CPUs << "", ""; } return CPUs.str(); } std::string &GetDefaultNameFromType(CPUtype type) { Assert((type >= CPU_None) && (type < sizeofCPUtype)); return names[type][0]; } CPUtype GetTypeFromName(std::string name) { CPUtype retn = CPU_None; for (int i = 1; (retn == CPU_None) && (i < sizeofCPUtype); i++) for (int j = 0, je = names[i].size(); (retn == CPU_None) && (j < je); j++) if (!name.compare(names[i][j])) retn = (CPUtype)i; return retn; } bool BackwardCompatible(CPUtype what, CPUtype with) { Assert((what > CPU_None) && (what < sizeofCPUtype)); Assert((with > CPU_None) && (with < sizeofCPUtype)); return compat[what].find(with) != compat[what].end(); } }; Target::Target(const char *arch, const char *cpu, const char *isa, bool pic, bool printTarget, std::string genericAsSmth) : m_target(NULL), m_targetMachine(NULL), m_dataLayout(NULL), m_valid(false), m_isa(SSE2), m_treatGenericAsSmth(genericAsSmth), m_arch(""""), m_is32Bit(true), m_cpu(""""), m_attributes(""""), #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_3 m_tf_attributes(NULL), #endif m_nativeVectorWidth(-1), m_nativeVectorAlignment(-1), m_dataTypeWidth(-1), m_vectorWidth(-1), m_generatePIC(pic), m_maskingIsFree(false), m_maskBitCount(-1), m_hasHalf(false), m_hasRand(false), m_hasGather(false), m_hasScatter(false), m_hasTranscendentals(false), m_hasTrigonometry(false), m_hasRsqrtd(false), m_hasRcpd(false), m_hasVecPrefetch(false) { CPUtype CPUID = CPU_None, CPUfromISA = CPU_None; AllCPUs a; if (cpu) { CPUID = a.GetTypeFromName(cpu); if (CPUID == CPU_None) { Error(SourcePos(), ""Error: CPU type \\""%s\\"" unknown. Supported"" "" CPUs: %s."", cpu, a.HumanReadableListOfNames().c_str()); return; } } if (isa == NULL) { // If a CPU was specified explicitly, try to pick the best // possible ISA based on that. switch (CPUID) { case CPU_None: // No CPU and no ISA, so use system info to figure out // what this CPU supports. isa = lGetSystemISA(); Warning(SourcePos(), ""No --target specified on command-line."" "" Using default system target \\""%s\\""."", isa); break; case CPU_Generic: isa = ""generic-1""; break; #ifdef ISPC_NVPTX_ENABLED case CPU_SM35: isa = ""nvptx""; break; #endif #ifdef ISPC_ARM_ENABLED case CPU_CortexA9: case CPU_CortexA15: isa = ""neon-i32x4""; break; #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ case CPU_KNL: isa = ""avx512knl-i32x16""; break; #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ case CPU_SKX: isa = ""avx512skx-i32x16""; break; #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_6 case CPU_Broadwell: #endif case CPU_Haswell: isa = ""avx2-i32x8""; break; case CPU_IvyBridge: isa = ""avx1.1-i32x8""; break; case CPU_SandyBridge: isa = ""avx1-i32x8""; break; // Penryn is here because ISPC does not use SSE 4.2 case CPU_Penryn: case CPU_Nehalem: #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_4 case CPU_Silvermont: #endif isa = ""sse4-i32x4""; break; default: isa = ""sse2-i32x4""; break; } if (CPUID != CPU_None) Warning(SourcePos(), ""No --target specified on command-line."" "" Using ISA \\""%s\\"" based on specified CPU \\""%s\\""."", isa, cpu); } if (!strcasecmp(isa, ""host"")) { isa = lGetSystemISA(); } if (arch == NULL) { #ifdef ISPC_ARM_ENABLED if (!strncmp(isa, ""neon"", 4)) arch = ""arm""; else #endif #ifdef ISPC_NVPTX_ENABLED if (!strncmp(isa, ""nvptx"", 5)) arch = ""nvptx64""; else #endif /* ISPC_NVPTX_ENABLED */ arch = ""x86-64""; } // Define arch alias if (std::string(arch) == ""x86_64"") arch = ""x86-64""; bool error = false; // Make sure the target architecture is a known one; print an error // with the valid ones otherwise. #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ for (llvm::TargetRegistry::iterator iter = llvm::TargetRegistry::targets().begin(); iter != llvm::TargetRegistry::targets().end(); ++iter) { #else for (llvm::TargetRegistry::iterator iter = llvm::TargetRegistry::begin(); iter != llvm::TargetRegistry::end(); ++iter) { #endif if (std::string(arch) == iter->getName()) { this->m_target = &*iter; break; } } if (this->m_target == NULL) { fprintf(stderr, ""Invalid architecture \\""%s\\""\\nOptions: "", arch); llvm::TargetRegistry::iterator iter; #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ for (iter = llvm::TargetRegistry::targets().begin(); iter != llvm::TargetRegistry::targets().end(); ++iter) #else for (iter = llvm::TargetRegistry::begin(); iter != llvm::TargetRegistry::end(); ++iter) #endif fprintf(stderr, ""%s "", iter->getName()); fprintf(stderr, ""\\n""); error = true; } else { this->m_arch = arch; } // Check default LLVM generated targets if (!strcasecmp(isa, ""sse2"") || !strcasecmp(isa, ""sse2-i32x4"")) { this->m_isa = Target::SSE2; this->m_nativeVectorWidth = 4; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 32; this->m_vectorWidth = 4; this->m_maskingIsFree = false; this->m_maskBitCount = 32; CPUfromISA = CPU_x86_64; } else if (!strcasecmp(isa, ""sse2-x2"") || !strcasecmp(isa, ""sse2-i32x8"")) { this->m_isa = Target::SSE2; this->m_nativeVectorWidth = 4; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 32; this->m_vectorWidth = 8; this->m_maskingIsFree = false; this->m_maskBitCount = 32; CPUfromISA = CPU_Core2; } else if (!strcasecmp(isa, ""sse4"") || !strcasecmp(isa, ""sse4-i32x4"")) { this->m_isa = Target::SSE4; this->m_nativeVectorWidth = 4; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 32; this->m_vectorWidth = 4; this->m_maskingIsFree = false; this->m_maskBitCount = 32; CPUfromISA = CPU_Nehalem; } else if (!strcasecmp(isa, ""sse4x2"") || !strcasecmp(isa, ""sse4-x2"") || !strcasecmp(isa, ""sse4-i32x8"")) { this->m_isa = Target::SSE4; this->m_nativeVectorWidth = 4; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 32; this->m_vectorWidth = 8; this->m_maskingIsFree = false; this->m_maskBitCount = 32; CPUfromISA = CPU_Nehalem; } else if (!strcasecmp(isa, ""sse4-i8x16"")) { this->m_isa = Target::SSE4; this->m_nativeVectorWidth = 16; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 8; this->m_vectorWidth = 16; this->m_maskingIsFree = false; this->m_maskBitCount = 8; CPUfromISA = CPU_Nehalem; } else if (!strcasecmp(isa, ""sse4-i16x8"")) { this->m_isa = Target::SSE4; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 16; this->m_vectorWidth = 8; this->m_maskingIsFree = false; this->m_maskBitCount = 16; CPUfromISA = CPU_Nehalem; } else if (!strcasecmp(isa, ""generic-4"") || !strcasecmp(isa, ""generic-x4"")) { this->m_isa = Target::GENERIC; this->m_nativeVectorWidth = 4; this->m_nativeVectorAlignment = 16; this->m_vectorWidth = 4; this->m_maskingIsFree = true; this->m_maskBitCount = 1; this->m_hasHalf = true; this->m_hasTranscendentals = true; this->m_hasTrigonometry = true; this->m_hasGather = this->m_hasScatter = true; this->m_hasRsqrtd = this->m_hasRcpd = true; CPUfromISA = CPU_Generic; } else if (!strcasecmp(isa, ""generic-8"") || !strcasecmp(isa, ""generic-x8"")) { this->m_isa = Target::GENERIC; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 32; this->m_vectorWidth = 8; this->m_maskingIsFree = true; this->m_maskBitCount = 1; this->m_hasHalf = true; this->m_hasTranscendentals = true; this->m_hasTrigonometry = true; this->m_hasGather = this->m_hasScatter = true; this->m_hasRsqrtd = this->m_hasRcpd = true; CPUfromISA = CPU_Generic; } else if (!strcasecmp(isa, ""generic-16"") || !strcasecmp(isa, ""generic-x16"") || // We treat *-generic-16 as generic-16, but with special name mangling strstr(isa, ""-generic-16"") || strstr(isa, ""-generic-x16"")) { this->m_isa = Target::GENERIC; if (strstr(isa, ""-generic-16"") || strstr(isa, ""-generic-x16"")) { // It is used for appropriate name mangling and dispatch function during multitarget compilation this->m_treatGenericAsSmth = isa; // We need to create appropriate name for mangling. // Remove ""-x16"" or ""-16"" and replace ""-"" with ""_"". this->m_treatGenericAsSmth = this->m_treatGenericAsSmth.substr(0, this->m_treatGenericAsSmth.find_last_of(""-"")); std::replace(this->m_treatGenericAsSmth.begin(), this->m_treatGenericAsSmth.end(), '-', '_'); } this->m_nativeVectorWidth = 16; this->m_nativeVectorAlignment = 64; this->m_vectorWidth = 16; this->m_maskingIsFree = true; this->m_maskBitCount = 1; this->m_hasHalf = true; this->m_hasTranscendentals = true; // It's set to false, because stdlib implementation of math functions // is faster on MIC, than ""native"" implementation provided by the // icc compiler. this->m_hasTrigonometry = false; this->m_hasGather = this->m_hasScatter = true; this->m_hasRsqrtd = this->m_hasRcpd = true; // It's set to true, because MIC has hardware vector prefetch instruction this->m_hasVecPrefetch = true; CPUfromISA = CPU_Generic; } else if (!strcasecmp(isa, ""generic-32"") || !strcasecmp(isa, ""generic-x32"")) { this->m_isa = Target::GENERIC; this->m_nativeVectorWidth = 32; this->m_nativeVectorAlignment = 64; this->m_vectorWidth = 32; this->m_maskingIsFree = true; this->m_maskBitCount = 1; this->m_hasHalf = true; this->m_hasTranscendentals = true; this->m_hasTrigonometry = true; this->m_hasGather = this->m_hasScatter = true; this->m_hasRsqrtd = this->m_hasRcpd = true; CPUfromISA = CPU_Generic; } else if (!strcasecmp(isa, ""generic-64"") || !strcasecmp(isa, ""generic-x64"")) { this->m_isa = Target::GENERIC; this->m_nativeVectorWidth = 64; this->m_nativeVectorAlignment = 64; this->m_vectorWidth = 64; this->m_maskingIsFree = true; this->m_maskBitCount = 1; this->m_hasHalf = true; this->m_hasTranscendentals = true; this->m_hasTrigonometry = true; this->m_hasGather = this->m_hasScatter = true; this->m_hasRsqrtd = this->m_hasRcpd = true; CPUfromISA = CPU_Generic; } else if (!strcasecmp(isa, ""generic-1"") || !strcasecmp(isa, ""generic-x1"")) { this->m_isa = Target::GENERIC; this->m_nativeVectorWidth = 1; this->m_nativeVectorAlignment = 16; this->m_vectorWidth = 1; this->m_maskingIsFree = false; this->m_maskBitCount = 32; CPUfromISA = CPU_Generic; } else if (!strcasecmp(isa, ""avx1-i32x4"")) { this->m_isa = Target::AVX; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 32; this->m_vectorWidth = 4; this->m_maskingIsFree = false; this->m_maskBitCount = 32; CPUfromISA = CPU_SandyBridge; } else if (!strcasecmp(isa, ""avx"") || !strcasecmp(isa, ""avx1"") || !strcasecmp(isa, ""avx1-i32x8"")) { this->m_isa = Target::AVX; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 32; this->m_vectorWidth = 8; this->m_maskingIsFree = false; this->m_maskBitCount = 32; CPUfromISA = CPU_SandyBridge; } else if (!strcasecmp(isa, ""avx-i64x4"") || !strcasecmp(isa, ""avx1-i64x4"")) { this->m_isa = Target::AVX; this->m_nativeVectorWidth = 8; /* native vector width in terms of floats */ this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 64; this->m_vectorWidth = 4; this->m_maskingIsFree = false; this->m_maskBitCount = 64; CPUfromISA = CPU_SandyBridge; } else if (!strcasecmp(isa, ""avx-x2"") || !strcasecmp(isa, ""avx1-x2"") || !strcasecmp(isa, ""avx1-i32x16"")) { this->m_isa = Target::AVX; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 32; this->m_vectorWidth = 16; this->m_maskingIsFree = false; this->m_maskBitCount = 32; CPUfromISA = CPU_SandyBridge; } else if (!strcasecmp(isa, ""avx1.1"") || !strcasecmp(isa, ""avx1.1-i32x8"")) { this->m_isa = Target::AVX11; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 32; this->m_vectorWidth = 8; this->m_maskingIsFree = false; this->m_maskBitCount = 32; this->m_hasHalf = true; this->m_hasRand = true; CPUfromISA = CPU_IvyBridge; } else if (!strcasecmp(isa, ""avx1.1-x2"") || !strcasecmp(isa, ""avx1.1-i32x16"")) { this->m_isa = Target::AVX11; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 32; this->m_vectorWidth = 16; this->m_maskingIsFree = false; this->m_maskBitCount = 32; this->m_hasHalf = true; this->m_hasRand = true; CPUfromISA = CPU_IvyBridge; } else if (!strcasecmp(isa, ""avx1.1-i64x4"")) { this->m_isa = Target::AVX11; this->m_nativeVectorWidth = 8; /* native vector width in terms of floats */ this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 64; this->m_vectorWidth = 4; this->m_maskingIsFree = false; this->m_maskBitCount = 64; this->m_hasHalf = true; this->m_hasRand = true; CPUfromISA = CPU_IvyBridge; } else if (!strcasecmp(isa, ""avx2"") || !strcasecmp(isa, ""avx2-i32x8"")) { this->m_isa = Target::AVX2; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 32; this->m_vectorWidth = 8; this->m_maskingIsFree = false; this->m_maskBitCount = 32; this->m_hasHalf = true; this->m_hasRand = true; this->m_hasGather = true; CPUfromISA = CPU_Haswell; } else if (!strcasecmp(isa, ""avx2-x2"") || !strcasecmp(isa, ""avx2-i32x16"")) { this->m_isa = Target::AVX2; this->m_nativeVectorWidth = 16; this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 32; this->m_vectorWidth = 16; this->m_maskingIsFree = false; this->m_maskBitCount = 32; this->m_hasHalf = true; this->m_hasRand = true; this->m_hasGather = true; CPUfromISA = CPU_Haswell; } else if (!strcasecmp(isa, ""avx2-i64x4"")) { this->m_isa = Target::AVX2; this->m_nativeVectorWidth = 8; /* native vector width in terms of floats */ this->m_nativeVectorAlignment = 32; this->m_dataTypeWidth = 64; this->m_vectorWidth = 4; this->m_maskingIsFree = false; this->m_maskBitCount = 64; this->m_hasHalf = true; this->m_hasRand = true; this->m_hasGather = true; CPUfromISA = CPU_Haswell; } #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ else if (!strcasecmp(isa, ""avx512knl-i32x16"")) { this->m_isa = Target::KNL_AVX512; this->m_nativeVectorWidth = 16; this->m_nativeVectorAlignment = 64; this->m_dataTypeWidth = 32; this->m_vectorWidth = 16; this->m_maskingIsFree = true; this->m_maskBitCount = 8; this->m_hasHalf = true; this->m_hasRand = true; this->m_hasGather = this->m_hasScatter = true; this->m_hasTranscendentals = false; // For MIC it is set to true due to performance reasons. The option should be tested. this->m_hasTrigonometry = false; this->m_hasRsqrtd = this->m_hasRcpd = false; this->m_hasVecPrefetch = false; CPUfromISA = CPU_KNL; } #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ else if (!strcasecmp(isa, ""avx512skx-i32x16"")) { this->m_isa = Target::SKX_AVX512; this->m_nativeVectorWidth = 16; this->m_nativeVectorAlignment = 64; this->m_dataTypeWidth = 32; this->m_vectorWidth = 16; this->m_maskingIsFree = true; this->m_maskBitCount = 8; this->m_hasHalf = true; this->m_hasRand = true; this->m_hasGather = this->m_hasScatter = true; this->m_hasTranscendentals = false; // For MIC it is set to true due to performance reasons. The option should be tested. this->m_hasTrigonometry = false; this->m_hasRsqrtd = this->m_hasRcpd = false; this->m_hasVecPrefetch = false; CPUfromISA = CPU_SKX; } #endif #ifdef ISPC_ARM_ENABLED else if (!strcasecmp(isa, ""neon-i8x16"")) { this->m_isa = Target::NEON8; this->m_nativeVectorWidth = 16; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 8; this->m_vectorWidth = 16; this->m_attributes = ""+neon,+fp16""; this->m_hasHalf = true; // ?? this->m_maskingIsFree = false; this->m_maskBitCount = 8; } else if (!strcasecmp(isa, ""neon-i16x8"")) { this->m_isa = Target::NEON16; this->m_nativeVectorWidth = 8; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 16; this->m_vectorWidth = 8; this->m_attributes = ""+neon,+fp16""; this->m_hasHalf = true; // ?? this->m_maskingIsFree = false; this->m_maskBitCount = 16; } else if (!strcasecmp(isa, ""neon"") || !strcasecmp(isa, ""neon-i32x4"")) { this->m_isa = Target::NEON32; this->m_nativeVectorWidth = 4; this->m_nativeVectorAlignment = 16; this->m_dataTypeWidth = 32; this->m_vectorWidth = 4; this->m_attributes = ""+neon,+fp16""; this->m_hasHalf = true; // ?? this->m_maskingIsFree = false; this->m_maskBitCount = 32; } #endif #ifdef ISPC_NVPTX_ENABLED else if (!strcasecmp(isa, ""nvptx"")) { this->m_isa = Target::NVPTX; this->m_cpu = ""sm_35""; this->m_nativeVectorWidth = 32; this->m_nativeVectorAlignment = 32; this->m_vectorWidth = 1; this->m_hasHalf = true; this->m_maskingIsFree = true; this->m_maskBitCount = 1; this->m_hasTranscendentals = true; this->m_hasTrigonometry = true; this->m_hasGather = this->m_hasScatter = false; CPUfromISA = CPU_SM35; } #endif /* ISPC_NVPTX_ENABLED */ else { Error(SourcePos(), ""Target \\""%s\\"" is unknown. Choices are: %s."", isa, SupportedTargets()); error = true; } #if defined(ISPC_ARM_ENABLED) && !defined(__arm__) if ((CPUID == CPU_None) && !strncmp(isa, ""neon"", 4)) CPUID = CPU_CortexA9; #endif if (CPUID == CPU_None) { #ifndef ISPC_ARM_ENABLED if (isa == NULL) { #endif std::string hostCPU = llvm::sys::getHostCPUName(); if (hostCPU.size() > 0) cpu = strdup(hostCPU.c_str()); else { Warning(SourcePos(), ""Unable to determine host CPU!\\n""); cpu = a.GetDefaultNameFromType(CPU_Generic).c_str(); } #ifndef ISPC_ARM_ENABLED } else { cpu = a.GetDefaultNameFromType(CPUfromISA).c_str(); } #endif } else { if ((CPUfromISA != CPU_None) && !a.BackwardCompatible(CPUID, CPUfromISA)) { Error(SourcePos(), ""The requested CPU is incompatible"" "" with the CPU %s needs: %s vs. %s!\\n"", isa, cpu, a.GetDefaultNameFromType(CPUfromISA).c_str()); return; } cpu = a.GetDefaultNameFromType(CPUID).c_str(); } this->m_cpu = cpu; if (!error) { // Create TargetMachine std::string triple = GetTripleString(); #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_8 llvm::Reloc::Model relocModel = m_generatePIC ? llvm::Reloc::PIC_ : llvm::Reloc::Default; #else llvm::Optional relocModel; if (m_generatePIC) { relocModel = llvm::Reloc::PIC_; } #endif std::string featuresString = m_attributes; llvm::TargetOptions options; #ifdef ISPC_ARM_ENABLED if (m_isa == Target::NEON8 || m_isa == Target::NEON16 || m_isa == Target::NEON32) options.FloatABIType = llvm::FloatABI::Hard; #endif if (g->opt.disableFMA == false) options.AllowFPOpFusion = llvm::FPOpFusion::Fast; #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 if (g->NoOmitFramePointer) options.NoFramePointerElim = true; #ifdef ISPC_IS_WINDOWS if (strcmp(""x86"", arch) == 0) { // Workaround for issue #503 (LLVM issue 14646). // It's Win32 specific. options.NoFramePointerElim = true; } #endif #endif m_targetMachine = m_target->createTargetMachine(triple, m_cpu, featuresString, options, relocModel); Assert(m_targetMachine != NULL); // Set Optimization level for llvm codegen based on Optimization level // requested by user via ISPC Optimization Flag. Mapping is : // ISPC O0 -> Codegen O0 // ISPC O1,O2,O3,default -> Codegen O3 llvm::CodeGenOpt::Level cOptLevel = llvm::CodeGenOpt::Level::Aggressive; switch (g->codegenOptLevel) { case Globals::CodegenOptLevel::None: cOptLevel = llvm::CodeGenOpt::Level::None; break; case Globals::CodegenOptLevel::Aggressive: cOptLevel = llvm::CodeGenOpt::Level::Aggressive; break; } m_targetMachine->setOptLevel(cOptLevel); #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 m_targetMachine->setAsmVerbosityDefault(true); #else /* LLVM 3.7+ */ m_targetMachine->Options.MCOptions.AsmVerbose = true; #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_5 // Change default version of generated DWARF. if (g->generateDWARFVersion != 0) { m_targetMachine->Options.MCOptions.DwarfVersion = g->generateDWARFVersion; } #endif // Initialize TargetData/DataLayout in 3 steps. // 1. Get default data layout first std::string dl_string; #if ISPC_LLVM_VERSION == ISPC_LLVM_3_6 dl_string = m_targetMachine->getSubtargetImpl()->getDataLayout()->getStringRepresentation(); #elif ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ dl_string = m_targetMachine->createDataLayout().getStringRepresentation(); #else // LLVM 3.5- or LLVM 3.7 dl_string = m_targetMachine->getDataLayout()->getStringRepresentation(); #endif // 2. Adjust for generic if (m_isa == Target::GENERIC) { // <16 x i1> vectors only need 16 bit / 2 byte alignment, so add // that to the regular datalayout string for IA.. // For generic-4 target we need to treat <4 x i1> as 128 bit value // in terms of required memory storage and alignment, as this is // translated to __m128 type. dl_string = ""e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"" ""i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-"" ""f80:128:128-n8:16:32:64-S128-v16:16:16-v32:32:32-v4:128:128""; } #ifdef ISPC_NVPTX_ENABLED else if (m_isa == Target::NVPTX) { dl_string = ""e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:"" ""32-v64:64:64-v128:128:128-n16:32:64""; } #endif // 3. Finally set member data m_dataLayout = new llvm::DataLayout(dl_string); // Set is32Bit // This indicates if we are compiling for 32 bit platform // and can assume 32 bit runtime. // FIXME: all generic targets are handled as 64 bit, which is incorrect. this->m_is32Bit = (getDataLayout()->getPointerSize() == 4); #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_3 // This is LLVM 3.3+ feature. // Initialize target-specific ""target-feature"" attribute. if (!m_attributes.empty()) { llvm::AttrBuilder attrBuilder; #ifdef ISPC_NVPTX_ENABLED if (m_isa != Target::NVPTX) #endif attrBuilder.addAttribute(""target-cpu"", this->m_cpu); attrBuilder.addAttribute(""target-features"", this->m_attributes); #if ISPC_LLVM_VERSION <= ISPC_LLVM_4_0 this->m_tf_attributes = new llvm::AttributeSet( llvm::AttributeSet::get(*g->ctx, llvm::AttributeSet::FunctionIndex, attrBuilder)); #else // LLVM 5.0+ this->m_tf_attributes = new llvm::AttrBuilder(attrBuilder); #endif } #endif Assert(this->m_vectorWidth <= ISPC_MAX_NVEC); } m_valid = !error; if (printTarget) { printf(""Target Triple: %s\\n"", m_targetMachine->getTargetTriple().str().c_str()); printf(""Target CPU: %s\\n"", m_targetMachine->getTargetCPU().str().c_str()); printf(""Target Feature String: %s\\n"", m_targetMachine->getTargetFeatureString().str().c_str()); } return; } std::string Target::SupportedCPUs() { AllCPUs a; return a.HumanReadableListOfNames(); } const char *Target::SupportedArchs() { return #ifdef ISPC_ARM_ENABLED ""arm, "" #endif ""x86, x86-64""; } const char *Target::SupportedTargets() { return ""host, sse2-i32x4, sse2-i32x8, "" ""sse4-i32x4, sse4-i32x8, sse4-i16x8, sse4-i8x16, "" ""avx1-i32x4, "" ""avx1-i32x8, avx1-i32x16, avx1-i64x4, "" ""avx1.1-i32x8, avx1.1-i32x16, avx1.1-i64x4, "" ""avx2-i32x8, avx2-i32x16, avx2-i64x4, "" #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ ""avx512knl-i32x16, "" #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ ""avx512skx-i32x16, "" #endif ""generic-x1, generic-x4, generic-x8, generic-x16, "" ""generic-x32, generic-x64, *-generic-x16"" #ifdef ISPC_ARM_ENABLED "", neon-i8x16, neon-i16x8, neon-i32x4"" #endif #ifdef ISPC_NVPTX_ENABLED "", nvptx"" #endif ; } std::string Target::GetTripleString() const { llvm::Triple triple; #ifdef ISPC_ARM_ENABLED if (m_arch == ""arm"") { triple.setTriple(""armv7-eabi""); } else #endif { // Start with the host triple as the default triple.setTriple(llvm::sys::getDefaultTargetTriple()); // And override the arch in the host triple based on what the user // specified. Here we need to deal with the fact that LLVM uses one // naming convention for targets TargetRegistry, but wants some // slightly different ones for the triple. TODO: is there a way to // have it do this remapping, which would presumably be a bit less // error prone? if (m_arch == ""x86"") triple.setArchName(""i386""); else if (m_arch == ""x86-64"") triple.setArchName(""x86_64""); #ifdef ISPC_NVPTX_ENABLED else if (m_arch == ""nvptx64"") triple = llvm::Triple(""nvptx64"", ""nvidia"", ""cuda""); #endif /* ISPC_NVPTX_ENABLED */ else triple.setArchName(m_arch); } return triple.str(); } // This function returns string representation of ISA for the purpose of // mangling. And may return any unique string, preferably short, like // sse4, avx and etc. const char *Target::ISAToString(ISA isa) { switch (isa) { #ifdef ISPC_ARM_ENABLED case Target::NEON8: return ""neon-8""; case Target::NEON16: return ""neon-16""; case Target::NEON32: return ""neon-32""; #endif case Target::SSE2: return ""sse2""; case Target::SSE4: return ""sse4""; case Target::AVX: return ""avx""; case Target::AVX11: return ""avx11""; case Target::AVX2: return ""avx2""; #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ case Target::KNL_AVX512: return ""avx512knl""; #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ case Target::SKX_AVX512: return ""avx512skx""; #endif case Target::GENERIC: return ""generic""; #ifdef ISPC_NVPTX_ENABLED case Target::NVPTX: return ""nvptx""; #endif /* ISPC_NVPTX_ENABLED */ default: FATAL(""Unhandled target in ISAToString()""); } return """"; } const char *Target::GetISAString() const { return ISAToString(m_isa); } // This function returns string representation of default target corresponding // to ISA. I.e. for SSE4 it's sse4-i32x4, for AVX11 it's avx1.1-i32x8. This // string may be used to initialize Target. const char *Target::ISAToTargetString(ISA isa) { switch (isa) { #ifdef ISPC_ARM_ENABLED case Target::NEON8: return ""neon-8""; case Target::NEON16: return ""neon-16""; case Target::NEON32: return ""neon-32""; #endif case Target::SSE2: return ""sse2-i32x4""; case Target::SSE4: return ""sse4-i32x4""; case Target::AVX: return ""avx1-i32x8""; case Target::AVX11: return ""avx1.1-i32x8""; case Target::AVX2: return ""avx2-i32x8""; #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_7 // LLVM 3.7+ case Target::KNL_AVX512: return ""avx512knl-i32x16""; #endif #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+ case Target::SKX_AVX512: return ""avx512skx-i32x16""; #endif case Target::GENERIC: return ""generic-4""; #ifdef ISPC_NVPTX_ENABLED case Target::NVPTX: return ""nvptx""; #endif /* ISPC_NVPTX_ENABLED */ default: FATAL(""Unhandled target in ISAToTargetString()""); } return """"; } const char *Target::GetISATargetString() const { return ISAToString(m_isa); } static bool lGenericTypeLayoutIndeterminate(llvm::Type *type) { if (type->isFloatingPointTy() || type->isX86_MMXTy() || type->isVoidTy() || type->isIntegerTy() || type->isLabelTy() || type->isMetadataTy()) return false; if (type == LLVMTypes::BoolVectorType || type == LLVMTypes::MaskType || type == LLVMTypes::Int1VectorType) return true; llvm::ArrayType *at = llvm::dyn_cast(type); if (at != NULL) return lGenericTypeLayoutIndeterminate(at->getElementType()); llvm::PointerType *pt = llvm::dyn_cast(type); if (pt != NULL) return false; llvm::StructType *st = llvm::dyn_cast(type); if (st != NULL) { for (int i = 0; i < (int)st->getNumElements(); ++i) if (lGenericTypeLayoutIndeterminate(st->getElementType(i))) return true; return false; } Assert(llvm::isa(type)); return true; } llvm::Value *Target::SizeOf(llvm::Type *type, llvm::BasicBlock *insertAtEnd) { if (m_isa == Target::GENERIC && lGenericTypeLayoutIndeterminate(type)) { llvm::Value *index[1] = {LLVMInt32(1)}; llvm::PointerType *ptrType = llvm::PointerType::get(type, 0); llvm::Value *voidPtr = llvm::ConstantPointerNull::get(ptrType); llvm::ArrayRef arrayRef(&index[0], &index[1]); #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 llvm::Instruction *gep = llvm::GetElementPtrInst::Create(voidPtr, arrayRef, ""sizeof_gep"", insertAtEnd); #else /* LLVM 3.7+ */ llvm::Instruction *gep = llvm::GetElementPtrInst::Create(PTYPE(voidPtr), voidPtr, arrayRef, ""sizeof_gep"", insertAtEnd); #endif if (m_is32Bit || g->opt.force32BitAddressing) return new llvm::PtrToIntInst(gep, LLVMTypes::Int32Type, ""sizeof_int"", insertAtEnd); else return new llvm::PtrToIntInst(gep, LLVMTypes::Int64Type, ""sizeof_int"", insertAtEnd); } uint64_t byteSize = getDataLayout()->getTypeStoreSize(type); if (m_is32Bit || g->opt.force32BitAddressing) return LLVMInt32((int32_t)byteSize); else return LLVMInt64(byteSize); } llvm::Value *Target::StructOffset(llvm::Type *type, int element, llvm::BasicBlock *insertAtEnd) { if (m_isa == Target::GENERIC && lGenericTypeLayoutIndeterminate(type) == true) { llvm::Value *indices[2] = {LLVMInt32(0), LLVMInt32(element)}; llvm::PointerType *ptrType = llvm::PointerType::get(type, 0); llvm::Value *voidPtr = llvm::ConstantPointerNull::get(ptrType); llvm::ArrayRef arrayRef(&indices[0], &indices[2]); #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 llvm::Instruction *gep = llvm::GetElementPtrInst::Create(voidPtr, arrayRef, ""offset_gep"", insertAtEnd); #else /* LLVM 3.7+ */ llvm::Instruction *gep = llvm::GetElementPtrInst::Create(PTYPE(voidPtr), voidPtr, arrayRef, ""offset_gep"", insertAtEnd); #endif if (m_is32Bit || g->opt.force32BitAddressing) return new llvm::PtrToIntInst(gep, LLVMTypes::Int32Type, ""offset_int"", insertAtEnd); else return new llvm::PtrToIntInst(gep, LLVMTypes::Int64Type, ""offset_int"", insertAtEnd); } llvm::StructType *structType = llvm::dyn_cast(type); if (structType == NULL || structType->isSized() == false) { Assert(m->errorCount > 0); return NULL; } const llvm::StructLayout *sl = getDataLayout()->getStructLayout(structType); Assert(sl != NULL); uint64_t offset = sl->getElementOffset(element); if (m_is32Bit || g->opt.force32BitAddressing) return LLVMInt32((int32_t)offset); else return LLVMInt64(offset); } void Target::markFuncWithTargetAttr(llvm::Function *func) { #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_3 if (m_tf_attributes) { #if ISPC_LLVM_VERSION <= ISPC_LLVM_4_0 func->addAttributes(llvm::AttributeSet::FunctionIndex, *m_tf_attributes); #else // LLVM 5.0+ func->addAttributes(llvm::AttributeList::FunctionIndex, *m_tf_attributes); #endif } #endif } /////////////////////////////////////////////////////////////////////////// // Opt Opt::Opt() { level = 1; fastMath = false; fastMaskedVload = false; force32BitAddressing = true; unrollLoops = true; disableAsserts = false; disableFMA = false; forceAlignedMemory = false; disableMaskAllOnOptimizations = false; disableHandlePseudoMemoryOps = false; disableBlendedMaskedStores = false; disableCoherentControlFlow = false; disableUniformControlFlow = false; disableGatherScatterOptimizations = false; disableMaskedStoreToStore = false; disableGatherScatterFlattening = false; disableUniformMemoryOptimizations = false; disableCoalescing = false; } /////////////////////////////////////////////////////////////////////////// // Globals Globals::Globals() { mathLib = Globals::Math_ISPC; codegenOptLevel = Globals::Aggressive; includeStdlib = true; runCPP = true; debugPrint = false; printTarget = false; NoOmitFramePointer = false; debugIR = -1; disableWarnings = false; warningsAsErrors = false; quiet = false; forceColoredOutput = false; disableLineWrap = false; emitPerfWarnings = true; emitInstrumentation = false; generateDebuggingSymbols = false; #if ISPC_LLVM_VERSION >= ISPC_LLVM_3_5 generateDWARFVersion = 3; #endif enableFuzzTest = false; fuzzTestSeed = -1; mangleFunctionsWithTarget = false; ctx = new llvm::LLVMContext; #ifdef ISPC_IS_WINDOWS _getcwd(currentDirectory, sizeof(currentDirectory)); #else if (getcwd(currentDirectory, sizeof(currentDirectory)) == NULL) FATAL(""Current directory path too long!""); #endif forceAlignment = -1; dllExport = false; } /////////////////////////////////////////////////////////////////////////// // SourcePos SourcePos::SourcePos(const char *n, int fl, int fc, int ll, int lc) { name = n; if (name == NULL) { if (m != NULL) name = m->module->getModuleIdentifier().c_str(); else name = ""(unknown)""; } first_line = fl; first_column = fc; last_line = ll != 0 ? ll : fl; last_column = lc != 0 ? lc : fc; } #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 llvm::DIFile #else /* LLVM 3.7+ */ llvm::DIFile * // llvm::MDFile* #endif SourcePos::GetDIFile() const { std::string directory, filename; GetDirectoryAndFileName(g->currentDirectory, name, &directory, &filename); #if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 llvm::DIFile ret = m->diBuilder->createFile(filename, directory); Assert(ret.Verify()); #else /* LLVM 3.7+ */ llvm::DIFile *ret = m->diBuilder->createFile(filename, directory); #endif return ret; } void SourcePos::Print() const { printf("" @ [%s:%d.%d - %d.%d] "", name, first_line, first_column, last_line, last_column); } bool SourcePos::operator==(const SourcePos &p2) const { return (!strcmp(name, p2.name) && first_line == p2.first_line && first_column == p2.first_column && last_line == p2.last_line && last_column == p2.last_column); } SourcePos Union(const SourcePos &p1, const SourcePos &p2) { if (strcmp(p1.name, p2.name) != 0) return p1; SourcePos ret; ret.name = p1.name; ret.first_line = std::min(p1.first_line, p2.first_line); ret.first_column = std::min(p1.first_column, p2.first_column); ret.last_line = std::max(p1.last_line, p2.last_line); ret.last_column = std::max(p1.last_column, p2.last_column); return ret; } ",16237,True,2794.603434158063,median "--- title: 章 7. 多媒體 part: 部 II. 一般作業 prev: books/handbook/desktop next: books/handbook/kernelconfig showBookMenu: true weight: 10 path: ""/books/handbook/"" --- [[multimedia]] = 多媒體 :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 7 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/multimedia/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[multimedia-synopsis]] == 概述 FreeBSD 廣泛地支援各種音效卡, 讓使用者可以享受來自電腦上的高傳真音質(Hi-Fi), 此外還包括了錄製和播放 MPEG Audio Layer 3 (MP3)、 Waveform Audio File (WAV)、Ogg Vorbis 以及其他許多種格式聲音的能力。同時 FreeBSD Port 套件集也包含了許多可讓您可以錄音、編修音效以及控制 MIDI 配備的應用程式。 FreeBSD 也能播放一般的視訊檔和 DVD。 FreeBSD Port 套件集中含有可編碼、轉換以及播放格種影像媒體的應用程式。 本章會說明如何設定 FreeBSD 上的音效卡、影像播放器、電視卡及掃描器。同時會說明有那些應用程式可以使用這些裝置。 讀完這章,您將了解: * 設定 FreeBSD 上的音效卡。 * 音效設定疑難排解。 * 播放、錄製 MP3 及其他聲音檔案格式。 * FreeBSD 系統播放影像的準備工具。 * 播放 DVD 的 [.filename]#.mpg# 及 [.filename]#.avi# 檔。 * 擷取(Rip) CD 和 DVD的內容至檔案。 * 設定電視卡。 * 在 FreeBSD 安裝 MythTV * 設定影像掃描機。 * 設定藍芽耳機。 在開始閱讀這章之前,您需要: * 知道如何安裝應用程式如 crossref:ports[ports,安裝應用程式:套件與 Port] 所敘述。 [[sound-setup]] == 設定音效卡 開始設定之前,必須先知道你的音效卡型號、晶片為何。 FreeBSD 支援許多種音效卡,請檢查支援的音效硬體表 https://www.FreeBSD.org/releases/12.0r/hardware/[Hardware Notes],以確認你的音效卡是否支援以及如何在 FreeBSD 上驅動。 要使用音效裝置,必須要載入正確的驅動程式才行。最簡單方式就是以 man:kldload[8] 來載入核心模組。以下範例示範載入 Intel 規格內建的音效晶片驅動程式: [source,shell] .... # kldload snd_hda .... 要開機時自動載入驅動程式,需將驅動程式加到 [.filename]#/boot/loader.conf# 檔,以此驅動程式為例: [.programlisting] .... snd_hda_load=""YES"" .... 其他可用的音效卡模組清單列於 [.filename]#/boot/defaults/loader.conf#。當不確認要使用何種驅動程式時,可載入 [.filename]#snd_driver# 模組: [source,shell] .... # kldload snd_driver .... 它是 metadriver 會載入所有最通用的音效驅動程式並且用來加速尋找正確的驅動程式。也可以把 metadriver 加入 [.filename]#/boot/loader.conf# 檔來載入所有音效驅動程式。 要知道載入 [.filename]#snd_driver# metadriver 後使用了那個音效卡驅動程式,請輸入 `cat /dev/sndstat`。 === 設定自訂核心支援音效 This section is for users who prefer to statically compile in support for the sound card in a custom kernel. For more information about recompiling a kernel, refer to crossref:kernelconfig[kernelconfig,設定 FreeBSD 核心]. When using a custom kernel to provide sound support, make sure that the audio framework driver exists in the custom kernel configuration file: [.programlisting] .... device sound .... Next, add support for the sound card. To continue the example of the built-in audio chipset based on the Intel specification from the previous section, use the following line in the custom kernel configuration file: [.programlisting] .... device snd_hda .... Be sure to read the manual page of the driver for the device name to use for the driver. Non-PnP ISA sound cards may require the IRQ and I/O port settings of the card to be added to [.filename]#/boot/device.hints#. During the boot process, man:loader[8] reads this file and passes the settings to the kernel. For example, an old Creative SoundBlaster(TM) 16 ISA non-PnP card will use the man:snd_sbc[4] driver in conjunction with `snd_sb16`. For this card, the following lines must be added to the kernel configuration file: [.programlisting] .... device snd_sbc device snd_sb16 .... If the card uses the `0x220` I/O port and IRQ `5`, these lines must also be added to [.filename]#/boot/device.hints#: [.programlisting] .... hint.sbc.0.at=""isa"" hint.sbc.0.port=""0x220"" hint.sbc.0.irq=""5"" hint.sbc.0.drq=""1"" hint.sbc.0.flags=""0x15"" .... The syntax used in [.filename]#/boot/device.hints# is described in man:sound[4] and the manual page for the driver of the sound card. The settings shown above are the defaults. In some cases, the IRQ or other settings may need to be changed to match the card. Refer to man:snd_sbc[4] for more information about this card. [[sound-testing]] === 測試音效 After loading the required module or rebooting into the custom kernel, the sound card should be detected. To confirm, run `dmesg | grep pcm`. This example is from a system with a built-in Conexant CX20590 chipset: [source,shell] .... pcm0: at nid 5 on hdaa0 pcm1: at nid 6 on hdaa0 pcm2: at nid 31,25 and 35,27 on hdaa1 .... The status of the sound card may also be checked using this command: [source,shell] .... # cat /dev/sndstat FreeBSD Audio Driver (newpcm: 64bit 2009061500/amd64) Installed devices: pcm0: (play) pcm1: (play) pcm2: (play/rec) default .... The output will vary depending upon the sound card. If no [.filename]#pcm# devices are listed, double-check that the correct device driver was loaded or compiled into the kernel. The next section lists some common problems and their solutions. If all goes well, the sound card should now work in FreeBSD. If the CD or DVD drive is properly connected to the sound card, one can insert an audio CD in the drive and play it with man:cdcontrol[1]: [source,shell] .... % cdcontrol -f /dev/acd0 play 1 .... [WARNING] ==== Audio CDs have specialized encodings which means that they should not be mounted using man:mount[8]. ==== Various applications, such as package:audio/workman[], provide a friendlier interface. The package:audio/mpg123[] port can be installed to listen to MP3 audio files. Another quick way to test the card is to send data to [.filename]#/dev/dsp#: [source,shell] .... % cat filename > /dev/dsp .... where [.filename]#filename# can be any type of file. This command should produce some noise, confirming that the sound card is working. [NOTE] ==== The [.filename]#/dev/dsp*# device nodes will be created automatically as needed. When not in use, they do not exist and will not appear in the output of man:ls[1]. ==== [[bluetooth-headset]] === 設定藍芽音效裝置 Connecting to a Bluetooth device is out of scope for this chapter. Refer to crossref:advanced-networking[network-bluetooth,藍牙] for more information. To get Bluetooth sound sink working with FreeBSD's sound system, users have to install package:audio/virtual_oss[] first: [source,shell] .... # pkg install virtual_oss .... package:audio/virtual_oss[] requires `cuse` to be loaded into the kernel: [source,shell] .... # kldload cuse .... To load `cuse` during system startup, run this command: [source,shell] .... # sysrc -f /boot/loader.conf cuse_load=yes .... To use headphones as a sound sink with package:audio/virtual_oss[], users need to create a virtual device after connecting to a Bluetooth audio device: [source,shell] .... # virtual_oss -C 2 -c 2 -r 48000 -b 16 -s 768 -R /dev/null -P /dev/bluetooth/headphones -d dsp .... [NOTE] ==== _headphones_ in this example is a hostname from [.filename]#/etc/bluetooth/hosts#. `BT_ADDR` could be used instead. ==== 請參考 man:virtual_oss[8] 取得更多資訊。 [[troubleshooting]] === 疑難排解音效 <> lists some common error messages and their solutions: [[multimedia-sound-common-error-messages]] .常見錯誤訊息 [cols=""1,1"", frame=""none"", options=""header""] |=== | 錯誤 | 解決方式 |`sb_dspwr(XX) timed out` | The I/O port is not set correctly. |`bad irq XX` | The IRQ is set incorrectly. Make sure that the set IRQ and the sound IRQ are the same. |`xxx: gus pcm not attached, out of memory` | There is not enough available memory to use the device. |`xxx: can't open /dev/dsp!` | Type `fstat \\| grep dsp` to check if another application is holding the device open. Noteworthy troublemakers are esound and KDE's sound support. |=== Modern graphics cards often come with their own sound driver for use with HDMI. This sound device is sometimes enumerated before the sound card meaning that the sound card will not be used as the default playback device. To check if this is the case, run dmesg and look for `pcm`. The output looks something like this: [.programlisting] .... ... hdac0: HDA Driver Revision: 20100226_0142 hdac1: HDA Driver Revision: 20100226_0142 hdac0: HDA Codec #0: NVidia (Unknown) hdac0: HDA Codec #1: NVidia (Unknown) hdac0: HDA Codec #2: NVidia (Unknown) hdac0: HDA Codec #3: NVidia (Unknown) pcm0: at cad 0 nid 1 on hdac0 pcm1: at cad 1 nid 1 on hdac0 pcm2: at cad 2 nid 1 on hdac0 pcm3: at cad 3 nid 1 on hdac0 hdac1: HDA Codec #2: Realtek ALC889 pcm4: at cad 2 nid 1 on hdac1 pcm5: at cad 2 nid 1 on hdac1 pcm6: at cad 2 nid 1 on hdac1 pcm7: at cad 2 nid 1 on hdac1 ... .... In this example, the graphics card (`NVidia`) has been enumerated before the sound card (`Realtek ALC889`). To use the sound card as the default playback device, change `hw.snd.default_unit` to the unit that should be used for playback: [source,shell] .... # sysctl hw.snd.default_unit=n .... where `n` is the number of the sound device to use. In this example, it should be `4`. Make this change permanent by adding the following line to [.filename]#/etc/sysctl.conf#: [.programlisting] .... hw.snd.default_unit=4 .... [[sound-multiple-sources]] === 使用多個音效來源 It is often desirable to have multiple sources of sound that are able to play simultaneously. FreeBSD uses ""Virtual Sound Channels"" to multiplex the sound card's playback by mixing sound in the kernel. Three man:sysctl[8] knobs are available for configuring virtual channels: [source,shell] .... # sysctl dev.pcm.0.play.vchans=4 # sysctl dev.pcm.0.rec.vchans=4 # sysctl hw.snd.maxautovchans=4 .... This example allocates four virtual channels, which is a practical number for everyday use. Both `dev.pcm.0.play.vchans=4` and `dev.pcm.0.rec.vchans=4` are configurable after a device has been attached and represent the number of virtual channels [.filename]#pcm0# has for playback and recording. Since the [.filename]#pcm# module can be loaded independently of the hardware drivers, `hw.snd.maxautovchans` indicates how many virtual channels will be given to an audio device when it is attached. Refer to man:pcm[4] for more information. [NOTE] ==== The number of virtual channels for a device cannot be changed while it is in use. First, close any programs using the device, such as music players or sound daemons. ==== The correct [.filename]#pcm# device will automatically be allocated transparently to a program that requests [.filename]#/dev/dsp0#. === 設定混音器頻道的預設值 The default values for the different mixer channels are hardcoded in the source code of the man:pcm[4] driver. While sound card mixer levels can be changed using man:mixer[8] or third-party applications and daemons, this is not a permanent solution. To instead set default mixer values at the driver level, define the appropriate values in [.filename]#/boot/device.hints#, as seen in this example: [.programlisting] .... hint.pcm.0.vol=""50"" .... This will set the volume channel to a default value of `50` when the man:pcm[4] module is loaded. [[sound-mp3]] == MP3 音樂 This section describes some MP3 players available for FreeBSD, how to rip audio CD tracks, and how to encode and decode MP3s. [[mp3-players]] === MP3 播放器 A popular graphical MP3 player is Audacious. It supports Winamp skins and additional plugins. The interface is intuitive, with a playlist, graphic equalizer, and more. Those familiar with Winamp will find Audacious simple to use. On FreeBSD, Audacious can be installed from the package:multimedia/audacious[] port or package. Audacious is a descendant of XMMS. The package:audio/mpg123[] package or port provides an alternative, command-line MP3 player. Once installed, specify the MP3 file to play on the command line. If the system has multiple audio devices, the sound device can also be specified: [source,shell] .... # mpg123 -a /dev/dsp1.0 Foobar-GreatestHits.mp3 High Performance MPEG 1.0/2.0/2.5 Audio Player for Layers 1, 2 and 3 version 1.18.1; written and copyright by Michael Hipp and others free software (LGPL) without any warranty but with best wishes Playing MPEG stream from Foobar-GreatestHits.mp3 ... MPEG 1.0 layer III, 128 kbit/s, 44100 Hz joint-stereo .... Additional MP3 players are available in the FreeBSD Ports Collection. [[rip-cd]] === 擷取 CD 音軌 Before encoding a CD or CD track to MP3, the audio data on the CD must be ripped to the hard drive. This is done by copying the raw CD Digital Audio (CDDA) data to WAV files. The `cdda2wav` tool, which is installed with the package:sysutils/cdrtools[] suite, can be used to rip audio information from CDs. With the audio CD in the drive, the following command can be issued as `root` to rip an entire CD into individual, per track, WAV files: [source,shell] .... # cdda2wav -D 0,1,0 -B .... In this example, the `-D _0,1,0_` indicates the SCSI device [.filename]#0,1,0# containing the CD to rip. Use `cdrecord -scanbus` to determine the correct device parameters for the system. To rip individual tracks, use `-t` to specify the track: [source,shell] .... # cdda2wav -D 0,1,0 -t 7 .... To rip a range of tracks, such as track one to seven, specify a range: [source,shell] .... # cdda2wav -D 0,1,0 -t 1+7 .... To rip from an ATAPI (IDE) CDROM drive, specify the device name in place of the SCSI unit numbers. For example, to rip track 7 from an IDE drive: [source,shell] .... # cdda2wav -D /dev/acd0 -t 7 .... Alternately, `dd` can be used to extract audio tracks on ATAPI drives, as described in crossref:disks[duplicating-audiocds,複製音樂 CD]. [[mp3-encoding]] === MP3 編碼與解碼 Lame is a popular MP3 encoder which can be installed from the package:audio/lame[] port. Due to patent issues, a package is not available. The following command will convert the ripped WAV file [.filename]#audio01.wav# to [.filename]#audio01.mp3#: [source,shell] .... # lame -h -b 128 --tt ""Foo Song Title"" --ta ""FooBar Artist"" --tl ""FooBar Album"" \\ --ty ""2014"" --tc ""Ripped and encoded by Foo"" --tg ""Genre"" audio01.wav audio01.mp3 .... The specified 128 kbits is a standard MP3 bitrate while the 160 and 192 bitrates provide higher quality. The higher the bitrate, the larger the size of the resulting MP3. The `-h` turns on the ""higher quality but a little slower"" mode. The options beginning with `--t` indicate ID3 tags, which usually contain song information, to be embedded within the MP3 file. Additional encoding options can be found in the lame manual page. In order to burn an audio CD from MP3s, they must first be converted to a non-compressed file format. XMMS can be used to convert to the WAV format, while mpg123 can be used to convert to the raw Pulse-Code Modulation (PCM) audio data format. To convert [.filename]#audio01.mp3# using mpg123, specify the name of the PCM file: [source,shell] .... # mpg123 -s audio01.mp3 > audio01.pcm .... To use XMMS to convert a MP3 to WAV format, use these steps: [.procedure] ==== *Procedure: Converting to WAV Format in XMMS* . Launch XMMS. . Right-click the window to bring up the XMMS menu. . Select `Preferences` under `Options`. . Change the Output Plugin to ""Disk Writer Plugin"". . Press `Configure`. . Enter or browse to a directory to write the uncompressed files to. . Load the MP3 file into XMMS as usual, with volume at 100% and EQ settings turned off. . Press `Play`. The XMMS will appear as if it is playing the MP3, but no music will be heard. It is actually playing the MP3 to a file. . When finished, be sure to set the default Output Plugin back to what it was before in order to listen to MP3s again. ==== Both the WAV and PCM formats can be used with cdrecord. When using WAV files, there will be a small tick sound at the beginning of each track. This sound is the header of the WAV file. The package:audio/sox[] port or package can be used to remove the header: [source,shell] .... % sox -t wav -r 44100 -s -w -c 2 track.wav track.raw .... Refer to crossref:disks[creating-cds,建立與使用 CD 媒體] for more information on using a CD burner in FreeBSD. [[video-playback]] == 影片播放 Before configuring video playback, determine the model and chipset of the video card. While Xorg supports a wide variety of video cards, not all provide good playback performance. To obtain a list of extensions supported by the Xorg server using the card, run `xdpyinfo` while Xorg is running. It is a good idea to have a short MPEG test file for evaluating various players and options. Since some DVD applications look for DVD media in [.filename]#/dev/dvd# by default, or have this device name hardcoded in them, it might be useful to make a symbolic link to the proper device: [source,shell] .... # ln -sf /dev/cd0 /dev/dvd .... Due to the nature of man:devfs[5], manually created links will not persist after a system reboot. In order to recreate the symbolic link automatically when the system boots, add the following line to [.filename]#/etc/devfs.conf#: [.programlisting] .... link cd0 dvd .... DVD decryption invokes certain functions that require write permission to the DVD device. To enhance the shared memory Xorg interface, it is recommended to increase the values of these man:sysctl[8] variables: [.programlisting] .... kern.ipc.shmmax=67108864 kern.ipc.shmall=32768 .... [[video-interface]] === 偵測影像處理能力 There are several possible ways to display video under Xorg and what works is largely hardware dependent. Each method described below will have varying quality across different hardware. Common video interfaces include: . Xorg: normal output using shared memory. . XVideo: an extension to the Xorg interface which allows video to be directly displayed in drawable objects through a special acceleration. This extension provides good quality playback even on low-end machines. The next section describes how to determine if this extension is running. . SDL: the Simple Directmedia Layer is a porting layer for many operating systems, allowing cross-platform applications to be developed which make efficient use of sound and graphics. SDL provides a low-level abstraction to the hardware which can sometimes be more efficient than the Xorg interface. On FreeBSD, SDL can be installed using the package:devel/sdl20[] package or port. . DGA: the Direct Graphics Access is an Xorg extension which allows a program to bypass the Xorg server and directly alter the framebuffer. Because it relies on a low level memory mapping, programs using it must be run as `root`. The DGA extension can be tested and benchmarked using man:dga[1]. When `dga` is running, it changes the colors of the display whenever a key is pressed. To quit, press kbd:[q]. . SVGAlib: a low level console graphics layer. [[video-interface-xvideo]] ==== XVideo To check whether this extension is running, use `xvinfo`: [source,shell] .... % xvinfo .... XVideo is supported for the card if the result is similar to: [source,shell] .... X-Video Extension version 2.2 screen #0 Adaptor #0: ""Savage Streams Engine"" number of ports: 1 port base: 43 operations supported: PutImage supported visuals: depth 16, visualID 0x22 depth 16, visualID 0x23 number of attributes: 5 ""XV_COLORKEY"" (range 0 to 16777215) client settable attribute client gettable attribute (current value is 2110) ""XV_BRIGHTNESS"" (range -128 to 127) client settable attribute client gettable attribute (current value is 0) ""XV_CONTRAST"" (range 0 to 255) client settable attribute client gettable attribute (current value is 128) ""XV_SATURATION"" (range 0 to 255) client settable attribute client gettable attribute (current value is 128) ""XV_HUE"" (range -180 to 180) client settable attribute client gettable attribute (current value is 0) maximum XvImage size: 1024 x 1024 Number of image formats: 7 id: 0x32595559 (YUY2) guid: 59555932-0000-0010-8000-00aa00389b71 bits per pixel: 16 number of planes: 1 type: YUV (packed) id: 0x32315659 (YV12) guid: 59563132-0000-0010-8000-00aa00389b71 bits per pixel: 12 number of planes: 3 type: YUV (planar) id: 0x30323449 (I420) guid: 49343230-0000-0010-8000-00aa00389b71 bits per pixel: 12 number of planes: 3 type: YUV (planar) id: 0x36315652 (RV16) guid: 52563135-0000-0000-0000-000000000000 bits per pixel: 16 number of planes: 1 type: RGB (packed) depth: 0 red, green, blue masks: 0x1f, 0x3e0, 0x7c00 id: 0x35315652 (RV15) guid: 52563136-0000-0000-0000-000000000000 bits per pixel: 16 number of planes: 1 type: RGB (packed) depth: 0 red, green, blue masks: 0x1f, 0x7e0, 0xf800 id: 0x31313259 (Y211) guid: 59323131-0000-0010-8000-00aa00389b71 bits per pixel: 6 number of planes: 3 type: YUV (packed) id: 0x0 guid: 00000000-0000-0000-0000-000000000000 bits per pixel: 0 number of planes: 0 type: RGB (packed) depth: 1 red, green, blue masks: 0x0, 0x0, 0x0 .... The formats listed, such as YUV2 and YUV12, are not present with every implementation of XVideo and their absence may hinder some players. If the result instead looks like: [source,shell] .... X-Video Extension version 2.2 screen #0 no adaptors present .... XVideo is probably not supported for the card. This means that it will be more difficult for the display to meet the computational demands of rendering video, depending on the video card and processor. [[video-ports]] === 可處理影像的 Port 與套件 This section introduces some of the software available from the FreeBSD Ports Collection which can be used for video playback. [[video-mplayer]] ==== MPlayer 與 MEncoder MPlayer is a command-line video player with an optional graphical interface which aims to provide speed and flexibility. Other graphical front-ends to MPlayer are available from the FreeBSD Ports Collection. MPlayer can be installed using the package:multimedia/mplayer[] package or port. Several compile options are available and a variety of hardware checks occur during the build process. For these reasons, some users prefer to build the port rather than install the package. When compiling the port, the menu options should be reviewed to determine the type of support to compile into the port. If an option is not selected, MPlayer will not be able to display that type of video format. Use the arrow keys and spacebar to select the required formats. When finished, press kbd:[Enter] to continue the port compile and installation. By default, the package or port will build the `mplayer` command line utility and the `gmplayer` graphical utility. To encode videos, compile the package:multimedia/mencoder[] port. Due to licensing restrictions, a package is not available for MEncoder. The first time MPlayer is run, it will create [.filename]#~/.mplayer# in the user's home directory. This subdirectory contains default versions of the user-specific configuration files. This section describes only a few common uses. Refer to mplayer(1) for a complete description of its numerous options. To play the file [.filename]#testfile.avi#, specify the video interfaces with `-vo`, as seen in the following examples: [source,shell] .... % mplayer -vo xv testfile.avi .... [source,shell] .... % mplayer -vo sdl testfile.avi .... [source,shell] .... % mplayer -vo x11 testfile.avi .... [source,shell] .... # mplayer -vo dga testfile.avi .... [source,shell] .... # mplayer -vo 'sdl:dga' testfile.avi .... It is worth trying all of these options, as their relative performance depends on many factors and will vary significantly with hardware. To play a DVD, replace [.filename]#testfile.avi# with `dvd://_N_ -dvd-device _DEVICE_`, where _N_ is the title number to play and _DEVICE_ is the device node for the DVD. For example, to play title 3 from [.filename]#/dev/dvd#: [source,shell] .... # mplayer -vo xv dvd://3 -dvd-device /dev/dvd .... [NOTE] ==== The default DVD device can be defined during the build of the MPlayer port by including the `WITH_DVD_DEVICE=/path/to/desired/device` option. By default, the device is [.filename]#/dev/cd0#. More details can be found in the port's [.filename]#Makefile.options#. ==== To stop, pause, advance, and so on, use a keybinding. To see the list of keybindings, run `mplayer -h` or read mplayer(1). Additional playback options include `-fs -zoom`, which engages fullscreen mode, and `-framedrop`, which helps performance. Each user can add commonly used options to their [.filename]#~/.mplayer/config# like so: [.programlisting] .... vo=xv fs=yes zoom=yes .... `mplayer` can be used to rip a DVD title to a [.filename]#.vob#. To dump the second title from a DVD: [source,shell] .... # mplayer -dumpstream -dumpfile out.vob dvd://2 -dvd-device /dev/dvd .... The output file, [.filename]#out.vob#, will be in MPEG format. Anyone wishing to obtain a high level of expertise with UNIX(TM) video should consult http://www.mplayerhq.hu/DOCS/[mplayerhq.hu/DOCS] as it is technically informative. This documentation should be considered as required reading before submitting any bug reports. Before using `mencoder`, it is a good idea to become familiar with the options described at http://www.mplayerhq.hu/DOCS/HTML/en/mencoder.html[mplayerhq.hu/DOCS/HTML/en/mencoder.html]. There are innumerable ways to improve quality, lower bitrate, and change formats, and some of these options may make the difference between good or bad performance. Improper combinations of command line options can yield output files that are unplayable even by `mplayer`. Here is an example of a simple copy: [source,shell] .... % mencoder input.avi -oac copy -ovc copy -o output.avi .... To rip to a file, use `-dumpfile` with `mplayer`. To convert [.filename]#input.avi# to the MPEG4 codec with MPEG3 audio encoding, first install the package:audio/lame[] port. Due to licensing restrictions, a package is not available. Once installed, type: [source,shell] .... % mencoder input.avi -oac mp3lame -lameopts br=192 \\ -ovc lavc -lavcopts vcodec=mpeg4:vhq -o output.avi .... This will produce output playable by applications such as `mplayer` and `xine`. [.filename]#input.avi# can be replaced with `dvd://1 -dvd-device /dev/dvd` and run as `root` to re-encode a DVD title directly. Since it may take a few tries to get the desired result, it is recommended to instead dump the title to a file and to work on the file. [[video-xine]] ==== xine 影像播放器 xine is a video player with a reusable base library and a modular executable which can be extended with plugins. It can be installed using the package:multimedia/xine[] package or port. In practice, xine requires either a fast CPU with a fast video card, or support for the XVideo extension. The xine video player performs best on XVideo interfaces. By default, the xine player starts a graphical user interface. The menus can then be used to open a specific file. Alternatively, xine may be invoked from the command line by specifying the name of the file to play: [source,shell] .... % xine -g -p mymovie.avi .... Refer to http://www.xine-project.org/faq[ xine-project.org/faq] for more information and troubleshooting tips. [[video-ports-transcode]] ==== Transcode 工具 Transcode provides a suite of tools for re-encoding video and audio files. Transcode can be used to merge video files or repair broken files using command line tools with stdin/stdout stream interfaces. In FreeBSD, Transcode can be installed using the package:multimedia/transcode[] package or port. Many users prefer to compile the port as it provides a menu of compile options for specifying the support and codecs to compile in. If an option is not selected, Transcode will not be able to encode that format. Use the arrow keys and spacebar to select the required formats. When finished, press kbd:[Enter] to continue the port compile and installation. This example demonstrates how to convert a DivX file into a PAL MPEG-1 file (PAL VCD): [source,shell] .... % transcode -i input.avi -V --export_prof vcd-pal -o output_vcd % mplex -f 1 -o output_vcd.mpg output_vcd.m1v output_vcd.mpa .... The resulting MPEG file, [.filename]#output_vcd.mpg#, is ready to be played with MPlayer. The file can be burned on a CD media to create a video CD using a utility such as package:multimedia/vcdimager[] or package:sysutils/cdrdao[]. In addition to the manual page for `transcode`, refer to http://www.transcoding.org/cgi-bin/transcode[transcoding.org/cgi-bin/transcode] for further information and examples. [[tvcard]] == 電視卡 電視卡 (TV card) 可以讓您用電腦來看無線、有線電視節目。許多卡都是透過 RCA 或 S-video 輸入端子來接收視訊,而且有些卡還可接收 FM 廣播的功能。 FreeBSD 可透過 man:bktr[4] 驅動程式,來支援 PCI 介面的電視卡,只要這些卡使用的是 Brooktree Bt848/849/878/879 或 Conexant CN-878/Fusion 878a 視訊擷取晶片。此外,要再確認哪些卡上所附的選台功能是否有支援,可以參考 man:bktr[4] 說明,以查看所支援的硬體清單。 === 載入驅動程式 要用電視卡的話,就要載入 man:bktr[4] 驅動程式,這個可以透過在 [.filename]#/boot/loader.conf# 檔加上下面這一行就可以了: [.programlisting] .... bktr_load=""YES"" .... 或者可以將電視卡支援靜態編譯到自訂的核心當中,若要這麼做則可在自訂核心設定檔加入以下行: [.programlisting] .... device bktr device iicbus device iicbb device smbus .... 之所以要加上這些額外的驅動程式,是因為卡的各組成部分都是透過 I2C 匯流排而相互連接的。接下來,請編譯、安裝新的核心 。 要測試調諧器 (Tuner) 是否被正確的偵測,請先重新啟動系統。電視卡應該會出現在開機訊息檔中,如同此範例: [.programlisting] .... bktr0: mem 0xd7000000-0xd7000fff irq 10 at device 10.0 on pci0 iicbb0: on bti2c0 iicbus0: on iicbb0 master-only iicbus1: on iicbb0 master-only smbus0: on bti2c0 bktr0: Pinnacle/Miro TV, Philips SECAM tuner. .... 該訊息會依硬體不同而有所不同。若必要,可以使用 man:sysctl[8] 系統偵測的參數或者自訂核心設定選項。例如要強制使用 Philips SECAM 調諧器則可加入下列行至自訂核心設定檔: [.programlisting] .... options OVERRIDE_TUNER=6 .... 或使用 man:sysctl[8]: [source,shell] .... # sysctl hw.bt848.tuner=6 .... 請參考 man:bktr[4] 查看 man:sysctl[8] 可用的參數說明及核心選項。 === 好用的應用程式 To use the TV card, install one of the following applications: * package:multimedia/fxtv[] provides TV-in-a-window and image/audio/video capture capabilities. * package:multimedia/xawtv[] is another TV application with similar features. * package:audio/xmradio[] provides an application for using the FM radio tuner of a TV card. More applications are available in the FreeBSD Ports Collection. === 疑難排解 If any problems are encountered with the TV card, check that the video capture chip and the tuner are supported by man:bktr[4] and that the right configuration options were used. For more support or to ask questions about supported TV cards, refer to the http://lists.FreeBSD.org/mailman/listinfo/freebsd-multimedia[freebsd-multimedia] mailing list. [[mythtv]] == MythTV MythTV is a popular, open source Personal Video Recorder (PVR) application. This section demonstrates how to install and setup MythTV on FreeBSD. Refer to http://www.mythtv.org/wiki/[mythtv.org/wiki] for more information on how to use MythTV. MythTV requires a frontend and a backend. These components can either be installed on the same system or on different machines. The frontend can be installed on FreeBSD using the package:multimedia/mythtv-frontend[] package or port. Xorg must also be installed and configured as described in crossref:x11[x11,X Window 系統]. Ideally, this system has a video card that supports X-Video Motion Compensation (XvMC) and, optionally, a Linux Infrared Remote Control (LIRC)-compatible remote. To install both the backend and the frontend on FreeBSD, use the package:multimedia/mythtv[] package or port. A MySQL(TM) database server is also required and should automatically be installed as a dependency. Optionally, this system should have a tuner card and sufficient storage to hold recorded data. === 硬體 MythTV uses Video for Linux (V4L) to access video input devices such as encoders and tuners. In FreeBSD, MythTV works best with USB DVB-S/C/T cards as they are well supported by the package:multimedia/webcamd[] package or port which provides a V4L userland application. Any Digital Video Broadcasting (DVB) card supported by webcamd should work with MythTV. A list of known working cards can be found at https://wiki.freebsd.org/WebcamCompat[wiki.freebsd.org/WebcamCompat]. Drivers are also available for Hauppauge cards in the package:multimedia/pvr250[] and package:multimedia/pvrxxx[] ports, but they provide a non-standard driver interface that does not work with versions of MythTV greater than 0.23. Due to licensing restrictions, no packages are available and these two ports must be compiled. The https://wiki.freebsd.org/HTPC[wiki.freebsd.org/HTPC] page contains a list of all available DVB drivers. === 設定 MythTV 後端 要使用 Binary 套件安裝 MythTV 可: [source,shell] .... # pkg install mythtv .... 或從 Port 套件集安裝: [source,shell] .... # cd /usr/ports/multimedia/mythtv # make install .... Once installed, set up the MythTV database: [source,shell] .... # mysql -uroot -p < /usr/local/shared/mythtv/database/mc.sql .... Then, configure the backend: [source,shell] .... # mythtv-setup .... Finally, start the backend: [source,shell] .... # sysrc mythbackend_enable=yes # service mythbackend start .... [[scanners]] == 影像掃描器 In FreeBSD, access to image scanners is provided by SANE (Scanner Access Now Easy), which is available in the FreeBSD Ports Collection. SANE will also use some FreeBSD device drivers to provide access to the scanner hardware. FreeBSD supports both SCSI and USB scanners. Depending upon the scanner interface, different device drivers are required. Be sure the scanner is supported by SANE prior to performing any configuration. Refer to http://www.sane-project.org/sane-supported-devices.html[ http://www.sane-project.org/sane-supported-devices.html] for more information about supported scanners. This chapter describes how to determine if the scanner has been detected by FreeBSD. It then provides an overview of how to configure and use SANE on a FreeBSD system. [[scanners-kernel-usb]] === 檢查掃描器 The [.filename]#GENERIC# kernel includes the device drivers needed to support USB scanners. Users with a custom kernel should ensure that the following lines are present in the custom kernel configuration file: [.programlisting] .... device usb device uhci device ohci device ehci .... To determine if the USB scanner is detected, plug it in and use `dmesg` to determine whether the scanner appears in the system message buffer. If it does, it should display a message similar to this: [source,shell] .... ugen0.2: at usbus0 .... In this example, an EPSON Perfection(TM) 1650 USB scanner was detected on [.filename]#/dev/ugen0.2#. If the scanner uses a SCSI interface, it is important to know which SCSI controller board it will use. Depending upon the SCSI chipset, a custom kernel configuration file may be needed. The [.filename]#GENERIC# kernel supports the most common SCSI controllers. Refer to [.filename]#/usr/src/sys/conf/NOTES# to determine the correct line to add to a custom kernel configuration file. In addition to the SCSI adapter driver, the following lines are needed in a custom kernel configuration file: [.programlisting] .... device scbus device pass .... Verify that the device is displayed in the system message buffer: [source,shell] .... pass2 at aic0 bus 0 target 2 lun 0 pass2: Fixed Scanner SCSI-2 device pass2: 3.300MB/s transfers .... If the scanner was not powered-on at system boot, it is still possible to manually force detection by performing a SCSI bus scan with `camcontrol`: [source,shell] .... # camcontrol rescan all Re-scan of bus 0 was successful Re-scan of bus 1 was successful Re-scan of bus 2 was successful Re-scan of bus 3 was successful .... The scanner should now appear in the SCSI devices list: [source,shell] .... # camcontrol devlist at scbus0 target 5 lun 0 (pass0,da0) at scbus0 target 6 lun 0 (pass1,da1) at scbus1 target 2 lun 0 (pass3) at scbus2 target 0 lun 0 (pass2,cd0) .... Refer to man:scsi[4] and man:camcontrol[8] for more details about SCSI devices on FreeBSD. === SANE 設定 The SANE system is split in two parts: the backends (package:graphics/sane-backends[]) and the frontends (package:graphics/sane-frontends[] or package:graphics/xsane[]). The backends provide access to the scanner. Refer to http://www.sane-project.org/sane-supported-devices.html[http://www.sane-project.org/sane-supported-devices.html] to determine which backend supports the scanner. The frontends provide the graphical scanning interface. package:graphics/sane-frontends[] installs xscanimage while package:graphics/xsane[] installs xsane. 要由 Binary 套件安裝這兩個部份可: [source,shell] .... # pkg install xsane sane-frontends .... 或由 Port 套件集安裝 [source,shell] .... # cd /usr/ports/graphics/sane-frontends # make install clean # cd /usr/ports/graphics/xsane # make install clean .... After installing the package:graphics/sane-backends[] port or package, use `sane-find-scanner` to check the scanner detection by the SANE system: [source,shell] .... # sane-find-scanner -q found SCSI scanner ""AGFA SNAPSCAN 600 1.10"" at /dev/pass3 .... The output should show the interface type of the scanner and the device node used to attach the scanner to the system. The vendor and the product model may or may not appear. [NOTE] ==== Some USB scanners require firmware to be loaded. Refer to sane-find-scanner(1) and sane(7) for details. ==== Next, check if the scanner will be identified by a scanning frontend. The SANE backends include `scanimage` which can be used to list the devices and perform an image acquisition. Use `-L` to list the scanner devices. The first example is for a SCSI scanner and the second is for a USB scanner: [source,shell] .... # scanimage -L device `snapscan:/dev/pass3' is a AGFA SNAPSCAN 600 flatbed scanner # scanimage -L device 'epson2:libusb:/dev/usb:/dev/ugen0.2' is a Epson GT-8200 flatbed scanner .... In this second example, `'epson2:libusb:/dev/usb:/dev/ugen0.2'` is the backend name (`epson2`) and `/dev/ugen0.2` is the device node used by the scanner. If `scanimage` is unable to identify the scanner, this message will appear: [source,shell] .... # scanimage -L No scanners were identified. If you were expecting something different, check that the scanner is plugged in, turned on and detected by the sane-find-scanner tool (if appropriate). Please read the documentation which came with this software (README, FAQ, manpages). .... If this happens, edit the backend configuration file in [.filename]#/usr/local/etc/sane.d/# and define the scanner device used. For example, if the undetected scanner model is an EPSON Perfection(TM) 1650 and it uses the `epson2` backend, edit [.filename]#/usr/local/etc/sane.d/epson2.conf#. When editing, add a line specifying the interface and the device node used. In this case, add the following line: [.programlisting] .... usb /dev/ugen0.2 .... Save the edits and verify that the scanner is identified with the right backend name and the device node: [source,shell] .... # scanimage -L device 'epson2:libusb:/dev/usb:/dev/ugen0.2' is a Epson GT-8200 flatbed scanner .... Once `scanimage -L` sees the scanner, the configuration is complete and the scanner is now ready to use. While `scanimage` can be used to perform an image acquisition from the command line, it is often preferable to use a graphical interface to perform image scanning. The package:graphics/sane-frontends[] package or port installs a simple but efficient graphical interface, xscanimage. Alternately, xsane, which is installed with the package:graphics/xsane[] package or port, is another popular graphical scanning frontend. It offers advanced features such as various scanning modes, color correction, and batch scans. Both of these applications are usable as a GIMP plugin. === 掃描器權限 In order to have access to the scanner, a user needs read and write permissions to the device node used by the scanner. In the previous example, the USB scanner uses the device node [.filename]#/dev/ugen0.2# which is really a symlink to the real device node [.filename]#/dev/usb/0.2.0#. The symlink and the device node are owned, respectively, by the `wheel` and `operator` groups. While adding the user to these groups will allow access to the scanner, it is considered insecure to add a user to `wheel`. A better solution is to create a group and make the scanner device accessible to members of this group. This example creates a group called `_usb_`: [source,shell] .... # pw groupadd usb .... Then, make the [.filename]#/dev/ugen0.2# symlink and the [.filename]#/dev/usb/0.2.0# device node accessible to the `usb` group with write permissions of `0660` or `0664` by adding the following lines to [.filename]#/etc/devfs.rules#: [.programlisting] .... [system=5] add path ugen0.2 mode 0660 group usb add path usb/0.2.0 mode 0666 group usb .... Finally, add the users to `_usb_` in order to allow access to the scanner: [source,shell] .... # pw groupmod usb -m joe .... For more details refer to man:pw[8]. ",12088,False,2098.3396639519265,median "// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // ""License""); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // = Profiling an Enterprise Application in IDE NetBeans :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: Profiling an Enterprise Application in IDE NetBeans - Apache NetBeans :keywords: Apache NetBeans, Tutorials, Profiling an Enterprise Application in IDE NetBeans IDE NetBeans includes a powerful profiling tool that can provide important information about the runtime behavior of enterprise applications. С помощью средства профилирования можно легко следить за состояниями потоков и получать данные о производительности ЦП и использовании приложением памяти. В этом документе говорится об использовании средства профилирования для получения данных о простых приложениях, которые развернуты на сервере приложений как файлы WAR. В документе показано, как использовать среду IDE, чтобы получить результаты профилирования следующих показателей. * Поведение приложения при выполнении * Время ЦП, используемое методами приложения * Создание объекта При развертывании приложения на локальном зарегистрированном сервере Tomcat, сервере GlassFish или установке JBoss приложение можно профилировать всего лишь несколькими нажатиями кнопок мыши и почти не настраивая. Процесс профилирования проекта очень похож на использование команды ""Выполнить"" в среде IDE. Можно с легкостью начать профилирование проектов приложений или отдельных веб-модулей и модулей EJB, выбрав пункт ""Профиль"" > ""Профилировать главный проект"" главного меню. * Создание примера проекта *Для работы с этим учебным курсом требуется следующее программное обеспечение и ресурсы.* |=== |Программное обеспечение или материал |Требуемая версия |link:https://netbeans.org/downloads/index.html[+IDE NetBeans+] |7.3, 7.4, 8.0, пакет Java EE |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Комплект для разработчика на языке Java (JDK)+] |JDK 7 или 8 |Сервер GlassFish |3.1, 4.0 |=== [NOTE] ==== * При первом использовании профилировщика рекомендуется ознакомиться с разделом link:../java/profiler-intro.html[+Введение в профилирование приложений Java в IDE NetBeans+], который содержит обзор задач отслеживания и профилирования. * Если используется IDE NetBeans 7.2 или более ранняя версия, см. раздел link:../../72/javaee/profiler-javaee.html[+Профилирование корпоративных приложений в IDE NetBeans 7.2+] * В этом документе говорится о профилировании корпоративного приложения, развернутого на сервере GlassFish. Предпочтительная и самая простая настройка профилирования во время разработки корпоративных или веб-приложений — запуск приложения на локальных серверах Tomcat, GlassFish или JBoss. ==== == О профилировании приложений в среде IDE При профилировании корпоративных приложений в большинстве случаев требуется анализировать производительность приложения для получения времени выполнения методов проекта. Это позволяет исправить ошибки приложения и улучшить его производительность. В некоторых случаях требуется также получить данные по использованию памяти для оптимизации сбора мусора. Процесс профилирования корпоративных приложений, модулей EJB и веб-приложений по сути такой же, как выполнение проекта с помощью команды ""Выполнить"". После выбора задачи профилирования и настройки параметров нажмите ""Выполнить"" в диалоговом окне ""Выбрать задачу профилирования"" для запуска сессии профилирования. При запуске сеанса профилирования среда IDE выполняет следующие действия: * компилирует приложение; * запускает целевой сервер в режиме профилирования; * развертывает приложение; * прикрепляется к приложению; * открывает веб-страницу веб-браузера (если это указано в свойствах проекта); * открывает вкладку ""Текущие результаты профилирования"". В зависимости от параметров профилирования среда IDE может немедленно вывести результаты профилирования во вкладке ""Текущие результаты профилирования"". В некоторых случаях, например, при указании профилирования корневых методов, может оказаться необходимым произвести некоторые действия в веб-браузере, прежде чем будут показаны результаты. === Профилирование проектов корпоративных приложений Корпоративное приложение, которое создается в среде IDE, может быть и веб-приложением, которое развертывается на сервере приложений как архивный веб-файл (WAR), и проектом корпоративного приложения, содержащим веб-приложение и дополнительные библиотеки, развернутым на сервере как архивный файл корпоративного приложения (EAR). Если необходимо развернуть приложение как архивный файл EAR, создайте проект корпоративного приложения NetBeans, который содержит подпроекты и библиотеки. Проект корпоративного приложения не содержит ни одного исходного файла, только информацию о сборке и развертывании приложения и о метаданных настроек сервера. Бизнес-логика приложения проекта обычно содержится в модуле EJB, а исходный код уровня представления — в веб-модуле. При наличии всех исходных файлов проекта корпоративного приложения самым лучшим и простым методом профилирования является профилирование всего проекта корпоративного приложения целиком, а не его подпроектов. Это позволяет удостовериться, что весь необходимый код был скомпилирован и развернут, а приложение работает корректно. Чтобы профилировать проект корпоративного приложение, выполните следующие действия: * Если проект является главным проектом, нажмите кнопку ""Профилировать главный проект"" на панели инструментов или выберите ""Профилирование"" > ""Профилировать главный проект"" в главном меню. * Щелкните правой кнопкой мыши проект приложения в окне проектов и выберите ""Профилировать"" из всплывающего меню. При профилировании корпоративного приложения можно увеличить корректность результатов профилирования, указав профилирование корневых методов и используя фильтры инструментирования для ограничения количества классов, которые будут профилированы. Это поможет сократить влияние дополнительного расхода ресурсов процессом профилирования на производительность приложения и увеличит корректность результатов профилирования. При запуске корпоративных приложений, в отличие от веб-приложений, браузер не всегда открывается автоматически. (Это зависит от настройки проекта.) Это означает, что в некоторых случаях понадобится вручную запустить внешний интерфейс веб-приложения и затем вызвать код, такой как бизнес-логика в модуле EJB, из веб-браузера. === Профилирование модуля EJB и подпроектов веб-модулей Сеанс профилирования можно запустить из любого модуля EJB или веб-модуля проекта. В этом случае можно выбрать один из подходов: * *Профилирование модуля EJB.* Если использовать этот подход, возможно, придется вызывать код приложения вручную с веб-браузера или другого клиента, поскольку проекты модулей EJB, как правило, не настроены для открытия веб-браузера. После того, как модуль EJB развернут на сервере, необходимо вызвать его код точно так же, как при отладке или оценке функциональности приложения. Обычно это делается запуском внешнего интерфейса веб-приложения и выполнения действий в веб-браузере. * *Профилирования веб-модуля.* Если использовать этот подход, необходимо скомпилировать и развернуть модуль EJB на сервер до профилирования проекта веб-модуля. Обычно код EJB выполняется в результате некоторых действий пользователя в браузере. Если эти действия выполнены/обработаны кодом веб-приложения, код EJB будет виден в дереве вызовов. == Создание примера проекта В этом документе говорится о профилировании демонстрационного приложения ServletStateless. Приложение ServletStateless — это простое корпоративное веб-приложение, которое включено в среду IDE как демонстрационный проект. Для создания приложения ServletStateless выполните следующие действия: 1. Выберите 'Файл' > 'Создать проект' (Ctrl-Shift-N; ⌘-Shift-N в Mac) в главном меню. 2. В мастере создания проекта выберите категорию ""Примеры > Java EE"". 3. Выберите проект ""Servlet Stateless"". Нажмите кнопку ""Далее"". 4. Укажите местоположение проекта. Нажмите кнопку ""Завершить"". После нажатия кнопки ""Готово"" среда IDE создает демонстрационный проект ServletStateless. Проект ServletStateless отображается в окне 'Проекты'. [NOTE] ==== * По умолчанию, при использовании среды IDE для профилирования проекта, IDE выполнит профилирование проекта, выбранного в окне 'Проекты', если открыто более одного проекта. Если выбрать 'Выполнить' > 'Задать главный проект' в главном меню и задать проект как главный, то профилирование главного проекта выполняется по умолчанию. Можно щелкнуть правой кнопкой мыши узео проекта в окне 'Проекты' и выбрать 'Профиль' во всплывающем меню. * Если необходимо выполнить профилирование такого файла, как страница ``.jsp`` или сервлет, щелкните правой кнопкой мыши файл и выберите 'Профилировать файл' во всплывающем меню. Процесс профилирования такой же, как при выборе ""Профилирование главного проекта"", но при запуске сессии профилирования в браузере откроется выбранная страница вместо страницы проекта по умолчанию. ==== == Наблюдение за приложением Наблюдение за приложением позволяет получать информацию о свойствах целевой виртуальной машины Java, включая активность потоков и распределение памяти. Поскольку наблюдение за приложением не требует большого дополнительного расхода ресурсов, можно запускать приложение в этом режиме в течение длительного времени. При выборе задачи наблюдения целевое приложение запускается без каких-либо инструментов. Для отслеживания приложения ServletStateless выполните следующие действия: 1. Выберите 'Выполнить' > 'Задать главный проект' > ServletStateless для задания проекта как главного. При настройке проекта как главного, имя проекта будет выделено полужирным в окне 'Проекты'. . Выберите ""Профиль > Профилировать главный проект"" в главном меню. NOTE: Выберите JDK 1.7 или JDK 1.8 при отображении запроса на выбор платформы Java для профилирования. . Выберите ""Наблюдение"" в диалоговом окне ""Выбор задачи профилирования"". . Нажмите кнопку ""Выполнить"". NOTE: Если средство профилирования не использовалось ранее, может быть отображен запрос на калибровку средства профилирования до выбора 'Выполнить'. Дополнительные сведения о калибровке профилировщика см. раздел link:../java/profiler-intro.html#calibrate[+Первое использование профилировщика+] в link:../java/profiler-intro.html[+Введение в профилирование приложений Java в IDE NetBeans+]. По кнопке ""Выполнить"" среда IDE собирает приложение, запускает сервер в режиме профилирования, а затем разворачивает приложение на сервере. Затем среда IDE прикрепляется к приложению и запускает извлечение данных. Данные о потоках целевой виртуальной машины Java отображаются на вкладке ""Потоки"". Вкладка ""Потоки"" отображает данные по всем потокам, как серверным, так и потокам приложения. Дополнительную информацию о наблюдении можно получить, нажав кнопку ""Обзор телеметрии"" в окне ""Профилировщик"", чтобы открылось окно ""Обзор телеметрии виртуальной машины"". Окно ""Обзор телеметрии виртуальной машины"" позволяет быстро просмотреть данные наблюдения в реальном времени. Щелкнув два раза график в окне ""Обзор телеметрии виртуальной машины"", можно открыть более крупную версию изображения графика. При наблюдении за корпоративным приложением графики Memory (Heap) и Memory (GC) (график ""кучи"" памяти и график использования памяти при сборке мусора) помогают быстро проследить использование памяти приложением. Наведя указатель мыши на график, можно получить подсказку с более подробной информацией. Равномерное увеличение размера ""кучи"" или числа сохранившихся поколений указывает на утечку памяти. При подозрении на утечку памяти следует профилировать использование памяти приложением. image::images/monitor-memory-telemetry.png[title=""График памяти (GC), на котором отображаются данные GC""] == Анализ производительности приложения Задача анализа производительности ЦП позволяет увидеть данные производительности ЦП на уровне методов (время запуска) и количество вызовов методов из приложения. Можно предпочесть анализ производительности всего приложения или выбрать корень профилирования, чтобы применить профилирование только для части кода приложения. image::images/sample-task.png[title=""Режим образца приложения выбран на панели ЦП диалогового окна 'Выбор задачи профилирования'""] При запуске задачи анализа производительности ЦП в окне ""Задачи профилирования"" можно выбрать, какую часть приложения профилировать, отметив один из перечисленных параметров: * *Быстрый (образец).* В этом режиме IDE создает образец приложения и периодически создает трассировку стека. Этот вариант менее точен, чем методы инструментирования, но вызывает меньший дополнительный расход ресурсов. Этот вариант может помочь выбрать методы для инструментирования. * *Расширенный (инструментация).* В этом режиме методы профилируемого приложения инструментируются. Среда IDE регистрирует вход и выход потоков в методы проекта, позволяя отслеживать время, затрачиваемое на каждый метод. При входе в метод потоки создают событие ""вход в метод"". При выходе из метода потоки создают соответствующее событие ""выход из метода"". Записываются метки времени обоих событий. Эти данные обрабатываются в реальном времени. Можно выбрать инструментирование всех методов приложения или ограничить инструментирование поднабором кода приложения, указав один или несколько *корневых методов*. Определение корневых методов может сильно уменьшить дополнительный расход ресурсов на профилирование. Корневой метод — это метод, класс или пакет в исходном коде, который можно указать как корень обработки. Данные профилирования собираются при входе и выходе одного из потоков приложения из корня обработки. До входа одного из потоков приложения в корневой метод данные профилирования не собираются. Корневой метод можно указать, используя всплывающее меню в исходном коде, или щелкнув *настроить*, чтобы открыть диалоговое окно ""Изменить корневые методы профилирования"". *Советы про профилированию веб-приложений* * В дополнение к основным классам Java, корпоративные приложения обычно вызывают ряд методов в классах на целевом сервере. По этой причине важно настроить фильтр для ограничения количества исходного кода, которое необходимо инструментировать. Рекомендуется использовать фильтр *Профилировать только классы проекта* при профилировании корпоративных приложений. * Результаты профилирования собираются сразу при запуске сеанса профилирования. Если при использовании метода 'Расширенный' не указано профилирования ни одного корневого метода, некоторые интересные данные можно получить сразу же после запуска сервера, а именно прослушивателей веб-приложений и инициализации фильтров. Если указано профилирование неких корневых методов, эти данные, скорее всего, получены не будут. Их получение зависит от выбранных корневых методов. * Обычно данные прослушивателей и фильтров не бывают интересными, поэтому для их удаления можно нажать кнопку ""Сбросить собранные результаты"". Первые полезные данные собираются после того, как в результате некоторого действия в веб-браузере вызывается некоторый код, обычно это отображение страницы JSP, которая использует JavaBeans и/или избранные теги, или обработка методов ``doGet`` / ``doPost`` сервлета. Следует отметить, что данные, которые собираются при первом запуске приложения, обычно отражают только поведение веб-приложения при запуске. * Если страница JSP отображается впервые, она сервером внутренне компилируется в сервлет, что влияет на дерево вызовов и подсчет времени обработки метода. К тому же поведение кода сервлетов и других приложений при первом запуске может слегка отличаться от их поведения при производственной эксплуатации, когда они запущены постоянно. Для получения данных измерений, которые бы лучше характеризовали производительность приложения, перед измерением любых временных показателей следует увеличить рабочую нагрузку на профилируемый код (не должно повлиять на деревья вызовов). Для увеличения рабочей нагрузки можно использовать генераторы нагрузки. (Дополниетльные сведения см. в разделе link:../java/profile-loadgenerator.html[+Использование генератора нагрузки в IDE NetBeans+]). Средства кэширования у различных браузеров также могут повлиять на производительность. NOTE: При профилировании веб-приложений на сервере приложений GlassFish на компьютере под управлением Windows при запуске сервера для профилирования может произойти ошибка, если путь установки IDE NetBeans содержит пробелы (как например при установке в каталог по умолчанию ``C:\\Program Files\\netbeans-7.4`` ). В качестве временного решения можно установить или скопировать каталог установки IDE NetBeans в местоположение, путь к которому не содержит пробелов (например, ``C:\\netbeans-7.4`` ). === Опрос приложения Вариант ""Быстрый"" используется для обзора режима работы всего приложения в целом, когда нет необходимости в инструментировании методов. В режиме опроса приложения профиль Quick периодически снимает данные трассировки. Расход системных ресурсов в режиме профилирования 'Быстрый' меньше, чем в режиме профилирования 'Расширенный'. В следующем упражнении будет проанализирована производительность приложения в режиме профилирования 'Быстрый'. 1. Остановите сеанс наблюдения, нажав кнопку ""Стоп"" в меню ""Профилирование"". 2. Выберите ""Профиль > Профилировать главный проект"" в главном меню. 3. Выберите ""ЦП"" в диалоговом окне ""Выбор задачи профилирования"". 4. Выберите режим *Быстрый (образец)*. 5. Выберите *Профилировать только классы проекта* из раскрывающегося списка фильтров. Нажмите кнопку ""Выполнить"". NOTE: Этот фильтр ограничит классы, инструментированные для классов, найденных в проекте корпоративного приложения. Нажмите кнопку *Показать значение фильтра*, чтобы увидеть список отфильтрованных классов. image::images/sample-task.png[title=""Режим образца приложения выбран на панели ЦП диалогового окна 'Выбор задачи профилирования'""] По шкале в диалоговом окне можно заметить, что трата системных ресурсов относительно невысока. . Нажмите кнопку ""Текущие результаты профилирования"" в окне ""Профилирование"", чтобы открыть вкладку текущих результатов профилирования. image::images/sample-task-results.png[title=""Результаты режима 'Образцы приложений'""] На вкладке ""Текущие результаты профилирования"" показано время выполнения метода ``service`` для сервлета из класса ``Servlet2Stateless`` и то, что метод был вызван один раз. === Инструментирование всех методов В режиме ""Профилирование приложения"" все методы приложения инструментируются. Хотя это более точный метод изменения производительности приложения, трата системных ресурсов при профилировании выше, чем в режиме опроса. Можно настроить профилирование корневых методов так, чтобы ограничить количество инструментируемых методов и уменьшить загрузку при профилировании. Для некоторых приложений указание корневого метода может быть единственным способом получения подробных и/или реалистичных данных производительности, поскольку профилирование всего приложения может создать так много данных профилирования, что приложение станет непригодным к использованию, или даже произойдет отказ приложения. В следующем упражнении будет проанализирована производительность приложения с помощью инструментирования всех его методов. 1. Остановите сеанс наблюдения, нажав кнопку ""Стоп"" в меню ""Профилирование"". 2. Выберите ""Профиль > Профилировать главный проект"" в главном меню. 3. Выберите ""ЦП"" в диалоговом окне ""Выбор задачи профилирования"". 4. Выберите режим *Расширенный (инструментарий)*. 5. Выберите *Профилировать только классы проекта* из раскрывающегося списка фильтров. Нажмите кнопку ""Выполнить"". image::images/advanced-cpu-task.png[title=""Режим профилирования приложения выбран на панели ЦП диалогового окна 'Выбор задачи профилирования'""] По шкале в диалоговом окне можно заметить, что трата системных ресурсов выше, чем в режиме быстрого профилирования. . Нажмите кнопку ""Текущие результаты профилирования"" в окне ""Профилирование"", чтобы открыть вкладку текущих результатов профилирования. На вкладке ""Текущие результаты профилирования"" показано время выполнения методов ``init`` и ``service`` для сервлета из класса ``Servlet2Stateless`` , и то, что каждый из методов был вызван один раз. Метод ``init`` в классе ``StatelessSessionBean`` также был вызван. image::images/cpu-pane1-results.png[title=""Результаты режима 'Профилирование приложений'""] NOTE: По умолчанию режим автоматического обновления активен, что обеспечивает обновление отображаемых данных каждые несколько секунд. Можно включать или отключать режим автоматического обновления, нажав кнопку ""Автообновление"" на панели инструментов. Для повышения удобочитаемости собранные данные можно фильтровать, используя фильтр ""Результаты"" в списке ""Просмотр горячих точек"" окна ""Текущие результаты профилирования"". Фильтр ""Результаты"" формирует выборку только по результатам и не затрагивает обрабатываемые классы. Используя фильтр ""Результаты"", можно отбирать результаты, которые соответствуют определенному шаблону. Для фильтрации можно использовать также более сложные регулярные выражения. Данные фильтруются по именам пакетов/классов/методов, в точности, как они появляются в первой колонке таблицы результатов. Можно определить более, чем один шаблон фильтрации, разделяя их пробелом или точкой с пробелом. . Введите свое имя в поле в веб-браузере и нажмите ""Отправить запрос"". image::images/cpu-pane1-results1.png[title=""Результаты режима 'Профилирование приложений'""] По нажатию кнопки ""Отправить запрос""данные на вкладке ""Текущие результаты профилирования"" обновляются для отражения действий в веб-браузере. Нажатие кнопки запускает метод ``sayHello`` в классе ``StatelessSessionBean`` и вновь вызывает метод ``init`` . ``Служебный`` метод для сервлета из ``Servlet2Stateless`` также был вызван вновь. Вкладка ""Текущие результаты профилирования"" также показывает, сколько времени было затрачено в каждом из методов. Чтобы увидеть графическое представление относительного времени, затраченного в различных областях приложения (сервлетах, прослушивателях и т.д.), нажмите кнопку ""Развернуть"". Можно нажать на сам график, чтобы развернуть результаты профилирования на экран. image::images/drill-down.png[title=""График перехода по иерархии относительного времени, потраченного в сервлетах в приложении""] Инструментирование приложения всегда затрачивает некоторое количество системных ресурсов на профилирование. В таком простом приложении затрата системных ресурсов незаметна, но в сложных приложениях она может быть весьма значительной. Можно уменьшить затраты системных ресурсов ограничением количества профилируемых классов, выбрав профилирование корневого метода. === Использование профилирования корневых методов В следующем упражнении будет профилирована только часть приложения. Этот метод профилирования используется, если известны потенциальные ""узкие места"" приложения, касающиеся производительности, или если необходимо профилировать определенную часть кода, например, один из нескольких сервлетов. При этом методе на профилирование обычно затрачивается гораздо меньше системных ресурсов, чем при методе инструментирования всего приложения. При инструментировании только с части приложения собираются и отображаются только интересующие данные. Чтобы профилировать часть приложения, необходимо назначить один или более корневых методов профилирования. Среда IDE инструментирует только те методы, которые вызываются потоком, входящим в корневой метод профилирования. Например, если назначить метод ``sayHello`` в классе ``StatelessSessionBean`` корневым методом и использовать фильтр ""Профилировать только классы проекта"", среда IDE запустит методы инструментирования при вызове метода, когда в него войдет поток приложения. В этом приложении конструктор ``init`` не будет инструментирован, поскольку он вызывается перед ``sayHello`` . image::images/profileroot-sayhello-project.png[title=""График перехода по иерархии относительного времени, потраченного в сервлетах в приложении""] Если выбрать фильтр ""Профилировать все классы"", среда IDE инструментирует все методы, вызванные ``sayHello`` , включая базовые классы языка Java. image::images/profileroot-sayhello-all.png[title=""График перехода по иерархии относительного времени, потраченного в сервлетах в приложении""] NOTE: В более комплексных приложениях может потребоваться указание нескольких корневых методов. В качестве корней профилирования можно выбрать отдельные методы, целые классы и пакеты. Чтобы указать корень профилирования и проанализировать производительность приложения, выполните следующие действия. 1. Остановите предыдущие сессии профилирования (если они все еще запущены), нажав кнопку ""Завершить"" в окне ""Профилирование"". 2. Выберите ""Профиль > Профилировать главный проект"" в главном меню. 3. Выберите ""ЦП"" в диалоговом окне ""Выбор задачи профилирования"". 4. Выберите режим *Расширенный (инструментарий)*. 5. Нажмите кнопку *настроить*, чтобы открыть диалоговое окно ""Изменение корневых методов профилирования"". Чтобы профилировать часть приложения необходимо сначала определить корневые методы. После выбора корневого метода профилирование будет применяться только к тем методам, которые вызываются потоком, входящим в корень профилирования. . В диалоговом окне ""Изменить корневые методы профилирования"" выберите ""Вид веб-приложения"" в раскрывающемся списке ""Выбрать вид"". . Разверните узел ServletStateless и выберите метод ``service`` в пакете сервлетов. Нажмите кнопку ""ОК"". image::images/edit-profiling-roots.png[title=""Представление веб-приложения в диалоговом окне 'Изменение корневых методов профилирования'""] В противном случае можно выбрать ""Просмотр пакета"", чтобы увидеть все исходные пакеты приложения и выбрать метод ``service`` из класса ``Servlet2Stateless`` пакета ``servlet.stateless`` . image::images/edit-profiling-roots-pkg.png[title=""Представление пакета в диалоговом окне 'Изменение корневых методов профилирования'""] NOTE: Обратите внимание, что конструктор ``Servlet2Stateless`` не выбран. Диалог ""Изменить корневые методы профилирования"" используется, чтобы применять инструментирование только к определенным методам класса. Если нет необходимости применять инструментирование только к определенным методам, можно использовать представление пакетов, чтобы выбрать весь класс или пакет. Например, если выбрать класс ``Servlet2Stateless`` в представлении пактов диалога ""Изменить корневые методы профилирования"", среда IDE инструментирует конструктор ``init`` и метод ``service`` . Если нажать кнопку ""Дополнительно"", можно увидеть, что метод ``service`` представлен в диалоговом окне ""Изменить корневые методы профилирования (Дополнительно)"", как единственный корневой метод. Чтобы явно определить метод, добавив ему подпись и класс, нажмите кнопку ""Добавить"". image::images/edit-profilingroots-pkg-adv.png[title=""Диалоговое окно 'Изменение корневых методов профилирования' (Расширенное)""] . Нажмите кнопку ""ОК"" в диалоговом окне ""Изменить корневые методы профилирования"". В диалоговом окне ""Выбрать задачу профилирования"" видно, что режим расширенного профилирования будет запущен с помощью специальных корневых методов профилирования. Чтобы просмотреть и изменить выбранный корневой метод нажмите *Изменить*. Заметим, что затраты системных ресурсов после этих действий ниже, чем была до настройки корневых методов. . Выберите *Профилировать только классы проекта* из раскрывающегося списка фильтров. Нажмите кнопку ""Выполнить"". image::images/advanced-cpu-task-custom.png[title=""Режим профилирования приложения выбран с нестандартным корнем профилирования""] При нажатии кнопки ""Запустить"" среда IDE собирает и разворачивает приложение и открывает в веб-браузере страницу сервлета. В среде IDE результаты профилирования показываются на вкладке ""Текущие результаты профилирования"". image::images/cpu-pane2-results.png[title=""Результаты методов инструментирования с использованием корня профилирования""] Можно увидеть, что в среде IDE показываются результаты только для метода, определенного как корень профилирования. Поток приложения не вошел больше ни в один из методов приложения после входа в корень профилирования. Хотя поток приложения выполнил вход в другие методы после входа в корень профилирования, эти методы не отображаются, поскольку фильтр инструментирования отбирает для инструментирования только те классы, которые являются частью проекта. . Введите свое имя в поле в веб-браузере и нажмите ""Отправить запрос"". image::images/cpu-pane2-results1.png[title=""Результаты методов инструментирования с использованием корня профилирования после вызова метода sayHello""] По нажатию кнопки ""Отправить запрос""данные на вкладке ""Текущие результаты профилирования"" обновляются для отражения действий в веб-браузере. Нажатие кнопки вызывает метод ``sayHello`` класса ``StatelessSessionBean`` один раз. Метод ``service`` также заново вызывается. Результирующие данные, которые отражают производительность приложения, могут не совсем точно описывать производительность приложения, работающего уже некоторое время. Один из способов сымитировать поведение веб-приложения в более реальных условиях — запустить сценарий генератора загрузки. . Повторите в браузере предыдущее действие несколько раз, затем нажмите ""Сбросить результаты"" на вкладке ""Текущие результаты профилирования"" для удаления результатов. . После сброса результатов профилирования введите свое имя и нажмите ""Отправить запрос"" еще раз. image::images/cpu-pane2-results2.png[title=""Результаты методов инструментирования с использованием корня профилирования после вызова метода sayHello""] При взгляде на результаты профилирования в большинстве случаев заметно, что производительность приложения улучшилась. === Использование инструментальных фильтров При анализе производительность ЦП можно уменьшить затраты системных ресурсов с помощью инструментального фильтра, который отберет для профилирования интересующую части кода приложения. Фильтр отбирает пакеты/классы для инструментирования. Можно выбрать фильтр из следующего списка фильтров по умолчанию или создать индивидуальный. * *Профилирование всех классов.* Если выбрать этот фильтр при профилировании веб-приложений или корпоративных приложений, инструментируются все классы, включая основные классы Java и классов серверов. Этот фильтр необходимо использовать с осторожностью, поскольку инструментирование такого большого количества классов может повлечь *очень* значительные затраты системных ресурсов. * *Профилирование только классов проекта.* При профилировании корпоративного приложения рекомендуется использовать именно этот фильтр, чтобы инструментировать только классы проекта. Серверные классы не будут инструментированы. * *Профилирование классов проектов и подпроектов.* При профилировании проекта корпоративного приложения, которое содержит подпроекты, такие как веб-приложения, модули EJB или библиотеки классов, можно выбрать этот фильтр, чтобы ограничить инструментированного кода для классов в подпроектах. Можно создать индивидуальный фильтр, который будет использоваться в определенном проекте или для определенных типов профилирования. Например, если требуется использовать инструментальный фильтр для профилирования веб-приложений на сервере Oracle WebLogic, можно нажать кнопку ""Изменить набор фильтров"" и создать набор фильтров, которые будут исключать из процесса инструментирования базовые классы языка Java, классы Oracle WebLogic и классы NetBeans (удобно при отключенном мониторинге HTTP). Набору фильтров можно дать название, как, например ""Только для веб-приложений WebLogic"", и затем выбирать этот фильтр из выпадающего списка фильтров при профилировании приложения, развернутого на сервере WebLogic. image::images/custom-filter.png[title=""диалоговое окно, которое отображается при профилировании проекта в первый раз""] Можно задать простой инструментальный фильтр, выбрав ""Быстрый фильтр"" из выпадающего списка фильтров, который откроет диалоговое окно ""Установить быстрый фильтр"". Затем можно быстро изменить список пакетов или классов для инструментирования. Это создаст быстрый фильтр, который затем можно выбирать из выпадающего списка фильтров. image::images/set-quick-filter.png[title=""диалоговое окно, которое отображается при профилировании проекта в первый раз""] Более подробную информацию об определении и использовании инструментальных фильтров можно найти в документации по профилированию, поставляемой с IDE. == Анализ использования памяти приложением С помощью средства профилирования, встроенного в IDE, можно анализировать, сколько памяти использует корпоративное приложение, чтобы получить подробные данные по размещению объектов и сборке мусора. Задач ""Анализ использования памяти"" предоставляет данные об объектах, выделенных в целевом приложении, таких как число, тип и расположение выделенных объектов. При профилировании использования памяти нет возможности задать корневой метод профилирования и/или инструментальные фильтры, поэтому отслеживаются все объекты, созданные во время работы сервера. На сложных серверах приложений это может привести к серьезному потреблению памяти и затратам системных ресурсов на профилирование. Поэтому, прежде чем запускать этот тип профилирования, необходимо иметь в виду потенциальные ограничения работы компьютера. Чтобы уменьшить затраты системных ресурсов на профилирование, можно изменить его настройки так, чтобы профилировался только каждый десятый объект. Также можно отключить (ограничить) запись трассировки стеков для размещения объектов. При профилировании корпоративного приложения для поиска утечек памяти, полезно использовать метрики ""сохранившихся поколений"". Трассировкой числа различных циклов сборки мусора сохранившихся поколений, инструмент профилирования может найти утечку памяти заранее, пока приложение не использовало значительный объем памяти. Для анализа производительности памяти необходимо выбрать объем данных для получения, выбрав один из следующих вариантов. * *Быстро.* Если выбран этот вариант, профилировщик создаст образец приложения для предоставления данных, которые ограничены живыми объектами. Живые объекты - все доступные (и недоступные), не востребованные повторно сборщиком мусора (Garbage Collector). Этот параметр отслеживает только живые объекты и не отслеживает распределение при использовании инструментов. Если выбран этот вариант, невозможно регистрировать трассировки стеков или использовать точки профилирования. Этот вариант требует значительно меньших затрат, чем 'Дополнительно'. * *Дополнительно.* Если выбран этот вариант, можно получить информацию о количестве, типе и местоположении выделенных объектов. Выделенные объекты - это объекты, созданные с момента запуска приложения (или с момента последнего сброса собранных результатов в профилировщике). Все классы, которые в настоящее время загружены целевым JVM (и каждый новый класс после его загрузки) являются инструментами для получения информации о распределении объектов. Этот вариант необходимо выбрать, если нужно использовать точки профилирования при анализе памяти или если нужно выполнить запись стека вызовов. Этот вариант требует больших затрат на профилирование по сравнению с вариантом 'Быстро'. Если вы выберете вариант 'Дополнительно', вы также можете установить следующие параметры. * *Запись полного образа жизни объекта.* Выберите этот вариант, чтобы записать всю информацию по каждому объекту, в том числе количество выживших поколений. * *Запись трассировки стека для распределения.* Выберите этот вариант, чтобы записать полный стек вызовов. Этот вариант позволяет просматривать дерево обратных вызовов для вызовов методов при просмотре снимка памяти. * *Использование определенных точек профилирования.* Выберите этот вариант, чтобы включить поддержку точек профилирования. Отключенные точки профилирования игнорируются. При отмене этого параметра все точки профилирования в проекте игнорируется. Измеритель 'Издержки' в окне 'Выбор задачи профилирования' дает приблизительное представление об увеличении или уменьшении издержек на профилирование в соответствии с выбранными параметрами профилирования. Используем среду IDE для анализа производительности памяти корпоративного приложения. Если необходимо получать информацию о выживших поколениях, необходимо выбрать вариант *Дополнительно*. Кроме того, если необходимы данные только о живых объектах, можно выбрать вариант *Быстро*. 1. Остановите предыдущие сессии профилирования (если они все еще запущены), нажав кнопку ""Завершить"" в окне ""Профилирование"". При нажатии ""Остановить"" среда IDE отсоединяется от приложения. . Выберите ""Профиль > Профилировать главный проект"" в главном меню. . Выберите *Память* в диалоговом окне ""Выбрать задачу профилирования"". . Выберите *Дополнительно*. . Выберите *Запись полного жизненного цикла объекта* для получения данных о выживании поколений. NOTE: При выборе этого параметра уровень затрат системных ресурсов значительно повысится. При профилировании корпоративного приложения может понадобиться увеличить размер памяти, используемой IDE, из-за количество собранных данных. . Снимите отметку с параметра *Использовать определенные точки профилирования* (если он был отмечен). Нажмите кнопку ""Выполнить"". image::images/profile-memory-advanced.png[title=""Диалоговое окно 'Выбрать задачу профилированию', в котором поазывается задача и параметры памяти""] При нажатии кнопки ""Выполнить"" среда IDE компилирует приложение, запускает сервер в режиме профилирования и разворачивает на нем приложение. Чтобы просмотреть результаты профилирования, нажмите кнопку ""Текущие результаты"" в окне ""Средство профилирования"", при этом откроется окно ""Текущие результаты"". Окно ""Текущие результаты"" показывает информацию о размере и количестве объектов, находящихся на целевой виртуальной машине Java. В дополнение к объектам, размещенным корпоративным приложением, в результатах показываются все объекты, размещенные сервером приложений. image::images/profile-memory-results.png[title=""Вкладка 'Результаты профилирования', на которой отображаются результаты профилирования использования памяти""] По умолчанию результаты сохраняются и отображаются как число выделенных байтов, но можно щелкнуть заголовок столбца, чтобы изменить способ отображения результатов. Также можно выполнить фильтрацию результатов, введя имя класса в поле фильтра под списком. link:/about/contact_form.html?to=3&subject=Feedback:%20Profiling%20Enterprise%20Applications[+Отправить отзыв по этому учебному курсу+] == Дополнительные сведения Этот документ описал основной подход к получению данных измерений при профилировании корпоративного приложение, развернутого на сервере приложений GlassFish. Для получения более подробной информации о параметрах и функциях профилирования, не рассмотренных в этом документе, воспользуйтесь документацией, входящей в состав среды IDE и доступной из меню ""Справка"". Сопутствующая документация приведена в следующих ресурсах. * link:http://wiki.netbeans.org/wiki/view/NetBeansUserFAQ#section-NetBeansUserFAQ-Profiler[+Часто задаваемые вопросы по профилированию NetBeans+] Документ содержит часто задаваемые вопросы по профилированию приложений в среде IDE NetBeans * link:http://wiki.netbeans.org/wiki/view/FaqProfilerProfileFreeForm[+Часто задаваемые вопросы: профилирование проекта произвольной формы+] * link:../java/profiler-screencast.html[+Демонстрация: точки профилирования, детализированные графики, анализатор кучи+] Демонстрация некоторых функций профилирования в среде IDE NetBeans * link:../../../community/magazine/html/04/profiler.html[+Расширенное профилирование: теория на практике+] * link:http://profiler.netbeans.org/index.html[+profiler.netbeans.org+] Сайт проекта средства профилирования NetBeans * link:http://blogs.oracle.com/nbprofiler/[+Блог по средству профилирования NetBeans+] * link:http://profiler.netbeans.org/mailinglists.html[+Списки рассылки по средству профилирования NetBeans+] * link:http://profiler.netbeans.org/docs/help/5.5/index.html[+Использование профилировщика NetBeans, версии 5.5+] <> ",12308,True,2573.7749650442524,median "[[git-plugin]] = Git Plugin :toc: macro :toc-title: [#introduction] == Introduction [.float-group] -- [.text-center] image:https://jenkins.io/images/logos/jenkins/jenkins.png[Jenkins logo,height=192,role=center,float=right] image:images/signe-1923369_640.png[plus,height=64,float=right] image:https://git-scm.com/images/logos/downloads/Git-Logo-2Color.png[Git logo,height=128,float=right] -- The git plugin provides fundamental git operations for Jenkins projects. It can poll, fetch, checkout, branch, list, merge, tag, and push repositories. toc::[] [#changelog] == Changelog in https://github.com/jenkinsci/git-plugin/releases[GitHub Releases] Release notes are recorded in https://github.com/jenkinsci/git-plugin/releases[GitHub Releases] since July 1, 2019 (git plugin 3.10.1 and later). Prior release notes are recorded in the git plugin repository link:CHANGELOG.adoc#changelog-moved-to-github-releases[change log]. == Pipelines The git plugin provides an SCM implementation to be used with the Pipeline SCM link:https://www.jenkins.io/doc/pipeline/steps/workflow-scm-step/[`checkout` step]. The link:https://www.jenkins.io/doc/book/pipeline/getting-started/#snippet-generator[""Pipeline Syntax"" snippet generator] guides the user to select checkout options. The link:https://youtu.be/ai1kf4ihZUo[90 second video clip] below introduces the Pipeline Syntax snippet generator and shows how it is used to generate steps for the Jenkins Pipeline. image:images/pipeline-syntax.png[link=https://youtu.be/ai1kf4ihZUo] === Multibranch Pipelines The git plugin includes a multibranch provider for Jenkins link:https://www.jenkins.io/doc/book/pipeline/multibranch/[Multibranch Pipelines] and for Jenkins link:https://www.jenkins.io/doc/book/pipeline/multibranch/#organization-folders[Organization Folders]. The git plugin multibranch provider is a ""base implementation"" that uses command line git. Users should prefer the multibranch implementation for their git provider when one is available. Multibranch implementations for specific git providers can use REST API calls to improve the Jenkins experience and add additional capabilities. Multibranch implementations are available for link:https://docs.cloudbees.com/docs/cloudbees-ci/latest/cloud-admin-guide/github-branch-source-plugin[GitHub], link:https://github.com/jenkinsci/bitbucket-branch-source-plugin/blob/master/docs/USER_GUIDE.adoc[Bitbucket], link:https://plugins.jenkins.io/gitlab-branch-source/[GitLab], link:https://plugins.jenkins.io/gitea/[Gitea], and link:https://plugins.jenkins.io/tuleap-git-branch-source/[Tuleap]. The link:https://youtu.be/B_2FXWI6CWg[30 minute video clip] below introduces Multibranch Pipelines. image:images/multibranch-pipeline.png[link=https://youtu.be/B_2FXWI6CWg] [#configuration] == [[GitPlugin-ProjectConfiguration]]Configuration [#using-repositories] === Repositories image:/images/git-repository-configuration.png[Repository Configuration] The git plugin fetches commits from one or more remote repositories and performs a checkout in the agent workspace. Repositories and their related information include: Repository URL:: The URL of the remote repository. The git plugin passes the remote repository URL to the git implementation (command line or JGit). Valid repository URL's include `https`, `ssh`, `scp`, `git`, `local file`, and other forms. Valid repository URL forms are described in the link:https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_protocols[git documentation]. Credentials:: Credentials are defined using the link:https://plugins.jenkins.io/credentials[Jenkins credentials plugin]. They are selected from a drop-down list and their identifier is stored in the job definition. Refer to <> for more details on supported credential types. Name:: Git uses a shortname to simplify user references to the URL of the remote repository. The default shortname is `origin`. Other values may be assigned and then used throughout the job definition to refer to the remote repository. Refspec:: A refspec maps remote branches to local references. It defines the branches and tags which will be fetched from the remote repository into the agent workspace. + A refspec defines the remote references that will be retrieved and how they map to local references. If left blank, it will default to the normal `git fetch` behavior and will retrieve all branches. This default behavior is sufficient for most cases. + The default refspec is `+refs/heads/*:refs/remotes/REPOSITORYNAME/` where REPOSITORYNAME is the value you specify in the above repository ""Name"" field. The default refspec retrieves all branches. If a checkout only needs one branch, then a more restrictive refspec can reduce the data transfer from the remote repository to the agent workspace. For example, `+refs/heads/master:refs/remotes/origin/master` will retrieve only the master branch and nothing else. + The refspec can be used with the <> option in the <> to limit the number of remote branches mapped to local references. If ""honor refspec on initial clone"" is not enabled, then a default refspec for its initial fetch. This maintains compatibility with previous behavior and allows the job definition to decide if the refspec should be honored on initial clone. + Multiple refspecs can be entered by separating them with a space character. The refspec value `+refs/heads/master:refs/remotes/origin/master +refs/heads/develop:refs/remotes/origin/develop` retrieves the master branch and the develop branch and nothing else. + Refer to the link:https://git-scm.com/book/en/v2/Git-Internals-The-Refspec[git refspec documentation] for more refspec details. [#using-credentials] === Using Credentials The git plugin supports username / password credentials and private key credentials provided by the https://plugins.jenkins.io/credentials[Jenkins credentials plugin]. It does not support other credential types like secret text, secret file, or certificates. Select credentials from the job definition drop down menu or enter their identifiers in Pipeline job definitions. When the remote repository is accessed with the **HTTP or HTTPS protocols**, the plugin requires a **username / password credential**. Other credential types will not work with HTTP or HTTPS protocols. When the remote repository is accessed with the **ssh protocol**, the plugin requires an **ssh private key credential**. Other credential types will not work with the ssh protocol. [#push-notification-from-repository] === [[GitPlugin-Pushnotificationfromrepository]]Push Notification From Repository To minimize the delay between a push and a build, configure the remote repository to use a Webhook to notify Jenkins of changs to the repository. Refer to webhook documentation for your repository: * link:https://plugins.jenkins.io/github#GitHubPlugin-GitHubhooktriggerforGITScmpolling[GitHub] * link:https://plugins.jenkins.io/bitbucket[Bitbucket] * link:https://plugins.jenkins.io/gitlab-branch-source[GitLab] * link:https://github.com/jenkinsci/gitea-plugin/blob/master/docs/README.md[Gitea] Other git repositories can use a link:https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks[post-receive hook] in the remote repository to notify Jenkins of changes. Add the following line in your `hooks/post-receive` file on the git server, replacing with the fully qualified URL you use when cloning the repository. .... curl http://yourserver/git/notifyCommit?url= .... This will scan all the jobs that: * Have Build Triggers > Poll SCM enabled. No polling schedule is required. * Are configured to build the repository at the specified URL For jobs that meet these conditions, polling will be triggered. If polling finds a change worthy of a build, a build will be triggered. This allows a notify script to remain the same for all Jenkins jobs. Or if you have multiple repositories under a single repository host application (such as Gitosis), you can share a single post-receive hook script with all the repositories. Finally, this URL doesn't require authentication even for secured Jenkins, because the server doesn't directly use anything that the client is sending. It polls to verify that there is a change before it actually starts a build. When notifyCommit is successful, the list of triggered projects is returned. [#enabling-jgit] === Enabling JGit See the link:https://plugins.jenkins.io/git-client/#enabling-jgit[git client plugin documentation] for instructions to enable JGit. JGit becomes available throughout Jenkins once it has been enabled. [#global-configuration] === [[GitPlugin-Configuration]]Global Configuration image:/images/git-global-configuration.png[Global Configuration] In the `Configure System` page, the Git Plugin provides the following options: [[global-config-user-name]] Global Config user.name Value:: Defines the default git user name that will be assigned when git commits a change from Jenkins. For example, `Janice Examplesperson`. This can be overridden by individual projects with the <> extension. [[global-config-user-email]] Global Config user.email Value:: Defines the default git user e-mail that will be assigned when git commits a change from Jenkins. For example, `janice.examplesperson@example.com`. This can be overridden by individual projects with the <> extension. [[create-new-accounts-based-on-author-email]] Create new accounts based on author/committer's email:: New user accounts are created in Jenkins for committers and authors identified in changelogs. The new user accounts are added to the internal Jenkins database. The e-mail address is used as the id of the account. [[show-the-entire-commit-summary-in-changes]] Show the entire commit summary in changes:: The `changes` page for each job would truncate the change summary prior to git plugin 4.0. With the release of git plugin 4.0, the default was changed to show the complete change summary. Administrators that want to restore the old behavior may disable this setting. [[hide-credentials]] Hide credential usage in job output:: If checked, the console log will not show the credential identifier used to clone a repository. [[disable-performance-enhancements]] Disable performance enhancements:: If JGit and command line git are both enabled on an agent, the git plugin uses a ""git tool chooser"" to choose a preferred git implementation. The preferred git implementation depends on the size of the repository and the git plugin features requested by the job. If the repository size is *less than* the JGit repository size threshold and the git features of the job are all implmented in JGit, then JGit is used. If the repository size is *greater than* the JGit repository size threshold or the job requires git features that are not implemented in JGit, then command line git is used. + If checked, the plugin will disable the feature that recommends a git implementation on the basis of the size of a repository. This switch may be used in case of a bug in the performance improvement feature. If you enable this setting, please report a git plugin issue that describes why you needed to enable it. [[preserve-second-fetch-during-checkout]] Preserve second fetch during initial checkout:: If checked, the initial checkout step will not avoid the second fetch. Git plugin versions prior to git plugin 4.4 would perform two fetch operations during the initial repository checkout. Git plugin 4.4 removes the second fetch operation in most cases. Enabling this option will restore the second fetch operation. This setting is only needed if there is a bug in the redundant fetch removal logic. If you enable this setting, please report a git plugin issue that describes why you needed to enable it. [[do-not-add-git-tag-action-to-jobs]] Add git tag action to jobs:: If checked, the git tag action will be added to any builds that happen *after* the box is checked. Prior to git plugin 4.5.0, the git tag action was always added. Git plugin 4.5.0 and later will not add the git tag action to new builds unless the administrator enables it. + The git tag action allows a user to apply a tag to the git repository in the workspace based on the git commit used in the build applying the tag. The git plugin does *not* push the applied tag to any other location. If the workspace is removed, the tag that was applied is lost. Tagging a workspace made sense when using centralized repositories that automatically applied the tag to the centralized repository. Applying a git tag in an agent workspace doesn't have many practical uses. [#repository-browser] === Repository Browser image:/images/git-repository-browser.png[Repository Browser] A Repository Browser adds links in ""changes"" views within Jenkins to an external system for browsing the details of those changes. The ""Auto"" selection attempts to infer the repository browser from the ""Repository URL"" and can detect cloud versions of GitHub, Bitbucket and GitLab. Repository browsers include: [#assemblaweb-repository-browser] ==== AssemblaWeb image:/images/git-repository-browser-assemblaweb.png[Assembla Repository Browser] Repository browser for git repositories hosted by link:https://www.assembla.com/home[Assembla]. Options include: [[assembla-git-url]] Assembla Git URL:: Root URL serving this Assembla repository. For example, `\\https://app.assembla.com/spaces/git-plugin/git/source` [#fisheye-repository-browser] ==== FishEye image:/images/git-repository-browser-fisheye.png[FishEye Repository Browser] Repository browser for git repositories hosted by link:https://www.atlassian.com/software/fisheye[Atlassian Fisheye]. Options include: [[fisheye-url]] URL:: Root URL serving this FishEye repository. For example, `\\https://fisheye.example.com/browser/my-project` [#kiln-repository-browser] ==== Kiln image:/images/git-repository-browser-kiln.png[Kiln Repository Browser] Repository browser for git repositories hosted by link:http://www.fogbugz.com/version-control[Kiln]. Options include: [[kiln-url]] URL:: Root URL serving this Kiln repository. For example, `\\https://kiln.example.com/username/my-project` [#visual-studio-team-services-repository-browser] ==== Microsoft Team Foundation Server/Visual Studio Team Services image:/images/git-repository-browser-microsoft.png[Microsoft Repository Browser] Repository browser for git repositories hosted by link:https://azure.microsoft.com/en-us/solutions/devops/[Azure DevOps]. Options include: [[visual-studio-repository-url-or-name]] URL or name:: Root URL serving this Azure DevOps repository. For example, `\\https://example.visualstudio.com/_git/my-project.` [bitbucketweb-repository-browser] ==== bitbucketweb image:/images/git-repository-browser-bitbucket.png[Bitbucket Repository Browser] Repository browser for git repositories hosted by link:https://bitbucket.org/[Bitbucket]. Options include: [[bitbucketweb-url]] URL:: Root URL serving this Bitbucket repository. For example, `\\https://bitbucket.example.com/username/my-project` [#cgit-repository-browser] ==== cgit image:/images/git-repository-browser-cgit.png[CGit Repository Browser] Repository browser for git repositories hosted by link:https://git.zx2c4.com/cgit/[cgit]. Options include: [[cgit-url]] URL:: Root URL serving this cgit repository. For example, `\\https://git.zx2c4.com/cgit/` [#gitblit-repository-browser] ==== gitblit image:/images/git-repository-browser-gitblit.png[GitBlit Repository Browser] [[gitblit-url]] GitBlit root url:: Root URL serving this GitBlit repository. For example, `\\https://gitblit.example.com/` [[gitblit-project-name]] Project name in GitBlit:: Name of the GitBlit project. For example, `my-project` [#githubweb-repository-browser] ==== githubweb image:/images/git-repository-browser-github.png[GitHub Repository Browser] Repository browser for git repositories hosted by link:https://github.com//[GitHub]. Options include: [[githubweb-url]] URL:: Root URL serving this GitHub repository. For example, `\\https://github.example.com/username/my-project` [#gitiles-repository-browser] ==== gitiles image:/images/git-repository-browser-gitiles.png[Gitiles Repository Browser] Repository browser for git repositories hosted by link:https://gerrit.googlesource.com/gitiles/[Gitiles]. Options include: [[githubweb-url]] gitiles root url:: Root URL serving this Gitiles repository. For example, `\\https://gerrit.googlesource.com/gitiles/` [#gitlab-self-hosted-repository-browser] [#gitlab-com-repository-browser] ==== gitlab image:/images/git-repository-browser-gitlab.png[GitLab Repository Browser] Repository browser for git repositories hosted by link:https://gitlab.com/[GitLab]. Options include: [[gitlab-url]] URL:: Root URL serving this GitLab repository. For example, `\\https://gitlab.example.com/username/my-project` [[gitlab-version]] Version:: Major and minor version of GitLab you use, such as 12.6. If you don't specify a version, a modern version of GitLab (>= 8.0) is assumed. For example, `12.6` [#gitlist-repository-browser] ==== gitlist image:/images/git-repository-browser-gitlist.png[Gitlist Repository Browser] Repository browser for git repositories hosted by link:https://gitlist.org/[GitList]. Options include: [[gitlist-url]] URL:: Root URL serving this GitList repository. For example, `\\https://gitlist.example.com/username/my-project` [#gitoriousweb-repository-browser] ==== gitoriousweb Gitorious was acquired in 2015. This browser is *deprecated*. [[gitoriousweb-url]] URL:: Root URL serving this Gitorious repository. For example, `\\https://gitorious.org/username/my-project` [#gitweb-repository-browser] ==== gitweb image:/images/git-repository-browser-gitweb.png[Gitweb Repository Browser] Repository browser for git repositories hosted by link:https://git-scm.com/docs/gitweb[GitWeb]. Options include: [[gitweb-url]] URL:: Root URL serving this GitWeb repository. For example, `\\https://gitweb.example.com/username/my-project` [#gogs-repository-browser] ==== gogs image:/images/git-repository-browser-gogs.png[Gogs Repository Browser] Repository browser for git repositories hosted by link:https://gogs.io/[Gogs]. Options include: [[gogs-url]] URL:: Root URL serving this Gogs repository. For example, `\\https://gogs.example.com/username/my-project` [#phabricator-repository-browser] ==== phabricator image:/images/git-repository-browser-phabricator.png[Phabricator Repository Browser] Repository browser for git repositories hosted by link:https://www.phacility.com/phabricator/[Phacility Phabricator]. Options include: [[phabricator-url]] URL:: Root URL serving this Phabricator repository. For example, `\\https://phabricator.example.com/` [[phabricator-repository-name]] Repository name in Phab:: Name of the Phabricator repository. For example, `my-project` [#redmineweb-repository-browser] ==== redmineweb image:/images/git-repository-browser-redmine.png[Redmine Repository Browser] Repository browser for git repositories hosted by link:https://www.redmine.org/[Redmine]. Options include: [[redmineweb-url]] URL:: Root URL serving this Redmine repository. For example, `\\https://redmine.example.com/username/projects/my-project/repository` [#rhodecode-repository-browser] ==== rhodecode image:/images/git-repository-browser-rhodecode.png[RhodeCode Repository Browser] Repository browser for git repositories hosted by link:https://thodecode.com/[RhodeCode]. Options include: [[rhodecode-url]] URL:: Root URL serving this RhodeCode repository. For example, `\\https://rhodecode.example.com/username/my-project` [#stash-repository-browser] ==== stash image:/images/git-repository-browser-stash.png[Stash Repository Browser] Stash is now called *BitBucket Server*. Repository browser for git repositories hosted by link:https://www.atlassian.com/software/bitbucket[BitBucket Server]. Options include: [[stash-url]] URL:: Root URL serving this Stash repository. For example, `\\https://stash.example.com/username/my-project` [#viewgit-repository-browser] ==== viewgit image:/images/git-repository-browser-viewgit.png[Viewgit Repository Browser] Repository browser for git repositories hosted by link:https://www.openhub.net/p/viewgit[viewgit]. Options include: [[viewgit-root-url]] ViewGit root url:: Root URL serving this ViewGit repository. For example, `\\https://viewgit.example.com/` [[viewgit-project-name]] Project Name in ViewGit:: ViewGit project name. For example, `my-project` [#extensions] == Extensions Extensions add new behavior or modify existing plugin behavior for different uses. Extensions help users more precisely tune the plugin to meet their needs. Extensions include: - <> - <> - <> - <> - <> - <> - <> [#clone-extensions] === Clone Extensions Clone extensions modify the git operations that retrieve remote changes into the agent workspace. The extensions can adjust the amount of history retrieved, how long the retrieval is allowed to run, and other retrieval details. [#advanced-clone-behaviours] ==== Advanced clone behaviours image:/images/git-advanced-clone-behaviours.png[Advanced clone behaviours] Advanced clone behaviors modify the `link:https://git-scm.com/docs/git-clone[git clone]` and `link:https://git-scm.com/docs/git-fetch[git fetch]` commands. They control: * breadth of history retrieval (refspecs) * depth of history retrieval (shallow clone) * disc space use (reference repositories) * duration of the command (timeout) * tag retrieval Advanced clone behaviors include: [[honor-refspec-on-initial-clone]] Honor refspec on initial clone:: Perform initial clone using the refspec defined for the repository. This can save time, data transfer and disk space when you only need to access the references specified by the refspec. If this is not enabled, then the plugin default refspec includes **all** remote branches. Shallow clone:: Perform a shallow clone by requesting a limited number of commits from the tip of the requested branch(es). Git will not download the complete history of the project. This can save time and disk space when you just want to access the latest version of a repository. Shallow clone depth:: Set shallow clone depth to the specified number of commits. Git will only download `depth` commits from the remote repository, saving time and disk space. Path of the reference repo to use during clone:: Specify a folder containing a repository that will be used by git as a reference during clone operations. This option will be ignored if the folder is not available on the agent. Timeout (in minutes) for clone and fetch operations:: Specify a timeout (in minutes) for clone and fetch operations. Fetch tags:: Deselect this to perform a clone without tags, saving time and disk space when you want to access only what is specified by the refspec, without considering any repository tags. [#prune-stale-remote-tracking-branches] ==== Prune stale remote tracking branches image:/images/git-prune-stale-remote-tracking-branches.png[Prune stale remote tracking branches] Removes remote tracking branches from the local workspace if they no longer exist on the remote. See `link:https://git-scm.com/docs/git-remote#Documentation/git-remote.txt-empruneem[git remote prune]` and `link:https://git-scm.com/docs/git-fetch#_pruning[git fetch --prune]` for more details. [#prune-stale-tags] ==== Prune stale tags image:/images/git-prune-stale-tags.png[Prune stale tags] Removes tags from the local workspace before fetch if they no longer exist on the remote. If stale tags are not pruned, deletion of a remote tag will not remove the local tag in the workspace. If the local tag already exists in the workspace, git correctly refuses to create the tag again. Pruning stale tags allows the local workspace to create a tag with the same name as a tag which was removed from the remote. [#checkout-extensions] === Checkout Extensions Checkout extensions modify the git operations that place files in the workspace from the git repository on the agent. The extensions can adjust the maximum duration of the checkout operation, the use and behavior of git submodules, the location of the workspace on the disc, and more. [#advanced-checkout-behaviors] ==== Advanced checkout behaviors image:/images/git-advanced-checkout-behaviors.png[Advanced checkout behaviors] Advanced checkout behaviors modify the `link:https://git-scm.com/docs/git-checkout[git checkout]` command. Advanced checkout behaviors include Timeout (in minutes) for checkout operation:: Specify a timeout (in minutes) for checkout. The checkout is stopped if the timeout is exceeded. Checkout timeout is usually only required with slow file systems or large repositories. [#advanced-sub-modules-behaviours] ==== Advanced sub-modules behaviours image:/images/git-advanced-sub-modules-behaviours.png[Advanced sub-modules behaviours] Advanced sub-modules behaviors modify the `link:https://git-scm.com/docs/git-submodule[git submodule]` commands. They control: * depth of history retrieval (shallow clone) * disc space use (reference repositories) * credential use * duration of the command (timeout) * concurrent threads used to fetch submodules Advanced sub-modules include: Disable submodules processing:: Ignore submodules in the repository. Recursively update submodules:: Retrieve all submodules recursively. Without this option, submodules which contain other submodules will ignore the contained submodules. Update tracking submodules to tip of branch:: Retrieve the tip of the configured branch in .gitmodules. Use credentials from default remote of parent repository:: Use credentials from the default remote of the parent project. Submodule updates do not use credentials by default. Enabling this extension will provide the parent repository credentials to each of the submodule repositories. Submodule credentials require that the submodule repository must accept the same credentials as the parent project. If the parent project is cloned with https, then the authenticated submodule references must use https as well. If the parent project is cloned with ssh, then the authenticated submodule references must use ssh as well. Path of the reference repo to use during submodule update:: Folder containing a repository that will be used by git as a reference during submodule clone operations. This option will be ignored if the folder is not available on the agent running the build. A reference repository may contain multiple subprojects. See the combining repositories section for more details. Timeout (in minutes) for submodule operations:: Specify a timeout (in minutes) for submodules operations. This option overrides the default timeout. Number of threads to use when updating submodules:: Number of parallel processes to be used when updating submodules. Default is to use a single thread for submodule updates Shallow clone:: Perform shallow clone of submodules. Git will not download the complete history of the project, saving time and disk space. Shallow clone depth:: Set shallow clone depth for submodules. Git will only download recent history of the project, saving time and disk space. [#checkout-to-a-sub-directory] ==== Checkout to a sub-directory image:/images/git-checkout-to-a-sub-directory.png[Checkout to a sub-directory] Checkout to a subdirectory of the workspace instead of using the workspace root. This extension should **not** be used in Jenkins Pipeline (either declarative or scripted). Jenkins Pipeline already provides standard techniques for checkout to a subdirectory. Use `ws` and `dir` in Jenkins Pipeline rather than this extension. Local subdirectory for repo:: Name of the local directory (relative to the workspace root) for the git repository checkout. If left empty, the workspace root itself will be used. [#checkout-to-specific-local-branch] ==== Checkout to specific local branch image:/images/git-checkout-to-specific-local-branch.png[Checkout to specific local branch] Branch name:: If given, checkout the revision to build as HEAD on the named branch. If value is an empty string or ""**"", then the branch name is computed from the remote branch without the origin. In that case, a remote branch 'origin/master' will be checked out to a local branch named 'master', and a remote branch 'origin/develop/new-feature' will be checked out to a local branch named 'develop/new-feature'. If a specific revision and not branch HEAD is checked out, then 'detached' will be used as the local branch name. [#wipe-out-repository-and-force-clone] ==== Wipe out repository and force clone image:/images/git-wipe-out-repository-and-force-clone.png[Wipe out repository and force clone] Delete the contents of the workspace before build and before checkout. Deletes the git repository inside the workspace and will force a full clone. [clean-after-checkout] ==== Clean after checkout image:/images/git-clean-after-checkout.png[Clean after checkout] Clean the workspace *after* every checkout by deleting all untracked files and directories, including those which are specified in `.gitignore`. Resets all tracked files to their versioned state. Ensures that the workspace is in the same state as if clone and checkout were performed in a new workspace. Reduces the risk that current build will be affected by files generated by prior builds. Does not remove files outside the workspace (like temporary files or cache files). Does not remove files in the `.git` repository of the workspace. Delete untracked nested repositories:: Remove subdirectories which contain `.git` subdirectories if this option is enabled. This is implemented in command line git as `git clean -xffd`. Refer to the link:https://git-scm.com/docs/git-clean[git clean manual page] for more information. [#clean-before-checkout] ==== Clean before checkout image:/images/git-clean-before-checkout.png[Clean before checkout] Clean the workspace *before* every checkout by deleting all untracked files and directories, including those which are specified in .gitignore. Resets all tracked files to their versioned state. Ensures that the workspace is in the same state as if cloned and checkout were performed in a new workspace. Reduces the risk that current build will be affected by files generated by prior builds. Does not remove files outside the workspace (like temporary files or cache files). Does not remove files in the `.git` repository of the workspace. Delete untracked nested repositories:: Remove subdirectories which contain `.git` subdirectories if this option is enabled. This is implemented in command line git as `git clean -xffd`. Refer to the link:https://git-scm.com/docs/git-clean[git clean manual page] for more information. [#sparse-checkout-paths] ==== Sparse checkout paths image:/images/git-sparse-checkout-paths.png[Sparse checkout paths] Specify the paths that you'd like to sparse checkout. This may be used for saving space (Think about a reference repository). Be sure to use a recent version of Git, at least above 1.7.10. Multiple sparse checkout path values can be added to a single job. Path:: File or directory to be included in the checkout [#git-lfs-pull-after-checkout] ==== Git LFS pull after checkout image:/images/git-lfs-pull-after-checkout.png[Git LFS pull after checkout] Enable https://git-lfs.github.com/[git large file support] for the workspace by pulling large files after the checkout completes. Requires that the controller and each agent performing an LFS checkout have installed `git lfs`. [#changelog-extensions] === Changelog Extensions The plugin can calculate the source code differences between two builds. Changelog extensions adapt the changelog calculations for different cases. [#calculate-changelog-against-a-specific-branch] ==== Calculate changelog against a specific branch image:/images/git-calculate-changelog-against-a-specific-branch.png[Calculate changelog against a specific branch] 'Calculate changelog against a specific branch' uses the specified branch to compute the changelog instead of computing it based on the previous build. This extension can be useful for computing changes related to a known base branch, especially in environments which do not have the concept of a ""pull request"". Name of repository:: Name of the repository, such as 'origin', that contains the branch. Name of branch:: Name of the branch used for the changelog calculation within the named repository. [#use-commit-author-in-changelog] ==== Use commit author in changelog image:/images/git-use-commit-author-in-changelog.png[Use commit author in changelog] The default behavior is to use the Git commit's ""Committer"" value in build changesets. If this option is selected, the git commit's ""Author"" value is used instead. [#tagging-extensions] === Tagging Extensions [#create-a-tag-for-every-build] ==== Create a tag for every build image:/images/git-create-a-tag-for-every-build.png[Create a tag for every build] Create a tag in the workspace for every build to unambiguously mark the commit that was built. You can combine this with Git publisher to push the tags to the remote repository. [#build-initiation-extensions] === Build Initiation Extensions The git plugin can start builds based on many different conditions. The build inititation extensions control the conditions that start a build. They can ignore notifications of a change or force a deeper evaluation of the commits when polling [#dont-trigger-a-build-on-commit-notifications] ==== Don't trigger a build on commit notifications image:/images/git-do-not-trigger-a-build-on-commit-notifications.png[Do not trigger a build on commit notifications] If checked, this repository will be ignored when the notifyCommit URL is accessed whether the repository matches or not. [#force-polling-using-workspace] ==== Force polling using workspace image:/images/git-force-polling-using-workspace.png[Force polling using workspace] The git plugin polls remotely using `ls-remote` when configured with a single branch (no wildcards!). When this extension is enabled, the polling is performed from a cloned copy of the workspace instead of using `ls-remote`. If this option is selected, polling will use a workspace instead of using `ls-remote`. By default, the plugin polls by executing a polling process or thread on the Jenkins master. If the Jenkins controller does not have a git installation, the administrator may <> to use a pure Java git implementation for polling. In addition, the administrator may need to <> to prevent use of command line git on the Jenkins master. [#polling-ignores-commits-from-certain-users] ==== Polling ignores commits from certain users image:/images/git-polling-ignores-commits-from-certain-users.png[Polling ignores commits from certain users] These options allow you to perform a merge to a particular branch before building. For example, you could specify an integration branch to be built, and to merge to master. In this scenario, on every change of integration, Jenkins will perform a merge with the master branch, and try to perform a build if the merge is successful. It then may push the merge back to the remote repository if the Git Push post-build action is selected. Excluded Users:: If set and Jenkins is configured to poll for changes, Jenkins will ignore any revisions committed by users in this list when determining if a build should be triggered. This can be used to exclude commits done by the build itself from triggering another build, assuming the build server commits the change with a distinct SCM user. Using this behavior prevents the faster `git ls-remote` polling mechanism. It forces polling to require a workspace, as if you had selected the <> extension. Each exclusion uses exact string comparison and must be separated by a new line. User names are only excluded if they exactly match one of the names in this list. [#polling-ignores-commits-in-certain-paths] ==== Polling ignores commits in certain paths image:/images/git-polling-ignores-commits-in-certain-paths.png[Polling ignores commits in certain paths] If set and Jenkins is configured to poll for changes, Jenkins will pay attention to included and/or excluded files and/or folders when determining if a build needs to be triggered. Using this behavior will preclude the faster remote polling mechanism, forcing polling to require a workspace thus sometimes triggering unwanted builds, as if you had selected the <> extension as well. This can be used to exclude commits done by the build itself from triggering another build, assuming the build server commits the change with a distinct SCM user. Using this behavior will preclude the faster git ls-remote polling mechanism, forcing polling to require a workspace, as if you had selected the <> extension as well. Included Regions:: Each inclusion uses java regular expression pattern matching, and must be separated by a new line. An empty list implies that everything is included. Excluded Regions:: Each exclusion uses java regular expression pattern matching, and must be separated by a new line. An empty list excludes nothing. [#polling-ignores-commits-with-certain-messages] ==== Polling ignores commits with certain messages image:/images/git-polling-ignores-commits-with-certain-messages.png[Polling ignores commits with certain messages] Excluded Messages:: If set and Jenkins is set to poll for changes, Jenkins will ignore any revisions committed with message matched to the regular expression pattern when determining if a build needs to be triggered. This can be used to exclude commits done by the build itself from triggering another build, assuming the build server commits the change with a distinct message. You can create more complex patterns using embedded flag expressions. [#strategy-for-choosing-what-to-build] ==== Strategy for choosing what to build image:/images/git-strategy-for-choosing-what-to-build.png[Strategy for choosing what to build] When you are interested in using a job to build multiple branches, you can choose how Jenkins chooses the branches to build and the order they should be built. This extension point in Jenkins is used by many other plugins to control the job as it builds specific commits. When you activate those plugins, you may see them installing a custom build strategy. Ancestry:: Maximum Age of Commit:: The maximum age of a commit (in days) for it to be built. This uses the GIT_COMMITTER_DATE, not GIT_AUTHOR_DATE Commit in Ancestry:: If an ancestor commit (SHA-1) is provided, only branches with this commit in their history will be built. Default:: Build all the branches that match the branch name pattern. Inverse:: Build all branches except for those which match the branch specifiers configure above. This is useful, for example, when you have jobs building your master and various release branches and you want a second job which builds all new feature branches. For example, branches which do not match these patterns without redundantly building master and the release branches again each time they change. [#merge-extensions] === Merge Extensions The git plugin can optionally merge changes from other branches into the current branch of the agent workspace. Merge extensions control the source branch for the merge and the options applied to the merge. [#merge-before-build] ==== Merge before build image:/images/git-merge-before-build.png[Merge before build] These options allow you to perform a merge to a particular branch before building. For example, you could specify an integration branch to be built, and to merge to master. In this scenario, on every change of integration, Jenkins will perform a merge with the master branch, and try to perform a build if the merge is successful. It then may push the merge back to the remote repository if the <> is selected. Name of repository:: Name of the repository, such as origin, that contains the branch. If left blank, it'll default to the name of the first repository configured. Branch to merge to:: The name of the branch within the named repository to merge to, such as master. Merge strategy:: Merge strategy selection. Choices include: * default * resolve * recursive * octopus * ours * subtree * recursive_theirs Fast-forward mode:: * `--ff`: fast-forward which gracefully falls back to a merge commit when required * `-ff-only`: fast-forward without any fallback * `--no-ff`: merge commit always, even if a fast-forward would have been allowed [#custom-user-name-e-mail-address] ==== Custom user name/e-mail address image:/images/git-custom-user-name-e-mail-address.png[Custom user name/e-mail address] user.name:: Defines the user name value which git will assign to new commits made in the workspace. If given, the environment variables `GIT_COMMITTER_NAME` and `GIT_AUTHOR_NAME` are set for builds and override values from the global settings. user.email:: Defines the user email value which git will assign to new commits made in the workspace. If given, the environment variables `GIT_COMMITTER_EMAIL` and `GIT_AUTHOR_EMAIL` are set for builds and override values from the global settings. [#deprecated-extensions] === Deprecated Extensions [#custom-scm-name---deprecated] ==== Custom SCM name - *Deprecated* Unique name for this SCM. Was needed when using Git within the Multi SCM plugin. Pipeline is the robust and feature-rich way to checkout from multiple repositories in a single job. [#submodule-combinator---removed] ==== Submodule Combinator - *Removed* An experiment was created many years ago that attempted to create combinations of submodules within the Jenkins job. The experiment was never available to Freestyle projects or other legacy projects like multi-configuration projects. It was visible in Pipeline, configuration as code, and JobDSL. The implementation of the experiment has been removed. Dependabot and other configuration tools are better suited to evaluate submodule combinations. There are no known uses of the submodule combinator and no open Jira issues reported against the submodule combinator. Those who were using submodule combinator should remain with git plugin versions prior to 4.6.0. The submodule combinator ignores any user provided value of the following arguments to git's `checkout scm`: doGenerateSubmoduleConfigurations:: A boolean that is now always set to `false`. Submodule configurations are no longer evaluated by the git plugin. submoduleCfg:: A list of submodule names and branches that is now always empty. Submodule configurations are no longer evaluated by the git plugin. Previous Pipeline syntax looked like this: ```groovy checkout([$class: 'GitSCM', branches: [[name: 'master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin']]]) ``` Current Pipeline Syntax looks like this: ```groovy checkout([$class: 'GitSCM', branches: [[name: 'master']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin']]]) ``` [#environment-variables] == Environment Variables The git plugin assigns values to environment variables in several contexts. Environment variables are assigned in Freestyle, Pipeline, Multibranch Pipeline, and Organization Folder projects. [#branch-variables] === Branch Variables GIT_BRANCH:: Name of branch being built including remote name, as in `origin/master` GIT_LOCAL_BRANCH:: Name of branch being built without remote name, as in `master` [#commit-variables] === Commit Variables GIT_COMMIT:: SHA-1 of the commit used in this build GIT_PREVIOUS_COMMIT:: SHA-1 of the commit used in the preceding build of this project GIT_PREVIOUS_SUCCESSFUL_COMMIT:: SHA-1 of the commit used in the most recent successful build of this project [#system-configuration-variables] === System Configuration Variables GIT_URL:: Remote URL of the first git repository in this workspace GIT_URL_n:: Remote URL of the additional git repositories in this workspace (if any) GIT_AUTHOR_EMAIL:: Author e-mail address that will be used for **new commits in this workspace** GIT_AUTHOR_NAME:: Author name that will be used for **new commits in this workspace** GIT_COMMITTER_EMAIL:: Committer e-mail address that will be used for **new commits in this workspace*** GIT_COMMITTER_NAME:: Committer name that will be used for **new commits in this workspace** [#properties] == Properties Some git plugin settings can only be controlled from command line properties set at Jenkins startup. [#default-timeout] === Default Timeout The default git timeout value (in minutes) can be overridden by the `org.jenkinsci.plugins.gitclient.Git.timeOut` property (see https://issues.jenkins-ci.org/browse/JENKINS-11286[JENKINS-11286]). The property should be set on the controller and on all agents to have effect (see https://issues.jenkins-ci.org/browse/JENKINS-22547[JENKINS-22547]). [[GitPlugin-WhyNotJGit]] Command line git is the reference git implementation in the git plugin and the git client plugin. Command line git provides the most functionality and is the most stable implementation. Some installations may not want to install command line git and may want to disable the command line git implementation. Administrators may disable command line git with the property `org.jenkinsci.plugins.gitclient.Git.useCLI=false`. [#git-publisher] == Git Publisher The Jenkins git plugin provides a ""git publisher"" as a post-build action. The git publisher can push commits or tags from the workspace of a Freestyle project to the remote repository. The git publisher is **only available** for Freestyle projects. It is **not available** for Pipeline, Multibranch Pipeline, Organization Folder, or any other job type other than Freestyle. [#git-publisher-options] === Git Publisher Options The git publisher behaviors are controlled by options that can be configured as part of the Jenkins job. Options include; Push Only If Build Succeeds:: Only push changes from the workspace to the remote repository if the build succeeds. If the build status is unstable, failed, or canceled, the changes from the workspace will not be pushed. [[publisher-push-merge-results]] Merge Results:: If pre-build merging is configured through one of the <>, then enabling this checkbox will push the merge to the remote repository. [[publisher-tag-force-push]] Force Push:: Git refuses to replace a remote commit with a different commit. This prevents accidental overwrite of new commits on the remote repository. However, there may be times when overwriting commits on the remote repository is acceptable and even desired. If the commits from the local workspace should overwrite commits on the remote repository, enable this option. It will request that the remote repository destroy history and replace it with history from the workspace. [#git-publisher-tags-options] ==== Git publisher tags options The git publisher can push tags from the workspace to the remote repository. Options in this section will allow the plugin to create a new tag. Options will also allow the plugin to update an existing tag, though the link:https://git-scm.com/docs/git-tag#_on_re_tagging[git documentation] **strongly advises** against updating tags. Tag to push:: Name of the tag to be pushed from the local workspace to the remote repository. The name may include link:https://jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables[Jenkins environment variables] or may be a fixed string. For example, the tag to push might be `$BUILD_TAG`, `my-tag-$BUILD_NUMBER`, `build-$BUILD_NUMBER-from-$NODE_NAME`, or `a-very-specific-string-that-will-be-used-once`. Tag message:: If the option is selected to create a tag or update a tag, then this message will be associated with the tag that is created. The message will expand references to link:https://jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables[Jenkins environment variables]. For example, the message `Build $BUILD_NUMBER tagged on $NODE_NAME` will use the message `Build 1 tagged on master` if build 1 of the job runs on the master. Create new tag:: Create a new tag in the workspace. The git publisher will fail the job if the tag already exists. Update new tag:: Modify existing tag in the workspace so that it points to the most recent commit. Many git repository hosting services will reject attempts to push a tag which has been modified to point to a different commit than its original commit. Refer to <> for an option which may force the remote repository to accept a modified tag. The link:https://git-scm.com/docs/git-tag#_on_re_tagging[git documentation] **strongly advises against updating tags**. Tag remote name:: Git uses the 'remote name' as a short string replacement for the full URL of the remote repository. This option defines which remote should receive the push. This is typically `origin`, though it could be any one of the remote names defined when the plugin performs the checkout. [#git-publisher-branches-options] ==== Git publisher branches options The git publisher can push branches from the workspace to the remote repository. Options in this section will allow the plugin to push the contents of a local branch to the remote repository. Branch to push:: The name of the remote branch that will receive the latest commits from the agent workspace. This is usually the same branch that was used for the checkout Target remote name:: The shortname of the remote that will receive the latest commits from the agent workspace. Usually this is `origin`. It needs to be a shortname that is defined in the agent workspace, either through the initial checkout or through later configuration. Rebase before push:: Some Jenkins jobs may be blocked from pushing changes to the remote repository because the remote repository has received new commits since the start of the job. This may happen with projects that receive many commits or with projects that have long running jobs. The `Rebase before push` option fetches the most recent commits from the remote repository, applies local changes over the most recent commits, then pushes the result. The plugin uses `git rebase` to apply the local changes over the most recent remote changes. + Because `Rebase before push` is modifying the commits in the agent workspace **after the job has completed**, it is creating a configuration of commits that has **not been evaluated by any Jenkins job**. The commits in the local workspace have been evaluated by the job. The most recent commits from the remote repository have not been evaluated by the job. Users may find that the risk of pushing an untested configuration is less than the risk of delaying the visibility of the changes which have been evaluated by the job. [#combining-repositories] == Combining repositories A single reference repository may contain commits from multiple repositories. For example, if a repository named `parent` includes references to submodules `child-1` and `child-2`, a reference repository could be created to cache commits from all three repositories using the commands: .... $ mkdir multirepository-cache.git $ cd multirepository-cache.git $ git init --bare $ git remote add parent https://github.com/jenkinsci/git-plugin $ git remote add child-1 https://github.com/jenkinsci/git-client-plugin $ git remote add child-2 https://github.com/jenkinsci/platformlabeler-plugin $ git fetch --all .... Those commands create a single bare repository with the current commits from all three repositories. If that reference repository is used in the advanced clone options link:#clone-reference-repository-path[clone reference repository], it will reduce data transfer and disc use for the parent repository. If that reference repository is used in the submodule options link:#submodule-reference-repository-path[clone reference repository], it will reduce data transfer and disc use for the submodule repositories. [#bug-reports] == Bug Reports Report issues and enhancements in the https://issues.jenkins-ci.org[Jenkins issue tracker]. [#contributing-to-the-plugin] == Contributing to the Plugin Refer to link:CONTRIBUTING.adoc#contributing-to-the-git-plugin[contributing to the plugin] for contribution guidelines. Refer to link:Priorities.adoc#git-plugin-development-priorities[plugin development priorities] for the prioritized list of development topics. == Remove Git Plugin BuildsByBranch BuildData Script This script is used to remove the static list of BuildsByBranch that is stored for each build by the Git Plugin. This is a workaround for link:https://issues.jenkins-ci.org/browse/JENKINS-19022[JENKINS-19022] [source,groovy] ---- import hudson.matrix.* import hudson.model.* hudsonInstance = hudson.model.Hudson.instance jobNames = hudsonInstance.getJobNames() allItems = [] for (name in jobNames) { allItems += hudsonInstance.getItemByFullName(name) } // Iterate over all jobs and find the ones that have a hudson.plugins.git.util.BuildData // as an action. // // We then clean it by removing the useless array action.buildsByBranchName // for (job in allItems) { println(""job: "" + job.name); def counter = 0; for (build in job.getBuilds()) { // It is possible for a build to have multiple BuildData actions // since we can use the Mulitple SCM plugin. def gitActions = build.getActions(hudson.plugins.git.util.BuildData.class) if (gitActions != null) { for (action in gitActions) { action.buildsByBranchName = new HashMap(); hudson.plugins.git.Revision r = action.getLastBuiltRevision(); if (r != null) { for (branch in r.getBranches()) { action.buildsByBranchName.put(branch.getName(), action.lastBuild) } } build.actions.remove(action) build.actions.add(action) build.save(); counter++; } } if (job instanceof MatrixProject) { def runcounter = 0; for (run in build.getRuns()) { gitActions = run.getActions(hudson.plugins.git.util.BuildData.class) if (gitActions != null) { for (action in gitActions) { action.buildsByBranchName = new HashMap(); hudson.plugins.git.Revision r = action.getLastBuiltRevision(); if (r != null) { for (branch in r.getBranches()) { action.buildsByBranchName.put(branch.getName(), action.lastBuild) } } run.actions.remove(action) run.actions.add(action) run.save(); runcounter++; } } } if (runcounter > 0) { println("" -->> cleaned: "" + runcounter + "" runs""); } } } if (counter > 0) { println(""-- cleaned: "" + counter + "" builds""); } } ---- ",12049,False,2005.666762413954,median "/*========================================================================= Program: Visualization Toolkit Module: vtkPolyData.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include ""vtkPolyData.h"" #include ""vtkCellArray.h"" #include ""vtkCellData.h"" #include ""vtkCriticalSection.h"" #include ""vtkEmptyCell.h"" #include ""vtkGenericCell.h"" #include ""vtkInformation.h"" #include ""vtkInformationVector.h"" #include ""vtkLine.h"" #include ""vtkNew.h"" #include ""vtkObjectFactory.h"" #include ""vtkPointData.h"" #include ""vtkPointLocator.h"" #include ""vtkPolyLine.h"" #include ""vtkPolyVertex.h"" #include ""vtkPolygon.h"" #include ""vtkQuad.h"" #include ""vtkTriangle.h"" #include ""vtkTriangleStrip.h"" #include ""vtkVertex.h"" #include ""vtkSmartPointer.h"" vtkStandardNewMacro(vtkPolyData); //---------------------------------------------------------------------------- // Initialize static member. This member is used to simplify traversal // of verts, lines, polygons, and triangle strips lists. It basically // ""marks"" empty lists so that the traveral method ""GetNextCell"" // works properly. struct vtkPolyDataDummyContainter { vtkSmartPointer Dummy; vtkPolyDataDummyContainter() { this->Dummy.TakeReference(vtkCellArray::New()); } }; vtkPolyDataDummyContainter vtkPolyData::DummyContainer; vtkPolyData::vtkPolyData () : Vertex(NULL), PolyVertex(NULL), Line(NULL), PolyLine(NULL), Triangle(NULL), Quad(NULL), Polygon(NULL), TriangleStrip(NULL), EmptyCell(NULL), Verts(NULL), Lines(NULL), Polys(NULL), Strips(NULL), Cells(NULL), Links(NULL) { this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_PIECES_EXTENT); this->Information->Set(vtkDataObject::DATA_PIECE_NUMBER(), -1); this->Information->Set(vtkDataObject::DATA_NUMBER_OF_PIECES(), 1); this->Information->Set(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS(), 0); } //---------------------------------------------------------------------------- vtkPolyData::~vtkPolyData() { this->Cleanup(); if (this->Vertex) { this->Vertex->Delete(); } if (this->PolyVertex) { this->PolyVertex->Delete(); } if (this->Line) { this->Line->Delete(); } if (this->PolyLine) { this->PolyLine->Delete(); } if (this->Triangle) { this->Triangle->Delete(); } if (this->Quad) { this->Quad->Delete(); } if (this->Polygon) { this->Polygon->Delete(); } if (this->TriangleStrip) { this->TriangleStrip->Delete(); } if (this->EmptyCell) { this->EmptyCell->Delete(); } } //---------------------------------------------------------------------------- int vtkPolyData::GetPiece() { return this->Information->Get(vtkDataObject::DATA_PIECE_NUMBER()); } //---------------------------------------------------------------------------- int vtkPolyData::GetNumberOfPieces() { return this->Information->Get(vtkDataObject::DATA_NUMBER_OF_PIECES()); } //---------------------------------------------------------------------------- int vtkPolyData::GetGhostLevel() { return this->Information->Get(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS()); } //---------------------------------------------------------------------------- // Copy the geometric and topological structure of an input poly data object. void vtkPolyData::CopyStructure(vtkDataSet *ds) { vtkPolyData *pd=static_cast(ds); vtkPointSet::CopyStructure(ds); if (this->Verts != pd->Verts) { if (this->Verts) { this->Verts->UnRegister(this); } this->Verts = pd->Verts; if (this->Verts) { this->Verts->Register(this); } } if (this->Lines != pd->Lines) { if (this->Lines) { this->Lines->UnRegister(this); } this->Lines = pd->Lines; if (this->Lines) { this->Lines->Register(this); } } if (this->Polys != pd->Polys) { if (this->Polys) { this->Polys->UnRegister(this); } this->Polys = pd->Polys; if (this->Polys) { this->Polys->Register(this); } } if (this->Strips != pd->Strips) { if (this->Strips) { this->Strips->UnRegister(this); } this->Strips = pd->Strips; if (this->Strips) { this->Strips->Register(this); } } if ( this->Cells ) { this->Cells->UnRegister(this); this->Cells = NULL; } if ( this->Links ) { this->Links->UnRegister(this); this->Links = NULL; } } //---------------------------------------------------------------------------- int vtkPolyData::GetCellType(vtkIdType cellId) { if ( !this->Cells ) { this->BuildCells(); } return this->Cells->GetCellType(cellId); } //---------------------------------------------------------------------------- vtkCell *vtkPolyData::GetCell(vtkIdType cellId) { int i, loc; vtkIdType *pts, numPts; vtkCell *cell = NULL; unsigned char type; if ( !this->Cells ) { this->BuildCells(); } type = this->Cells->GetCellType(cellId); loc = this->Cells->GetCellLocation(cellId); switch (type) { case VTK_VERTEX: if (!this->Vertex) { this->Vertex = vtkVertex::New(); } cell = this->Vertex; this->Verts->GetCell(loc,numPts,pts); break; case VTK_POLY_VERTEX: if (! this->PolyVertex) { this->PolyVertex = vtkPolyVertex::New(); } cell = this->PolyVertex; this->Verts->GetCell(loc,numPts,pts); cell->PointIds->SetNumberOfIds(numPts); //reset number of points cell->Points->SetNumberOfPoints(numPts); break; case VTK_LINE: if (! this->Line ) { this->Line = vtkLine::New(); } cell = this->Line; this->Lines->GetCell(loc,numPts,pts); break; case VTK_POLY_LINE: if (!this->PolyLine) { this->PolyLine = vtkPolyLine::New(); } cell = this->PolyLine; this->Lines->GetCell(loc,numPts,pts); cell->PointIds->SetNumberOfIds(numPts); //reset number of points cell->Points->SetNumberOfPoints(numPts); break; case VTK_TRIANGLE: if (!this->Triangle) { this->Triangle = vtkTriangle::New(); } cell = this->Triangle; this->Polys->GetCell(loc,numPts,pts); break; case VTK_QUAD: if (!this->Quad) { this->Quad = vtkQuad::New(); } cell = this->Quad; this->Polys->GetCell(loc,numPts,pts); break; case VTK_POLYGON: if (!this->Polygon) { this->Polygon = vtkPolygon::New(); } cell = this->Polygon; this->Polys->GetCell(loc,numPts,pts); cell->PointIds->SetNumberOfIds(numPts); //reset number of points cell->Points->SetNumberOfPoints(numPts); break; case VTK_TRIANGLE_STRIP: if (!this->TriangleStrip) { this->TriangleStrip = vtkTriangleStrip::New(); } cell = this->TriangleStrip; this->Strips->GetCell(loc,numPts,pts); cell->PointIds->SetNumberOfIds(numPts); //reset number of points cell->Points->SetNumberOfPoints(numPts); break; default: if (!this->EmptyCell) { this->EmptyCell = vtkEmptyCell::New(); } cell = this->EmptyCell; return cell; } for (i=0; i < numPts; i++) { cell->PointIds->SetId(i,pts[i]); cell->Points->SetPoint(i,this->Points->GetPoint(pts[i])); } return cell; } //---------------------------------------------------------------------------- void vtkPolyData::GetCell(vtkIdType cellId, vtkGenericCell *cell) { int i, loc; vtkIdType *pts=0; vtkIdType numPts; unsigned char type; double x[3]; if ( !this->Cells ) { this->BuildCells(); } type = this->Cells->GetCellType(cellId); loc = this->Cells->GetCellLocation(cellId); switch (type) { case VTK_VERTEX: cell->SetCellTypeToVertex(); this->Verts->GetCell(loc,numPts,pts); break; case VTK_POLY_VERTEX: cell->SetCellTypeToPolyVertex(); this->Verts->GetCell(loc,numPts,pts); cell->PointIds->SetNumberOfIds(numPts); //reset number of points cell->Points->SetNumberOfPoints(numPts); break; case VTK_LINE: cell->SetCellTypeToLine(); this->Lines->GetCell(loc,numPts,pts); break; case VTK_POLY_LINE: cell->SetCellTypeToPolyLine(); this->Lines->GetCell(loc,numPts,pts); cell->PointIds->SetNumberOfIds(numPts); //reset number of points cell->Points->SetNumberOfPoints(numPts); break; case VTK_TRIANGLE: cell->SetCellTypeToTriangle(); this->Polys->GetCell(loc,numPts,pts); break; case VTK_QUAD: cell->SetCellTypeToQuad(); this->Polys->GetCell(loc,numPts,pts); break; case VTK_POLYGON: cell->SetCellTypeToPolygon(); this->Polys->GetCell(loc,numPts,pts); cell->PointIds->SetNumberOfIds(numPts); //reset number of points cell->Points->SetNumberOfPoints(numPts); break; case VTK_TRIANGLE_STRIP: cell->SetCellTypeToTriangleStrip(); this->Strips->GetCell(loc,numPts,pts); cell->PointIds->SetNumberOfIds(numPts); //reset number of points cell->Points->SetNumberOfPoints(numPts); break; default: cell->SetCellTypeToEmptyCell(); numPts = 0; } for (i=0; i < numPts; i++) { cell->PointIds->SetId(i,pts[i]); this->Points->GetPoint(pts[i], x); cell->Points->SetPoint(i, x); } } //---------------------------------------------------------------------------- void vtkPolyData::CopyCells(vtkPolyData *pd, vtkIdList *idList, vtkPointLocator *locator) { vtkIdType cellId, ptId, newId, newCellId, locatorPtId; int numPts, numCellPts, i; vtkPoints *newPoints; vtkIdList *pointMap = vtkIdList::New(); //maps old pt ids into new vtkIdList *cellPts, *newCellPts = vtkIdList::New(); vtkGenericCell *cell = vtkGenericCell::New(); double x[3]; vtkPointData *outPD = this->GetPointData(); vtkCellData *outCD = this->GetCellData(); numPts = pd->GetNumberOfPoints(); if (this->GetPoints() == NULL) { this->Points = vtkPoints::New(); } newPoints = this->GetPoints(); pointMap->SetNumberOfIds(numPts); for (i=0; i < numPts; i++) { pointMap->SetId(i,-1); } // Filter the cells for (cellId=0; cellId < idList->GetNumberOfIds(); cellId++) { pd->GetCell(idList->GetId(cellId), cell); cellPts = cell->GetPointIds(); numCellPts = cell->GetNumberOfPoints(); for (i=0; i < numCellPts; i++) { ptId = cellPts->GetId(i); if ( (newId = pointMap->GetId(ptId)) < 0 ) { pd->GetPoint(ptId, x); if (locator != NULL) { if ((locatorPtId = locator->IsInsertedPoint(x)) == -1) { newId = newPoints->InsertNextPoint(x); locator->InsertNextPoint(x); pointMap->SetId(ptId, newId); outPD->CopyData(pd->GetPointData(), ptId, newId); } else { newId = locatorPtId; } } else { newId = newPoints->InsertNextPoint(x); pointMap->SetId(ptId, newId); outPD->CopyData(pd->GetPointData(), ptId, newId); } } newCellPts->InsertId(i,newId); } newCellId = this->InsertNextCell(cell->GetCellType(), newCellPts); outCD->CopyData(pd->GetCellData(), idList->GetId(cellId), newCellId); newCellPts->Reset(); } // for all cells newCellPts->Delete(); pointMap->Delete(); cell->Delete(); } //---------------------------------------------------------------------------- // Fast implementation of GetCellBounds(). Bounds are calculated without // constructing a cell. void vtkPolyData::GetCellBounds(vtkIdType cellId, double bounds[6]) { int i, loc; vtkIdType *pts, numPts; unsigned char type; double x[3]; if ( !this->Cells ) { this->BuildCells(); } type = this->Cells->GetCellType(cellId); loc = this->Cells->GetCellLocation(cellId); switch (type) { case VTK_VERTEX: case VTK_POLY_VERTEX: this->Verts->GetCell(loc,numPts,pts); break; case VTK_LINE: case VTK_POLY_LINE: this->Lines->GetCell(loc,numPts,pts); break; case VTK_TRIANGLE: case VTK_QUAD: case VTK_POLYGON: this->Polys->GetCell(loc,numPts,pts); break; case VTK_TRIANGLE_STRIP: this->Strips->GetCell(loc,numPts,pts); break; default: bounds[0] = bounds[1] = bounds[2] = bounds[3] = bounds[4] = bounds[5] = 0.0; return; } // carefully compute the bounds if (numPts) { this->Points->GetPoint( pts[0], x ); bounds[0] = x[0]; bounds[2] = x[1]; bounds[4] = x[2]; bounds[1] = x[0]; bounds[3] = x[1]; bounds[5] = x[2]; for (i=1; i < numPts; i++) { this->Points->GetPoint( pts[i], x ); bounds[0] = (x[0] < bounds[0] ? x[0] : bounds[0]); bounds[1] = (x[0] > bounds[1] ? x[0] : bounds[1]); bounds[2] = (x[1] < bounds[2] ? x[1] : bounds[2]); bounds[3] = (x[1] > bounds[3] ? x[1] : bounds[3]); bounds[4] = (x[2] < bounds[4] ? x[2] : bounds[4]); bounds[5] = (x[2] > bounds[5] ? x[2] : bounds[5]); } } else { vtkMath::UninitializeBounds(bounds); } } //---------------------------------------------------------------------------- void vtkPolyData::ComputeBounds() { if (this->GetMTime() > this->ComputeTime) { // If there are no cells, but there are points, back to the // bounds of the points set. if (this->GetNumberOfCells() == 0 && this->GetNumberOfPoints()) { vtkPointSet::ComputeBounds(); return; } int t, i; vtkIdType *pts = 0; vtkIdType npts = 0; double x[3]; vtkCellArray *cella[4]; cella[0] = this->GetVerts(); cella[1] = this->GetLines(); cella[2] = this->GetPolys(); cella[3] = this->GetStrips(); // carefully compute the bounds int doneOne = 0; this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_DOUBLE_MAX; this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_DOUBLE_MAX; // Iterate over cells's points for (t = 0; t < 4; t++) { for (cella[t]->InitTraversal(); cella[t]->GetNextCell(npts,pts); ) { for (i = 0; i < npts; i++) { this->Points->GetPoint( pts[i], x ); this->Bounds[0] = (x[0] < this->Bounds[0] ? x[0] : this->Bounds[0]); this->Bounds[1] = (x[0] > this->Bounds[1] ? x[0] : this->Bounds[1]); this->Bounds[2] = (x[1] < this->Bounds[2] ? x[1] : this->Bounds[2]); this->Bounds[3] = (x[1] > this->Bounds[3] ? x[1] : this->Bounds[3]); this->Bounds[4] = (x[2] < this->Bounds[4] ? x[2] : this->Bounds[4]); this->Bounds[5] = (x[2] > this->Bounds[5] ? x[2] : this->Bounds[5]); doneOne = 1; } } } if (!doneOne) { vtkMath::UninitializeBounds(this->Bounds); } this->ComputeTime.Modified(); } } //---------------------------------------------------------------------------- // Set the cell array defining vertices. void vtkPolyData::SetVerts (vtkCellArray* v) { if (v == this->DummyContainer.Dummy.GetPointer()) { v = NULL; } if ( v != this->Verts) { if (this->Verts) { this->Verts->UnRegister(this); } this->Verts = v; if (this->Verts) { this->Verts->Register(this); } this->Modified(); } } //---------------------------------------------------------------------------- // Get the cell array defining vertices. If there are no vertices, an // empty array will be returned (convenience to simplify traversal). vtkCellArray* vtkPolyData::GetVerts() { if ( !this->Verts ) { return this->DummyContainer.Dummy.GetPointer(); } else { return this->Verts; } } //---------------------------------------------------------------------------- // Set the cell array defining lines. void vtkPolyData::SetLines (vtkCellArray* l) { if (l == this->DummyContainer.Dummy.GetPointer()) { l = NULL; } if ( l != this->Lines) { if (this->Lines) { this->Lines->UnRegister(this); } this->Lines = l; if (this->Lines) { this->Lines->Register(this); } this->Modified(); } } //---------------------------------------------------------------------------- // Get the cell array defining lines. If there are no lines, an // empty array will be returned (convenience to simplify traversal). vtkCellArray* vtkPolyData::GetLines() { if ( !this->Lines ) { return this->DummyContainer.Dummy.GetPointer(); } else { return this->Lines; } } //---------------------------------------------------------------------------- // Set the cell array defining polygons. void vtkPolyData::SetPolys (vtkCellArray* p) { if(p == this->DummyContainer.Dummy.GetPointer()) { p = NULL; } if ( p != this->Polys) { if (this->Polys) { this->Polys->UnRegister(this); } this->Polys = p; if (this->Polys) { this->Polys->Register(this); } this->Modified(); } } //---------------------------------------------------------------------------- // Get the cell array defining polygons. If there are no polygons, an // empty array will be returned (convenience to simplify traversal). vtkCellArray* vtkPolyData::GetPolys() { if ( !this->Polys ) { return this->DummyContainer.Dummy.GetPointer(); } else { return this->Polys; } } //---------------------------------------------------------------------------- // Set the cell array defining triangle strips. void vtkPolyData::SetStrips (vtkCellArray* s) { if ( s == this->DummyContainer.Dummy.GetPointer()) { s = NULL; } if ( s != this->Strips) { if (this->Strips) { this->Strips->UnRegister(this); } this->Strips = s; if (this->Strips) { this->Strips->Register(this); } this->Modified(); } } //---------------------------------------------------------------------------- // Get the cell array defining triangle strips. If there are no // triangle strips, an empty array will be returned (convenience to // simplify traversal). vtkCellArray* vtkPolyData::GetStrips() { if ( !this->Strips ) { return this->DummyContainer.Dummy.GetPointer(); } else { return this->Strips; } } //---------------------------------------------------------------------------- void vtkPolyData::Cleanup() { if ( this->Verts ) { this->Verts->UnRegister(this); this->Verts = NULL; } if ( this->Lines ) { this->Lines->UnRegister(this); this->Lines = NULL; } if ( this->Polys ) { this->Polys->UnRegister(this); this->Polys = NULL; } if ( this->Strips ) { this->Strips->UnRegister(this); this->Strips = NULL; } if ( this->Cells ) { this->Cells->UnRegister(this); this->Cells = NULL; } if ( this->Links ) { this->Links->UnRegister(this); this->Links = NULL; } } //---------------------------------------------------------------------------- // Restore object to initial state. Release memory back to system. void vtkPolyData::Initialize() { vtkPointSet::Initialize(); this->Cleanup(); if(this->Information) { this->Information->Set(vtkDataObject::DATA_PIECE_NUMBER(), -1); this->Information->Set(vtkDataObject::DATA_NUMBER_OF_PIECES(), 0); this->Information->Set(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS(), 0); } } //---------------------------------------------------------------------------- int vtkPolyData::GetMaxCellSize() { int maxCellSize=0, cellSize; if ( this->Verts ) { cellSize = this->Verts->GetMaxCellSize(); if ( cellSize > maxCellSize ) { maxCellSize = cellSize; } } if ( this->Lines ) { cellSize = this->Lines->GetMaxCellSize(); if ( cellSize > maxCellSize ) { maxCellSize = cellSize; } } if ( this->Polys ) { cellSize = this->Polys->GetMaxCellSize(); if ( cellSize > maxCellSize ) { maxCellSize = cellSize; } } if ( this->Strips ) { cellSize = this->Strips->GetMaxCellSize(); if ( cellSize > maxCellSize ) { maxCellSize = cellSize; } } return maxCellSize; } //---------------------------------------------------------------------------- vtkIdType vtkPolyData::GetNumberOfCells() { return this->GetNumberOfVerts() + this->GetNumberOfLines() + this->GetNumberOfPolys() + this->GetNumberOfStrips(); } //---------------------------------------------------------------------------- vtkIdType vtkPolyData::GetNumberOfVerts() { return (this->Verts ? this->Verts->GetNumberOfCells() : 0); } vtkIdType vtkPolyData::GetNumberOfLines() { return (this->Lines ? this->Lines->GetNumberOfCells() : 0); } vtkIdType vtkPolyData::GetNumberOfPolys() { return (this->Polys ? this->Polys->GetNumberOfCells() : 0); } vtkIdType vtkPolyData::GetNumberOfStrips() { return (this->Strips ? this->Strips->GetNumberOfCells() : 0); } //---------------------------------------------------------------------------- void vtkPolyData::DeleteCells() { // if we have Links, we need to delete them (they are no longer valid) if (this->Links) { this->Links->UnRegister( this ); this->Links = NULL; } if (this->Cells) { this->Cells->UnRegister( this ); this->Cells = NULL; } } //---------------------------------------------------------------------------- // Create data structure that allows random access of cells. void vtkPolyData::BuildCells() { if (this->Cells) { this->DeleteCells(); } vtkCellArray *vertCells = this->GetVerts(); vtkCellArray *lineCells = this->GetLines(); vtkCellArray *polyCells = this->GetPolys(); vtkCellArray *stripCells = this->GetStrips(); // here are the number of cells we have vtkIdType nVerts = vertCells->GetNumberOfCells(); vtkIdType nLines = lineCells->GetNumberOfCells(); vtkIdType nPolys = polyCells->GetNumberOfCells(); vtkIdType nStrips = stripCells->GetNumberOfCells(); // pre-allocate the space we need vtkIdType nCells = nVerts + nLines + nPolys + nStrips; vtkUnsignedCharArray *types = vtkUnsignedCharArray::New(); unsigned char *pTypes = types->WritePointer(0, nCells); vtkIntArray *locs = vtkIntArray::New(); int *pLocs = locs->WritePointer(0, nCells); // record locations and type of each cell. // verts vtkIdType numCellPts; vtkIdType nextCellPts; if (nVerts) { vtkIdType *pVerts = vertCells->GetData()->GetPointer(0); numCellPts = pVerts[0]; nextCellPts = numCellPts + 1; pLocs[0] = 0; pTypes[0] = numCellPts > 1 ? VTK_POLY_VERTEX : VTK_VERTEX; for (vtkIdType i = 1; i < nVerts; ++i) { numCellPts = pVerts[nextCellPts]; pLocs[i] = nextCellPts; pTypes[i] = numCellPts > 1 ? VTK_POLY_VERTEX : VTK_VERTEX; nextCellPts += numCellPts + 1; } pLocs += nVerts; pTypes += nVerts; } // lines if (nLines) { vtkIdType *pLines = lineCells->GetData()->GetPointer(0); numCellPts = pLines[0]; pLocs[0] = 0; pTypes[0] = numCellPts > 2 ? VTK_POLY_LINE : VTK_LINE; nextCellPts = numCellPts + 1; for (vtkIdType i = 1; i < nLines; ++i) { numCellPts = pLines[nextCellPts]; pLocs[i] = nextCellPts; pTypes[i] = numCellPts > 2 ? VTK_POLY_LINE : VTK_LINE; nextCellPts += numCellPts + 1; } pLocs += nLines; pTypes += nLines; } // polys if (nPolys) { vtkIdType *pPolys = polyCells->GetData()->GetPointer(0); numCellPts = pPolys[0]; pLocs[0] = 0; pTypes[0] = numCellPts == 3 ? VTK_TRIANGLE : numCellPts == 4 ? VTK_QUAD : VTK_POLYGON; nextCellPts = numCellPts + 1; for (vtkIdType i = 1; i < nPolys; ++i) { numCellPts = pPolys[nextCellPts]; pLocs[i] = nextCellPts; pTypes[i] = numCellPts == 3 ? VTK_TRIANGLE : numCellPts == 4 ? VTK_QUAD : VTK_POLYGON; nextCellPts += numCellPts + 1; } pLocs += nPolys; pTypes += nPolys; } // strips if (nStrips) { std::fill_n(pTypes, nStrips, VTK_TRIANGLE_STRIP); vtkIdType *pStrips = stripCells->GetData()->GetPointer(0); numCellPts = pStrips[0]; pLocs[0] = 0; nextCellPts = numCellPts + 1; for (vtkIdType i = 1; i < nStrips; ++i) { numCellPts = pStrips[nextCellPts]; pLocs[i] = nextCellPts; nextCellPts += numCellPts + 1; } } // set up the cell types data structure this->Cells = vtkCellTypes::New(); this->Cells->SetCellTypes(nCells, types, locs); this->Cells->Register(this); this->Cells->Delete(); types->Delete(); locs->Delete(); } //---------------------------------------------------------------------------- void vtkPolyData::DeleteLinks() { if (this->Links) { this->Links->UnRegister( this ); this->Links = NULL; } } //---------------------------------------------------------------------------- // Create upward links from points to cells that use each point. Enables // topologically complex queries. void vtkPolyData::BuildLinks(int initialSize) { if ( this->Links ) { this->DeleteLinks(); } if ( this->Cells == NULL ) { this->BuildCells(); } this->Links = vtkCellLinks::New(); if ( initialSize > 0 ) { this->Links->Allocate(initialSize); } else { this->Links->Allocate(this->GetNumberOfPoints()); } this->Links->Register(this); this->Links->Delete(); this->Links->BuildLinks(this); } //---------------------------------------------------------------------------- // Copy a cells point ids into list provided. (Less efficient.) void vtkPolyData::GetCellPoints(vtkIdType cellId, vtkIdList *ptIds) { vtkIdType i; vtkIdType *pts, npts; ptIds->Reset(); if ( this->Cells == NULL ) { this->BuildCells(); } this->vtkPolyData::GetCellPoints(cellId, npts, pts); ptIds->InsertId (npts-1,pts[npts-1]); for (i=0; iSetId(i,pts[i]); } } //---------------------------------------------------------------------------- void vtkPolyData::GetPointCells(vtkIdType ptId, vtkIdList *cellIds) { vtkIdType *cells; vtkIdType numCells; vtkIdType i; if ( ! this->Links ) { this->BuildLinks(); } cellIds->Reset(); numCells = this->Links->GetNcells(ptId); cells = this->Links->GetCells(ptId); for (i=0; i < numCells; i++) { cellIds->InsertId(i,cells[i]); } } //---------------------------------------------------------------------------- // Method allocates initial storage for vertex, line, polygon, and // triangle strip arrays. Use this method before the method // PolyData::InsertNextCell(). (Or, provide vertex, line, polygon, and // triangle strip cell arrays.) void vtkPolyData::Allocate(vtkIdType numCells, int extSize) { vtkCellArray *cells; if (!this->Cells) { this->Cells = vtkCellTypes::New(); this->Cells->Allocate(numCells,3*numCells); // Consistent Register/UnRegister. (ShallowCopy). this->Cells->Register(this); this->Cells->Delete(); } cells = vtkCellArray::New(); cells->Allocate(numCells,extSize); this->SetVerts(cells); cells->Delete(); cells = vtkCellArray::New(); cells->Allocate(numCells,extSize); this->SetLines(cells); cells->Delete(); cells = vtkCellArray::New(); cells->Allocate(numCells,extSize); this->SetPolys(cells); cells->Delete(); cells = vtkCellArray::New(); cells->Allocate(numCells,extSize); this->SetStrips(cells); cells->Delete(); } void vtkPolyData::Allocate(vtkPolyData *inPolyData, vtkIdType numCells, int extSize) { vtkCellArray *cells; int numVerts=inPolyData->GetVerts()->GetNumberOfCells(); int numLines=inPolyData->GetLines()->GetNumberOfCells(); int numPolys=inPolyData->GetPolys()->GetNumberOfCells(); int numStrips=inPolyData->GetStrips()->GetNumberOfCells(); int total=numVerts+numLines+numPolys+numStrips; if ( total <= 0 ) { return; } if (!this->Cells) { this->Cells = vtkCellTypes::New(); this->Cells->Allocate(numCells,3*numCells); // Consistent Register/UnRegister. (ShallowCopy). this->Cells->Register(this); this->Cells->Delete(); } if ( numVerts > 0 ) { cells = vtkCellArray::New(); cells->Allocate( static_cast(static_cast(numVerts)/total*numCells),extSize); this->SetVerts(cells); cells->Delete(); } if ( numLines > 0 ) { cells = vtkCellArray::New(); cells->Allocate( static_cast(static_cast(numLines)/total*numCells),extSize); this->SetLines(cells); cells->Delete(); } if ( numPolys > 0 ) { cells = vtkCellArray::New(); cells->Allocate( static_cast(static_cast(numPolys)/total*numCells),extSize); this->SetPolys(cells); cells->Delete(); } if ( numStrips > 0 ) { cells = vtkCellArray::New(); cells->Allocate( static_cast(static_cast(numStrips)/total*numCells),extSize); this->SetStrips(cells); cells->Delete(); } } //---------------------------------------------------------------------------- // Insert a cell of type VTK_VERTEX, VTK_POLY_VERTEX, VTK_LINE, VTK_POLY_LINE, // VTK_TRIANGLE, VTK_QUAD, VTK_POLYGON, or VTK_TRIANGLE_STRIP. Make sure that // the PolyData::Allocate() function has been called first or that vertex, // line, polygon, and triangle strip arrays have been supplied. // Note: will also insert VTK_PIXEL, but converts it to VTK_QUAD. vtkIdType vtkPolyData::InsertNextCell(int type, int npts, vtkIdType *pts) { int id; if ( !this->Cells ) { // if we get to this point, the user has not made any guess at the // number of cells, so this guess is as good as any this->Cells = vtkCellTypes::New(); this->Cells->Allocate(5000,10000); } switch (type) { case VTK_VERTEX: case VTK_POLY_VERTEX: this->Verts->InsertNextCell(npts,pts); id = this->Cells->InsertNextCell(type, this->Verts->GetInsertLocation(npts)); break; case VTK_LINE: case VTK_POLY_LINE: this->Lines->InsertNextCell(npts,pts); id = this->Cells->InsertNextCell(type, this->Lines->GetInsertLocation(npts)); break; case VTK_TRIANGLE: case VTK_QUAD: case VTK_POLYGON: this->Polys->InsertNextCell(npts,pts); id = this->Cells->InsertNextCell(type, this->Polys->GetInsertLocation(npts)); break; case VTK_PIXEL: //need to rearrange vertices { vtkIdType pixPts[4]; pixPts[0] = pts[0]; pixPts[1] = pts[1]; pixPts[2] = pts[3]; pixPts[3] = pts[2]; this->Polys->InsertNextCell(npts,pixPts); id = this->Cells->InsertNextCell(VTK_QUAD, this->Polys->GetInsertLocation(npts)); break; } case VTK_TRIANGLE_STRIP: this->Strips->InsertNextCell(npts,pts); id = this->Cells->InsertNextCell(type, this->Strips->GetInsertLocation(npts)); break; default: id = -1; vtkErrorMacro(<<""Bad cell type! Can't insert!""); } return id; } //---------------------------------------------------------------------------- // Insert a cell of type VTK_VERTEX, VTK_POLY_VERTEX, VTK_LINE, VTK_POLY_LINE, // VTK_TRIANGLE, VTK_QUAD, VTK_POLYGON, or VTK_TRIANGLE_STRIP. Make sure that // the PolyData::Allocate() function has been called first or that vertex, // line, polygon, and triangle strip arrays have been supplied. // Note: will also insert VTK_PIXEL, but converts it to VTK_QUAD. vtkIdType vtkPolyData::InsertNextCell(int type, vtkIdList *pts) { vtkIdType id; vtkIdType npts = pts->GetNumberOfIds(); if ( !this->Cells ) { this->Cells = vtkCellTypes::New(); this->Cells->Allocate(5000,10000); } switch (type) { case VTK_VERTEX: case VTK_POLY_VERTEX: this->Verts->InsertNextCell(pts); id = this->Cells->InsertNextCell(type, this->Verts->GetInsertLocation(npts)); break; case VTK_LINE: case VTK_POLY_LINE: this->Lines->InsertNextCell(pts); id = this->Cells->InsertNextCell(type, this->Lines->GetInsertLocation(npts)); break; case VTK_TRIANGLE: case VTK_QUAD: case VTK_POLYGON: this->Polys->InsertNextCell(pts); id = this->Cells->InsertNextCell(type, this->Polys->GetInsertLocation(npts)); break; case VTK_PIXEL: //need to rearrange vertices { vtkIdType pixPts[4]; pixPts[0] = pts->GetId(0); pixPts[1] = pts->GetId(1); pixPts[2] = pts->GetId(3); pixPts[3] = pts->GetId(2); this->Polys->InsertNextCell(4,pixPts); id = this->Cells->InsertNextCell(VTK_QUAD, this->Polys->GetInsertLocation(npts)); break; } case VTK_TRIANGLE_STRIP: this->Strips->InsertNextCell(pts); id = this->Cells->InsertNextCell(type, this->Strips->GetInsertLocation(npts)); break; case VTK_EMPTY_CELL: id = -1; // do nothing break; default: id = -1; vtkErrorMacro(<<""Bad cell type! Can't insert!""); } return id; } //---------------------------------------------------------------------------- // Recover extra allocated memory when creating data whose initial size // is unknown. Examples include using the InsertNextCell() method, or // when using the CellArray::EstimateSize() method to create vertices, // lines, polygons, or triangle strips. void vtkPolyData::Squeeze() { if ( this->Verts != NULL ) { this->Verts->Squeeze(); } if ( this->Lines != NULL ) { this->Lines->Squeeze(); } if ( this->Polys != NULL ) { this->Polys->Squeeze(); } if ( this->Strips != NULL ) { this->Strips->Squeeze(); } vtkPointSet::Squeeze(); } //---------------------------------------------------------------------------- // Begin inserting data all over again. Memory is not freed but otherwise // objects are returned to their initial state. void vtkPolyData::Reset() { if ( this->Verts != NULL ) { this->Verts->Reset(); } if ( this->Lines != NULL ) { this->Lines->Reset(); } if ( this->Polys != NULL ) { this->Polys->Reset(); } if ( this->Strips != NULL ) { this->Strips->Reset(); } } //---------------------------------------------------------------------------- // Reverse the order of point ids defining the cell. void vtkPolyData::ReverseCell(vtkIdType cellId) { int loc, type; if ( this->Cells == NULL ) { this->BuildCells(); } loc = this->Cells->GetCellLocation(cellId); type = this->Cells->GetCellType(cellId); switch (type) { case VTK_VERTEX: case VTK_POLY_VERTEX: this->Verts->ReverseCell(loc); break; case VTK_LINE: case VTK_POLY_LINE: this->Lines->ReverseCell(loc); break; case VTK_TRIANGLE: case VTK_QUAD: case VTK_POLYGON: this->Polys->ReverseCell(loc); break; case VTK_TRIANGLE_STRIP: this->Strips->ReverseCell(loc); break; default: break; } } //---------------------------------------------------------------------------- // Add a point to the cell data structure (after cell pointers have been // built). This method allocates memory for the links to the cells. (To // use this method, make sure points are available and BuildLinks() has been invoked.) vtkIdType vtkPolyData::InsertNextLinkedPoint(int numLinks) { return this->Links->InsertNextPoint(numLinks); } //---------------------------------------------------------------------------- // Add a point to the cell data structure (after cell pointers have been // built). This method adds the point and then allocates memory for the // links to the cells. (To use this method, make sure points are available // and BuildLinks() has been invoked.) vtkIdType vtkPolyData::InsertNextLinkedPoint(double x[3], int numLinks) { this->Links->InsertNextPoint(numLinks); return this->Points->InsertNextPoint(x); } //---------------------------------------------------------------------------- // Add a new cell to the cell data structure (after cell pointers have been // built). This method adds the cell and then updates the links from the points // to the cells. (Memory is allocated as necessary.) vtkIdType vtkPolyData::InsertNextLinkedCell(int type, int npts, vtkIdType *pts) { vtkIdType i, id; id = this->InsertNextCell(type,npts,pts); for (i=0; iLinks->ResizeCellList(pts[i],1); this->Links->AddCellReference(id,pts[i]); } return id; } //---------------------------------------------------------------------------- // Remove a reference to a cell in a particular point's link list. You may also // consider using RemoveCellReference() to remove the references from all the // cell's points to the cell. This operator does not reallocate memory; use the // operator ResizeCellList() to do this if necessary. void vtkPolyData::RemoveReferenceToCell(vtkIdType ptId, vtkIdType cellId) { this->Links->RemoveCellReference(cellId, ptId); } //---------------------------------------------------------------------------- // Add a reference to a cell in a particular point's link list. (You may also // consider using AddCellReference() to add the references from all the // cell's points to the cell.) This operator does not realloc memory; use the // operator ResizeCellList() to do this if necessary. void vtkPolyData::AddReferenceToCell(vtkIdType ptId, vtkIdType cellId) { this->Links->AddCellReference(cellId, ptId); } //---------------------------------------------------------------------------- // Replace the points defining cell ""cellId"" with a new set of points. This // operator is (typically) used when links from points to cells have not been // built (i.e., BuildLinks() has not been executed). Use the operator // ReplaceLinkedCell() to replace a cell when cell structure has been built. void vtkPolyData::ReplaceCell(vtkIdType cellId, int npts, vtkIdType *pts) { int loc, type; if ( this->Cells == NULL ) { this->BuildCells(); } loc = this->Cells->GetCellLocation(cellId); type = this->Cells->GetCellType(cellId); switch (type) { case VTK_VERTEX: case VTK_POLY_VERTEX: this->Verts->ReplaceCell(loc,npts,pts); break; case VTK_LINE: case VTK_POLY_LINE: this->Lines->ReplaceCell(loc,npts,pts); break; case VTK_TRIANGLE: case VTK_QUAD: case VTK_POLYGON: this->Polys->ReplaceCell(loc,npts,pts); break; case VTK_TRIANGLE_STRIP: this->Strips->ReplaceCell(loc,npts,pts); break; default: break; } } //---------------------------------------------------------------------------- // Replace one cell with another in cell structure. This operator updates the // connectivity list and the point's link list. It does not delete references // to the old cell in the point's link list. Use the operator // RemoveCellReference() to delete all references from points to (old) cell. // You may also want to consider using the operator ResizeCellList() if the // link list is changing size. void vtkPolyData::ReplaceLinkedCell(vtkIdType cellId, int npts, vtkIdType *pts) { int loc = this->Cells->GetCellLocation(cellId); int type = this->Cells->GetCellType(cellId); switch (type) { case VTK_VERTEX: case VTK_POLY_VERTEX: this->Verts->ReplaceCell(loc,npts,pts); break; case VTK_LINE: case VTK_POLY_LINE: this->Lines->ReplaceCell(loc,npts,pts); break; case VTK_TRIANGLE: case VTK_QUAD: case VTK_POLYGON: this->Polys->ReplaceCell(loc,npts,pts); break; case VTK_TRIANGLE_STRIP: this->Strips->ReplaceCell(loc,npts,pts); break; default: npts = 0; } for (int i=0; i < npts; i++) { this->Links->InsertNextCellReference(pts[i],cellId); } } //---------------------------------------------------------------------------- // Get the neighbors at an edge. More efficient than the general // GetCellNeighbors(). Assumes links have been built (with BuildLinks()), // and looks specifically for edge neighbors. void vtkPolyData::GetCellEdgeNeighbors(vtkIdType cellId, vtkIdType p1, vtkIdType p2, vtkIdList *cellIds) { cellIds->Reset(); const vtkCellLinks::Link &link1(this->Links->GetLink(p1)); const vtkCellLinks::Link &link2(this->Links->GetLink(p2)); const vtkIdType *cells1 = link1.cells; const vtkIdType *cells1End = cells1 + link1.ncells; const vtkIdType *cells2 = link2.cells; const vtkIdType *cells2End = cells2 + link2.ncells; while (cells1 != cells1End) { if (*cells1 != cellId) { const vtkIdType *cells2Cur(cells2); while (cells2Cur != cells2End) { if (*cells1 == *cells2Cur) { cellIds->InsertNextId(*cells1); break; } ++cells2Cur; } } ++cells1; } } //---------------------------------------------------------------------------- void vtkPolyData::GetCellNeighbors(vtkIdType cellId, vtkIdList *ptIds, vtkIdList *cellIds) { vtkIdType i, j, numPts, cellNum; int allFound, oneFound; if ( ! this->Links ) { this->BuildLinks(); } cellIds->Reset(); // load list with candidate cells, remove current cell vtkIdType ptId = ptIds->GetId(0); int numPrime = this->Links->GetNcells(ptId); vtkIdType *primeCells = this->Links->GetCells(ptId); numPts = ptIds->GetNumberOfIds(); // for each potential cell for (cellNum = 0; cellNum < numPrime; cellNum++) { // ignore the original cell if (primeCells[cellNum] != cellId) { // are all the remaining points in the cell ? for (allFound=1, i=1; i < numPts && allFound; i++) { ptId = ptIds->GetId(i); int numCurrent = this->Links->GetNcells(ptId); vtkIdType *currentCells = this->Links->GetCells(ptId); oneFound = 0; for (j = 0; j < numCurrent; j++) { if (primeCells[cellNum] == currentCells[j]) { oneFound = 1; break; } } if (!oneFound) { allFound = 0; } } if (allFound) { cellIds->InsertNextId(primeCells[cellNum]); } } } } int vtkPolyData::IsEdge(vtkIdType p1, vtkIdType p2) { unsigned short int ncells; vtkIdType cellType; vtkIdType npts; vtkIdType i, j; vtkIdType *cells, *pts; vtkIdType nbPoints = this->GetNumberOfPoints(); if (p1 >= nbPoints || p2 >= nbPoints) { return 0; } this->GetPointCells(p1,ncells,cells); for (i=0; iGetCellType(cells[i]); switch (cellType) { case VTK_EMPTY_CELL: case VTK_VERTEX: case VTK_POLY_VERTEX: case VTK_LINE: case VTK_POLY_LINE: break; case VTK_TRIANGLE: if ( this->IsPointUsedByCell(p2,cells[i]) ) { return 1; } break; case VTK_QUAD: this->GetCellPoints(cells[i],npts,pts); for (j=0; jGetCellPoints(cells[i],npts,pts); for (j=0; jGetCellPoints(cells[i],npts,pts); for (j=0; jvtkPointSet::GetActualMemorySize(); if ( this->Verts ) { size += this->Verts->GetActualMemorySize(); } if ( this->Lines ) { size += this->Lines->GetActualMemorySize(); } if ( this->Polys ) { size += this->Polys->GetActualMemorySize(); } if ( this->Strips ) { size += this->Strips->GetActualMemorySize(); } if ( this->Cells ) { size += this->Cells->GetActualMemorySize(); } if ( this->Links ) { size += this->Links->GetActualMemorySize(); } return size; } //---------------------------------------------------------------------------- void vtkPolyData::ShallowCopy(vtkDataObject *dataObject) { vtkPolyData *polyData = vtkPolyData::SafeDownCast(dataObject); if (this == polyData) return; if ( polyData != NULL ) { this->SetVerts(polyData->GetVerts()); this->SetLines(polyData->GetLines()); this->SetPolys(polyData->GetPolys()); this->SetStrips(polyData->GetStrips()); // I do not know if this is correct but. if (this->Cells) { this->Cells->UnRegister(this); } this->Cells = polyData->Cells; if (this->Cells) { this->Cells->Register(this); } if (this->Links) { this->Links->Delete(); } this->Links = polyData->Links; if (this->Links) { this->Links->Register(this); } } // Do superclass this->vtkPointSet::ShallowCopy(dataObject); } //---------------------------------------------------------------------------- void vtkPolyData::DeepCopy(vtkDataObject *dataObject) { // Do superclass // We have to do this BEFORE we call BuildLinks, else there are no points // to build the links on (the parent DeepCopy copies the points) this->vtkPointSet::DeepCopy(dataObject); vtkPolyData *polyData = vtkPolyData::SafeDownCast(dataObject); if ( polyData != NULL ) { vtkCellArray *ca; ca = vtkCellArray::New(); ca->DeepCopy(polyData->GetVerts()); this->SetVerts(ca); ca->Delete(); ca = vtkCellArray::New(); ca->DeepCopy(polyData->GetLines()); this->SetLines(ca); ca->Delete(); ca = vtkCellArray::New(); ca->DeepCopy(polyData->GetPolys()); this->SetPolys(ca); ca->Delete(); ca = vtkCellArray::New(); ca->DeepCopy(polyData->GetStrips()); this->SetStrips(ca); ca->Delete(); if ( this->Cells ) { this->Cells->UnRegister(this); this->Cells = NULL; } if (polyData->Cells) { this->BuildCells(); } if ( this->Links ) { this->Links->UnRegister(this); this->Links = NULL; } if (polyData->Links) { this->BuildLinks(); } } } void vtkPolyData::RemoveGhostCells() { // Get a pointer to the cell ghost level array. vtkUnsignedCharArray* temp = this->GetCellGhostArray(); if (temp == NULL) { vtkDebugMacro(""Could not find cell ghost array.""); return; } if (temp->GetNumberOfComponents() != 1 || temp->GetNumberOfTuples() < this->GetNumberOfCells()) { vtkErrorMacro(""Poorly formed ghost array.""); return; } unsigned char* cellGhosts = temp->GetPointer(0); vtkIdType numCells = this->GetNumberOfCells(); vtkIntArray *types = vtkIntArray::New(); types->SetNumberOfValues(numCells); for (vtkIdType i = 0; i < numCells; i++) { types->SetValue(i, this->GetCellType(i)); } this->DeleteCells(); // we have to make new copies of Verts, Lines, Polys // and Strips since they may be shared with other polydata vtkSmartPointer verts; if(this->Verts) { verts = this->Verts; verts->InitTraversal(); this->Verts->UnRegister(this); this->Verts = vtkCellArray::New(); } vtkSmartPointer lines; if(this->Lines) { lines = this->Lines; lines->InitTraversal(); this->Lines->UnRegister(this); this->Lines = vtkCellArray::New(); } vtkSmartPointer polys; if(this->Polys) { polys = this->Polys; polys->InitTraversal(); this->Polys->UnRegister(this); this->Polys = vtkCellArray::New(); } vtkSmartPointer strips; if(this->Strips) { strips = this->Strips; strips->InitTraversal(); this->Strips->UnRegister(this); this->Strips = vtkCellArray::New(); } vtkCellData *newCellData = vtkCellData::New(); newCellData->CopyAllocate(this->CellData, numCells); vtkIdType *pts, n; int cellId; for (vtkIdType i = 0; i < numCells; i++) { int type = types->GetValue(i); if (type == VTK_VERTEX || type == VTK_POLY_VERTEX) { verts->GetNextCell(n, pts); if (! (cellGhosts[i] & vtkDataSetAttributes::DUPLICATECELL)) { cellId = this->InsertNextCell(type, n, pts); newCellData->CopyData(this->CellData, i, cellId); } } else if (type == VTK_LINE || type == VTK_POLY_LINE) { lines->GetNextCell(n, pts); if (! (cellGhosts[i] & vtkDataSetAttributes::DUPLICATECELL)) { cellId = this->InsertNextCell(type, n, pts); newCellData->CopyData(this->CellData, i, cellId); } } else if (type == VTK_POLYGON || type == VTK_TRIANGLE || type == VTK_QUAD) { polys->GetNextCell(n, pts); if (! (cellGhosts[i] & vtkDataSetAttributes::DUPLICATECELL)) { cellId = this->InsertNextCell(type, n, pts); newCellData->CopyData(this->CellData, i, cellId); } } else if (type == VTK_TRIANGLE_STRIP) { strips->GetNextCell(n, pts); if (! (cellGhosts[i] & vtkDataSetAttributes::DUPLICATECELL)) { cellId = this->InsertNextCell(type, n, pts); newCellData->CopyData(this->CellData, i, cellId); } } } newCellData->Squeeze(); this->CellData->ShallowCopy(newCellData); newCellData->Delete(); types->Delete(); // If there are no more ghost levels, then remove all arrays. this->CellData->RemoveArray(vtkDataSetAttributes::GhostArrayName()); this->Squeeze(); } //---------------------------------------------------------------------------- void vtkPolyData::RemoveDeletedCells() { if (!this->Cells) { return; } vtkNew oldData; oldData->ShallowCopy(this); this->DeleteCells(); if(this->Verts) { this->Verts->UnRegister(this); this->Verts = vtkCellArray::New(); } if(this->Lines) { this->Lines->UnRegister(this); this->Lines = vtkCellArray::New(); } if(this->Polys) { this->Polys->UnRegister(this); this->Polys = vtkCellArray::New(); } if(this->Strips) { this->Strips->UnRegister(this); this->Strips = vtkCellArray::New(); } this->CellData->CopyAllocate(oldData->GetCellData()); const vtkIdType numCells = oldData->GetNumberOfCells(); vtkCell *cell; vtkIdType cellId; vtkIdList *pointIds; int type; for (vtkIdType i = 0; i < numCells; i++) { type = oldData->GetCellType(i); if (type != VTK_EMPTY_CELL) { cell = oldData->GetCell(i); pointIds = cell->GetPointIds(); cellId = this->InsertNextCell(type, pointIds); this->CellData->CopyData(oldData->GetCellData(), i, cellId); } } this->CellData->Squeeze(); } //---------------------------------------------------------------------------- vtkPolyData* vtkPolyData::GetData(vtkInformation* info) { return info? vtkPolyData::SafeDownCast(info->Get(DATA_OBJECT())) : 0; } //---------------------------------------------------------------------------- vtkPolyData* vtkPolyData::GetData(vtkInformationVector* v, int i) { return vtkPolyData::GetData(v->GetInformationObject(i)); } //---------------------------------------------------------------------------- void vtkPolyData::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << ""Number Of Vertices: "" << this->GetNumberOfVerts() << ""\\n""; os << indent << ""Number Of Lines: "" << this->GetNumberOfLines() << ""\\n""; os << indent << ""Number Of Polygons: "" << this->GetNumberOfPolys() << ""\\n""; os << indent << ""Number Of Triangle Strips: "" << this->GetNumberOfStrips() << ""\\n""; os << indent << ""Number Of Pieces: "" << this->GetNumberOfPieces() << endl; os << indent << ""Piece: "" << this->GetPiece() << endl; os << indent << ""Ghost Level: "" << this->GetGhostLevel() << endl; } //---------------------------------------------------------------------------- int vtkPolyData::GetScalarFieldCriticalIndex (vtkIdType pointId, vtkDataArray *scalarField) { /* * implements scalar field critical point classification for manifold * 2D meshes. */ /* * returned value: * -4: no such field * -3: attribute check failed * -2: non 2-manifold star * -1: regular point * 0: minimum * 1: saddle * 2: maximum */ bool is_min = true, is_max = true; vtkIdList *starTriangleList = vtkIdList::New(), *lowerLinkPointList = vtkIdList::New(), *upperLinkPointList = vtkIdList::New(), *pointList = NULL; double pointFieldValue = scalarField->GetComponent(pointId, 0), neighborFieldValue = 0; if(this->GetNumberOfPoints() != scalarField->GetSize()) return vtkPolyData::ERR_INCORRECT_FIELD; /* make sure the connectivity is built */ if(!this->Links) this->BuildLinks(); /* build the lower and upper links */ this->GetPointCells(pointId, starTriangleList); int starNb = starTriangleList->GetNumberOfIds(); for(int i = 0; i < starNb; i++) { vtkCell *c = this->GetCell(starTriangleList->GetId(i)); pointList = c->GetPointIds(); int pointNb = pointList->GetNumberOfIds(); if(pointNb != 3) { starTriangleList->Delete(); lowerLinkPointList->Delete(); upperLinkPointList->Delete(); return vtkPolyData::ERR_NON_MANIFOLD_STAR; } for(int j = 0; j < pointNb; j++) { vtkIdType currentPointId = pointList->GetId(j); /* quick check for extrema */ neighborFieldValue = scalarField->GetComponent(currentPointId, 0); if((currentPointId != pointId)&&(neighborFieldValue == pointFieldValue)) { /* simulation of simplicity (Edelsbrunner et al. ACM ToG 1990) */ if(currentPointId > pointId) { is_max = false; upperLinkPointList->InsertUniqueId(currentPointId); } if(currentPointId < pointId) { is_min = false; lowerLinkPointList->InsertUniqueId(currentPointId); } } else { if(neighborFieldValue > pointFieldValue) { is_max = false; upperLinkPointList->InsertUniqueId(currentPointId); } if(neighborFieldValue < pointFieldValue) { is_min = false; lowerLinkPointList->InsertUniqueId(currentPointId); } } } } if((is_max)||(is_min)) { starTriangleList->Delete(); lowerLinkPointList->Delete(); upperLinkPointList->Delete(); if(is_max) return vtkPolyData::MAXIMUM; if(is_min) return vtkPolyData::MINIMUM; } /* * is the vertex really regular? * (lower and upper links are BOTH simply connected) */ int visitedPointNb = 0, stackBottom = 0, lowerLinkPointNb = lowerLinkPointList->GetNumberOfIds(), upperLinkPointNb = upperLinkPointList->GetNumberOfIds(); /* first, check lower link's simply connectedness */ vtkIdList *stack = vtkIdList::New(); stack->InsertUniqueId(lowerLinkPointList->GetId(0)); vtkIdType currentPointId = stack->GetId(stackBottom), nextPointId = -1; do { stackBottom++; vtkIdList *triangleList = vtkIdList::New(); this->GetPointCells(currentPointId, triangleList); int triangleNb = triangleList->GetNumberOfIds(); for(int i = 0; i < triangleNb; i++) { vtkCell *c = this->GetCell(triangleList->GetId(i)); pointList = c->GetPointIds();; int pointNb = pointList->GetNumberOfIds(); if(pointList->IsId(pointId) >= 0) { // those two triangles are in the star of pointId int j = 0; do { nextPointId = pointList->GetId(j); j++; }while(((nextPointId == pointId) ||(nextPointId == currentPointId))&&(j < pointNb )); } if(lowerLinkPointList->IsId(nextPointId) >= 0) { stack->InsertUniqueId(nextPointId); } } triangleList->Delete(); visitedPointNb++; currentPointId = stack->GetId(stackBottom), nextPointId = -1; }while(stackBottom < stack->GetNumberOfIds()); if(visitedPointNb != lowerLinkPointNb) { // the lower link is not simply connected, then it's a saddle stack->Delete(); starTriangleList->Delete(); lowerLinkPointList->Delete(); upperLinkPointList->Delete(); return vtkPolyData::SADDLE; } /* * then, check upper link's simply connectedness. * BOTH need to be checked if the 2-manifold has boundary components. */ stackBottom = 0; visitedPointNb = 0; stack->Delete(); stack = vtkIdList::New(); stack->InsertUniqueId(upperLinkPointList->GetId(0)); currentPointId = stack->GetId(stackBottom), nextPointId = -1; do { stackBottom++; vtkIdList *triangleList = vtkIdList::New(); this->GetPointCells(currentPointId, triangleList); int triangleNb = triangleList->GetNumberOfIds(); for(int i = 0; i < triangleNb; i++) { vtkCell *c = this->GetCell(triangleList->GetId(i)); pointList = c->GetPointIds(); int pointNb = pointList->GetNumberOfIds(); if(pointList->IsId(pointId) >= 0) { // those two triangles are in the star of pointId int j = 0; do { nextPointId = pointList->GetId(j); j++; }while(((nextPointId == pointId) ||(nextPointId == currentPointId))&&(j < pointNb)); } if(upperLinkPointList->IsId(nextPointId) >= 0) { stack->InsertUniqueId(nextPointId); } } triangleList->Delete(); visitedPointNb++; currentPointId = stack->GetId(stackBottom), nextPointId = -1; }while(stackBottom < stack->GetNumberOfIds()); if(visitedPointNb != upperLinkPointNb) { // the upper link is not simply connected, then it's a saddle stack->Delete(); starTriangleList->Delete(); lowerLinkPointList->Delete(); upperLinkPointList->Delete(); return vtkPolyData::SADDLE; } /* else it's necessarily a regular point (only 4 cases in 2D)*/ stack->Delete(); starTriangleList->Delete(); lowerLinkPointList->Delete(); upperLinkPointList->Delete(); return vtkPolyData::REGULAR_POINT; } //---------------------------------------------------------------------------- int vtkPolyData::GetScalarFieldCriticalIndex (vtkIdType pointId, const char* fieldName) { /* * returned value: * -4: no such field * -3: attribute check failed * -2: non 2-manifold star * -1: regular point * 0: minimum * 1: saddle * 2: maximum */ int fieldId = 0; vtkPointData *pointData = this->GetPointData(); vtkDataArray *scalarField = pointData->GetArray(fieldName, fieldId); if(!scalarField) return vtkPolyData::ERR_NO_SUCH_FIELD; return this->GetScalarFieldCriticalIndex(pointId, scalarField); } //---------------------------------------------------------------------------- int vtkPolyData::GetScalarFieldCriticalIndex (vtkIdType pointId, int fieldId) { /* * returned value: * -4: no such field * -3: attribute check failed * -2: non 2-manifold star * -1: regular point * 0: minimum * 1: saddle * 2: maximum */ vtkPointData *pointData = this->GetPointData(); vtkDataArray *scalarField = pointData->GetArray(fieldId); if(!scalarField) return vtkPolyData::ERR_NO_SUCH_FIELD; return this->GetScalarFieldCriticalIndex(pointId, scalarField); } ",16300,True,2786.8226409527656,median "/** * Duration * Standalone timeline for Creative Code * * Copyright (c) 2012 James George * Development Supported by YCAM InterLab http://interlab.ycam.jp/en/ * http://jamesgeorge.org + http://flightphase.com * http://github.com/obviousjim + http://github.com/flightphase * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the ""Software""), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #include ""DurationController.h"" #include ""ofxHotKeys.h"" #define DROP_DOWN_WIDTH 250 #define TEXT_INPUT_WIDTH 100 DurationController::DurationController(){ lastOSCBundleSent = 0; shouldStartPlayback = false; receivedAddTrack = false; receivedPaletteToLoad = false; enabled = false; shouldCreateNewProject = false; shouldLoadProject = false; audioTrack = NULL; } DurationController::~DurationController(){ } void DurationController::enableInterface(){ if(!enabled){ enabled = true; ofAddListener(ofEvents().update, this, &DurationController::update); ofAddListener(ofEvents().draw, this, &DurationController::draw); ofAddListener(ofEvents().keyPressed, this, &DurationController::keyPressed); gui->enable(); gui->disableAppEventCallbacks(); timeline.enable(); map >::iterator it = headers.begin(); while(it != headers.end()){ it->second->getGui()->enable(); it++; } } } void DurationController::disableInterface(){ if(enabled){ enabled = false; ofRemoveListener(ofEvents().update, this, &DurationController::update); ofRemoveListener(ofEvents().draw, this, &DurationController::draw); ofRemoveListener(ofEvents().keyPressed, this, &DurationController::keyPressed); gui->disable(); timeline.disable(); map >::iterator it = headers.begin(); while(it != headers.end()){ it->second->getGui()->disable(); it++; } } } bool DurationController::isInterfaceEnabled(){ return enabled; } void DurationController::setup(){ #ifdef TARGET_WIN32 FreeConsole(); #endif if(!translation.load(""languageFile.csv"")){ ofLogError(""DurationController::setup"") << ""error setting up translation, unpredictable stuff will happen"" << endl; } ofxXmlSettings defaultSettings; bool settingsLoaded = defaultSettings.loadFile(""settings.xml""); ; translation.setCurrentLanguage(defaultSettings.getValue(""language"", ""english"")); if(!settingsLoaded){ defaultSettings.setValue(""language"", ""english""); defaultSettings.saveFile(); } //populate projects vector projects; projects.push_back(translation.translateKey(""new project..."")); projects.push_back(translation.translateKey(""open project..."")); #ifdef TARGET_WIN32 defaultProjectDirectoryPath = ofToDataPath(ofFilePath::getUserHomeDir() + ""\\\\Documents\\\\Duration\\\\""); #else defaultProjectDirectoryPath = ofToDataPath(ofFilePath::getUserHomeDir() + ""/Documents/Duration/""); #endif ofDirectory projectDirectory = ofDirectory(defaultProjectDirectoryPath); if(!projectDirectory.exists()){ projectDirectory.create(true); } projectDirectory.listDir(); for(int i = 0; i < projectDirectory.size(); i++){ if(projectDirectory.getFile(i).isDirectory()){ ofDirectory subDir = ofDirectory(projectDirectory.getPath(i)); //cout << ""checking path "" << projectDirectory.getPath(i) << endl; subDir.allowExt(""durationproj""); subDir.setShowHidden(true); subDir.listDir(); if(subDir.size() > 0){ projects.push_back(projectDirectory.getName(i)); } } } #ifdef TARGET_WIN32 timeline.setupFont(""GUI/mplus-1c-regular.ttf"", 9); tooltipFont.loadFont(""GUI/mplus-1c-regular.ttf"", 7); #else timeline.setupFont(""GUI/mplus-1c-regular.ttf"", 6); tooltipFont.loadFont(""GUI/mplus-1c-regular.ttf"", 5); #endif //setup timeline timeline.setup(); // timeline.curvesUseBinary = true; //ELOI SWITCH THIS HERE // timeline.enableUndo(false); timeline.setSpacebarTogglePlay(false); timeline.setFrameRate(30); timeline.setDurationInSeconds(30); timeline.setOffset(ofVec2f(0, 90)); timeline.setBPM(120.f); timeline.setAutosave(false); timeline.setEditableHeaders(true); timeline.moveToThread(); //increases accuracy of bang call backs //Set up top GUI gui = new ofxUICanvas(0,0,ofGetWidth(), 90); //ADD PROJECT DROP DOWN projectDropDown = new ofxUIDropDownList(DROP_DOWN_WIDTH, ""PROJECT"", projects, OFX_UI_FONT_LARGE); projectDropDown->setAutoClose(true); gui->addWidgetDown(projectDropDown); //ADD TRACKS vector trackTypes; trackTypes.push_back(translation.translateKey(""bangs"")); trackTypes.push_back(translation.translateKey(""flags"")); trackTypes.push_back(translation.translateKey(""switches"")); trackTypes.push_back(translation.translateKey(""curves"")); trackTypes.push_back(translation.translateKey(""colors"")); trackTypes.push_back(translation.translateKey(""lfo"")); trackTypes.push_back(translation.translateKey(""audio"")); addTrackDropDown = new ofxUIDropDownList(DROP_DOWN_WIDTH, translation.translateKey(""ADD TRACK""), trackTypes, OFX_UI_FONT_MEDIUM); addTrackDropDown->setAllowMultiple(false); addTrackDropDown->setAutoClose(true); // gui->addWidgetRight(addTrackDropDown); gui->addWidgetSouthOf(addTrackDropDown, ""PROJECT""); saveButton = new ofxUIMultiImageButton(32, 32, false, ""GUI/save_.png"", ""SAVE""); saveButton->setLabelVisible(false); gui->addWidgetEastOf(saveButton, ""PROJECT""); //ADD TIMECODE string zeroTimecode = ""00:00:00:000""; timeLabel = new ofxUILabel(zeroTimecode, OFX_UI_FONT_LARGE); gui->addWidgetRight(timeLabel); //durationLabel = new ofxUILabel("" / ""+zeroTimecode, OFX_UI_FONT_SMALL); durationLabel = new ofxUITextInput(""DURATION"", zeroTimecode, timeLabel->getRect()->width,0,0,0,OFX_UI_FONT_MEDIUM); durationLabel->setAutoClear(false); gui->addWidgetSouthOf(durationLabel, zeroTimecode); //ADD PLAY/PAUSE playpauseToggle = new ofxUIMultiImageToggle(32, 32, false, ""GUI/play_.png"", ""PLAYPAUSE""); playpauseToggle->setLabelVisible(false); gui->addWidgetEastOf(playpauseToggle, zeroTimecode); stopButton = new ofxUIMultiImageButton(32, 32, false, ""GUI/stop_.png"", ""STOP""); stopButton->setLabelVisible(false); gui->addWidgetRight(stopButton); loopToggle = new ofxUIMultiImageToggle(32, 32, false, ""GUI/loop_.png"", ""LOOP""); loopToggle->setLabelVisible(false); gui->addWidgetRight(loopToggle); //SETUP BPM CONTROLS useBPMToggle = new ofxUILabelToggle(translation.translateKey(""BPM""), false); gui->addWidgetRight(useBPMToggle); bpmDialer = new ofxUINumberDialer(0., 250., 120., 2, ""BPM_VALUE"", OFX_UI_FONT_MEDIUM); gui->addWidgetEastOf(bpmDialer, translation.translateKey(""BPM"")); //figure out where to put this // snapToKeysToggle = new ofxUILabelToggle(""Snap to Keys"",false,0,0,00,OFX_UI_FONT_MEDIUM); // gui->addWidgetSouthOf(snapToKeysToggle, ""BPM""); // snapToBPMToggle = new ofxUILabelToggle(""Snap to BPM"",false,0,0,0,0,OFX_UI_FONT_SMALL); // gui->addWidgetSouthOf(snapToBPM, ""BPM""); //SETUP OSC CONTROLS enableOSCInToggle = new ofxUILabelToggle(translation.translateKey(""OSC IN""),false,0,0,0,0, OFX_UI_FONT_MEDIUM); enableOSCOutToggle = new ofxUILabelToggle(translation.translateKey(""OSC OUT""),false,0,0,0,0, OFX_UI_FONT_MEDIUM); oscOutIPInput = new ofxUITextInput(""OSCIP"", ""127.0.0.1"",TEXT_INPUT_WIDTH*1.5,0,0,0, OFX_UI_FONT_MEDIUM); oscOutIPInput->setAutoClear(false); oscInPortInput = new ofxUITextInput(""OSCINPORT"", ""12346"",TEXT_INPUT_WIDTH*.8,0,0,0, OFX_UI_FONT_MEDIUM); oscInPortInput->setAutoClear(false); oscOutPortInput = new ofxUITextInput(""OSCOUTPORT"", ""12345"",TEXT_INPUT_WIDTH*.8,0,0,0, OFX_UI_FONT_MEDIUM); oscOutPortInput->setAutoClear(false); gui->addWidgetRight(enableOSCInToggle); gui->addWidgetRight(oscInPortInput); gui->addWidgetRight(enableOSCOutToggle); gui->addWidgetRight(oscOutIPInput); gui->addWidgetRight(oscOutPortInput); ofAddListener(gui->newGUIEvent, this, &DurationController::guiEvent); //add events ofAddListener(timeline.events().bangFired, this, &DurationController::bangFired); ofAddListener(ofEvents().exit, this, &DurationController::exit); //SET UP LISENTERS enableInterface(); if(settingsLoaded){ string lastProjectPath = defaultSettings.getValue(""lastProjectPath"", """"); string lastProjectName = defaultSettings.getValue(""lastProjectName"", """"); if(lastProjectPath != """" && lastProjectName != """" && ofDirectory(lastProjectPath).exists()){ loadProject(lastProjectPath, lastProjectName); } else{ ofLogError() << ""Duration -- Last project was not found, creating a new project""; loadProject(ofToDataPath(defaultProjectDirectoryPath+""Sample Project""), ""Sample Project"", true); } } else { // cout << ""Loading sample project "" << defaultProjectDirectoryPath << endl; loadProject(ofToDataPath(defaultProjectDirectoryPath+""Sample Project""), ""Sample Project"", true); } createTooltips(); startThread(); } void DurationController::threadedFunction(){ while(isThreadRunning()){ lock(); oscLock.lock(); handleOscIn(); handleOscOut(); oscLock.unlock(); unlock(); ofSleepMillis(1); } } void DurationController::handleOscIn(){ if(!settings.oscInEnabled){ return; } //TODO: move parsing and receing to separate different threads? long timelineStartTime = timeline.getCurrentTimeMillis(); while(receiver.hasWaitingMessages()){ ofxOscMessage m; receiver.getNextMessage(&m); bool handled = false; long startTime = recordTimer.getAppTimeMicros(); vector& pages = timeline.getPages(); for(int i = 0; i < pages.size(); i++){ vector& tracks = pages[i]->getTracks(); for(int t = 0; t < tracks.size(); t++){ // cout << "" testing against "" << ""/""+tracks[t]->getDisplayName() << endl; ofxTLTrack* track = tracks[t]; ofPtr header = headers[track->getName()]; if(header->receiveOSC() && m.getAddress() == ofFilePath::addLeadingSlash(track->getDisplayName()) ){ if(timeline.getIsPlaying() ){ //TODO: change to isPlaying() && isRecording() if(track->getTrackType() == ""Curves""){ ofxTLCurves* curves = (ofxTLCurves*)track; // cout << ""adding value "" << m.getArgAsFloat(0) << endl; if(m.getArgType(0) == OFXOSC_TYPE_FLOAT){ float value = m.getArgAsFloat(0); if(value != header->lastValueReceived || !header->hasReceivedValue){ curves->addKeyframeAtMillis(value, timelineStartTime); header->lastValueReceived = value; header->hasReceivedValue = true; } } } else if(track->getTrackType() == ""Bangs""){ ofxTLBangs* bangs = (ofxTLBangs*)track; bangs->addKeyframeAtMillis(0,timelineStartTime); } } header->lastInputReceivedTime = recordTimer.getAppTimeSeconds(); handled = true; } } } long endTime = recordTimer.getAppTimeMicros(); // cout << ""receiving message took "" << (endTime - startTime) << "" micros "" << endl; if(handled){ return; } //check for playback messages if(m.getAddress() == ""/duration/open""){ if(m.getNumArgs() == 1 && m.getArgType(0) == OFXOSC_TYPE_STRING){ string projectPath = m.getArgAsString(0); shouldLoadProject = true; if(ofFilePath::isAbsolute(projectPath)){ projectToLoad = projectPath; } else{ projectToLoad = defaultProjectDirectoryPath+projectPath; } } else{ ofLogError(""Duration:OSC"") << "" Open Project Failed - must have on string argument specifying project name or absolute path""; } } else if(m.getAddress() == ""/duration/new""){ if(m.getNumArgs() == 1 && m.getArgType(0) == OFXOSC_TYPE_STRING){ string path = m.getArgAsString(0); shouldCreateNewProject = true; if(ofFilePath::isAbsolute(path)){ newProjectPath = path; } else{ newProjectPath = defaultProjectDirectoryPath+path; } cout << ""creating new project at path "" << newProjectPath << endl; } else{ ofLogError(""Duration:OSC"") << "" New Project Failed - must have on string argument specifying the new project path""; } } else if(m.getAddress() == ""/duration/save""){ saveProject(); } else if(m.getAddress() == ""/duration/setduration""){ if(m.getNumArgs() == 1){ //seconds if(m.getArgType(0) == OFXOSC_TYPE_FLOAT){ timeline.setDurationInSeconds(m.getArgAsFloat(0)); durationLabel->setTextString(timeline.getDurationInTimecode()); } //timecode else if(m.getArgType(0) == OFXOSC_TYPE_STRING){ timeline.setDurationInTimecode(m.getArgAsString(0)); durationLabel->setTextString(timeline.getDurationInTimecode()); } //millis else if(m.getArgType(0) == OFXOSC_TYPE_INT32){ timeline.setDurationInMillis(m.getArgAsInt32(0)); durationLabel->setTextString(timeline.getDurationInTimecode()); } else if(m.getArgType(0) == OFXOSC_TYPE_INT64){ timeline.setDurationInMillis(m.getArgAsInt64(0)); durationLabel->setTextString(timeline.getDurationInTimecode()); } } else { ofLogError(""Duration:OSC"") << "" Set Duration failed - must have one argument. seconds as float, timecode string HH:MM:SS:MILS, or integer as milliseconds""; } } else if(m.getAddress() == ""/duration/play""){ if(m.getNumArgs() == 0){ if(!timeline.getIsPlaying()){ shouldStartPlayback = true; } } else { for(int i = 0; i < m.getNumArgs(); i++){ if(m.getArgType(i) == OFXOSC_TYPE_STRING){ ofPtr header = getHeaderWithDisplayName(m.getArgAsString(i)); if(header != NULL){ header->getTrack()->play(); } } } } } else if(m.getAddress() == ""/duration/stop""){ if(m.getNumArgs() == 0){ if(timeline.getIsPlaying()){ timeline.stop(); } else{ timeline.setCurrentTimeMillis(0); } } else{ for(int i = 0; i < m.getNumArgs(); i++){ if(m.getArgType(i) == OFXOSC_TYPE_STRING){ ofPtr header = getHeaderWithDisplayName(m.getArgAsString(i)); if(header != NULL){ header->getTrack()->stop(); } } } } } else if(m.getAddress() == ""/duration/record""){ //TODO: turn on record mode shouldStartPlayback = true; //startPlayback(); } else if(m.getAddress() == ""/duration/seektosecond""){ if(m.getArgType(0) == OFXOSC_TYPE_FLOAT){ timeline.setCurrentTimeSeconds(m.getArgAsFloat(0)); } else{ ofLogError(""Duration:OSC"") << "" Seek to Second failed: first argument must be a float""; } } else if(m.getAddress() == ""/duration/seektoposition""){ if(m.getArgType(0) == OFXOSC_TYPE_FLOAT){ float percent = ofClamp(m.getArgAsFloat(0),0.0,1.0); timeline.setPercentComplete(percent); } else{ ofLogError(""Duration:OSC"") << "" Seek to Position failed: first argument must be a float between 0.0 and 1.0""; } } else if(m.getAddress() == ""/duration/seektomillis""){ if(m.getArgType(0) == OFXOSC_TYPE_INT32){ timeline.setCurrentTimeMillis(m.getArgAsInt32(0)); } else if(m.getArgType(0) == OFXOSC_TYPE_INT64){ timeline.setCurrentTimeMillis(m.getArgAsInt64(0)); } else{ ofLogError(""Duration:OSC"") << "" Seek to Millis failed: first argument must be a int 32 or in 64""; } } else if(m.getAddress() == ""/duration/seektotimecode""){ if(m.getArgType(0) == OFXOSC_TYPE_STRING){ long millis = ofxTimecode::millisForTimecode(m.getArgAsString(0)); if(millis > 0){ timeline.setCurrentTimeMillis(millis); } else{ ofLogError(""Duration:OSC"") << "" Seek to Timecode failed: bad timecode. Please format HH:MM:SS:MMM""; } } else{ ofLogError(""Duration:OSC"") << "" Seek to Timecode failed: first argument must be a string""; } } //enable and disable OSC else if(m.getAddress() == ""/duration/enableoscout""){ //system wide if(m.getNumArgs() == 1 && m.getArgType(0) == OFXOSC_TYPE_INT32){ settings.oscOutEnabled = m.getArgAsInt32(0) != 0; enableOSCOutToggle->setValue(settings.oscOutEnabled); } //per track else if(m.getNumArgs() == 2 && m.getArgType(0) == OFXOSC_TYPE_STRING && m.getArgType(1) == OFXOSC_TYPE_INT32) { string trackName = m.getArgAsString(0); ofPtr header = getHeaderWithDisplayName(trackName); if(header != NULL){ header->setSendOSC(m.getArgAsInt32(1) != 0); } else { ofLogError(""Duration:OSC"") << "" Enable OSC out failed. track not found "" << trackName; } } else{ ofLogError(""Duration:OSC"") << "" Enable OSC out incorrectly formatted arguments. usage: /duration/enableoscout enable:int32 == (1 or 0), or /duration/enableoscout trackname:string enable:int32 (1 or 0)""; } } else if(m.getAddress() == ""/duration/oscrate""){ if(m.getNumArgs() == 1){ if(m.getArgType(0) == OFXOSC_TYPE_INT32){ settings.oscRate = m.getArgAsInt32(0); oscFrequency = 1000*1/settings.oscRate; } else if(m.getArgType(0) == OFXOSC_TYPE_INT64){ settings.oscRate = m.getArgAsInt64(0); oscFrequency = 1000*1/settings.oscRate; } else if(m.getArgType(0) == OFXOSC_TYPE_FLOAT){ settings.oscRate = m.getArgAsFloat(0); oscFrequency = 1000*1/settings.oscRate; } else { ofLogError(""Duration:OSC"") << "" Set OSC rate failed. must specify an int or a float as the first parameter""; } } } else if(m.getAddress() == ""/duration/enableoscin""){ //system wide -- don't quite know what to do as this will turn off all osc if(m.getNumArgs() == 1 && m.getArgType(0) == OFXOSC_TYPE_INT32){ settings.oscInEnabled = m.getArgAsInt32(0) != 0; enableOSCInToggle->setValue(settings.oscInEnabled); } //per track else if(m.getNumArgs() == 2 && m.getArgType(0) == OFXOSC_TYPE_STRING && m.getArgType(1) == OFXOSC_TYPE_INT32){ string trackName = m.getArgAsString(0); ofPtr header = getHeaderWithDisplayName(trackName); if(header != NULL){ header->setReceiveOSC(m.getArgAsInt32(1) == 1); } else { ofLogError(""Duration:OSC"") << "" Enable in out failed. track not found "" << trackName; } } else{ ofLogError(""Duration:OSC"") << ""Enable OSC in incorrectly formatted arguments. usage: /duration/enableoscout enable:int32 == (1 or 0), or /duration/enableoscout trackname:string enable:int32 (1 or 0)""; } } //adding and removing tracks else if(m.getAddress() == ""/duration/addtrack""){ //type, receivedAddTrack = false; oscTrackTypeReceived = """"; oscTrackNameReceived = """"; oscTrackFilePathReceived = """"; //type if(m.getNumArgs() > 0 && m.getArgType(0) == OFXOSC_TYPE_STRING) { oscTrackTypeReceived = m.getArgAsString(0); receivedAddTrack = true; } //type, name if(m.getNumArgs() > 1 &&m.getArgType(1) == OFXOSC_TYPE_STRING) { oscTrackNameReceived = m.getArgAsString(1); receivedAddTrack = true; } //type, name, file path if(m.getNumArgs() > 2 && m.getArgType(2) == OFXOSC_TYPE_STRING) { oscTrackFilePathReceived = m.getArgAsString(2); receivedAddTrack = true; } if(!receivedAddTrack){ ofLogError(""Duration:OSC"") << ""Add track failed, incorrectly formatted arguments. \\n usage: /duration/addtrack type:string [optional name:string ] [optional filepath:string ]""; } } else if(m.getAddress() == ""/duration/removetrack""){ if(m.getNumArgs() == 1 && m.getArgType(0) == OFXOSC_TYPE_STRING){ string trackName = m.getArgAsString(0); ofPtr header = getHeaderWithDisplayName(trackName); if(header != NULL){ header->setShouldDelete(true); } else{ ofLogError(""Duration:OSC"") << ""Remove track failed, could not find track "" << trackName; } } else { ofLogError(""Duration:OSC"") << ""Remove track failed, incorrectly formatted arguments. \\n usage: /duration/removetrack name:string""; } } else if(m.getAddress() == ""/duration/trackname""){ if(m.getNumArgs() == 2 && m.getArgType(0) == OFXOSC_TYPE_STRING && m.getArgType(1) == OFXOSC_TYPE_STRING) { string trackName = m.getArgAsString(0); ofPtr header = getHeaderWithDisplayName(trackName); if(header != NULL){ header->getTrack()->setDisplayName(m.getArgAsString(1)); } else{ ofLogError(""Duration:OSC"") << ""Set Track Name failed, could not find track "" << trackName; } } else{ ofLogError(""Duration:OSC"") << ""Set Track Name failed, incorrectly formatted arguments. \\n usage: /duration/trackname oldname:string newname:string""; } } else if(m.getAddress() == ""/duration/valuerange""){ if(m.getNumArgs() == 3 && m.getArgType(0) == OFXOSC_TYPE_STRING && //track name m.getArgType(1) == OFXOSC_TYPE_FLOAT && //min m.getArgType(2) == OFXOSC_TYPE_FLOAT) //max { string trackName = m.getArgAsString(0); ofPtr header = getHeaderWithDisplayName(trackName); if(header != NULL){ if(header->getTrackType() == ""Curves"" || header->getTrackType() == ""LFO""){ header->setValueRange(ofRange(m.getArgAsFloat(1),m.getArgAsFloat(2))); } else { ofLogError(""Duration:OSC"") << ""Set value range failed, track is not a Curves track "" << trackName; } } else{ ofLogError(""Duration:OSC"") << ""Set value range failed, could not find track "" << trackName; } } else { ofLogError(""Duration:OSC"") << ""Set value range failed, incorrectly formatted message. \\n usage: /duration/valuerange trackname:string min:float max:float""; } } else if(m.getAddress() == ""/duration/valuerange/min""){ if(m.getNumArgs() == 2 && m.getArgType(0) == OFXOSC_TYPE_STRING && //track name m.getArgType(1) == OFXOSC_TYPE_FLOAT) //min { string trackName = m.getArgAsString(0); ofPtr header = getHeaderWithDisplayName(trackName); if(header != NULL){ if(header->getTrackType() == ""Curves"" || header->getTrackType() == ""LFO""){ header->setValueMin(m.getArgAsFloat(1)); } else{ ofLogError(""Duration:OSC"") << ""Set value range min failed, track is not a Curves track "" << trackName; } } else{ ofLogError(""Duration:OSC"") << ""Set value range min failed, could not find track "" << trackName; } } else{ ofLogError(""Duration:OSC"") << ""Set value range min failed. Incorrectly formatted arguments \\n usage: /duration/valuerange/min trackname:string""; } } else if(m.getAddress() == ""/duration/valuerange/max""){ if(m.getNumArgs() == 2 && m.getArgType(0) == OFXOSC_TYPE_STRING && //track name m.getArgType(1) == OFXOSC_TYPE_FLOAT) //max { string trackName = m.getArgAsString(0); ofPtr header = getHeaderWithDisplayName(trackName); if(header != NULL){ if(header->getTrackType() == ""Curves"" || header->getTrackType() == ""LFO""){ header->setValueMax(m.getArgAsFloat(1)); } else{ ofLogError(""Duration:OSC"") << ""Set value range max failed, track is not a Curves track "" << trackName; } } else{ ofLogError(""Duration:OSC"") << ""Set value range min failed, could not find track "" << trackName; } } else{ ofLogError(""Duration:OSC"") << ""Set value range min failed. Incorrectly formatted arguments \\n usage: /duration/valuerange/min trackname:string""; } } else if(m.getAddress() == ""/duration/colorpalette""){ if(m.getNumArgs() == 2 && m.getArgType(0) == OFXOSC_TYPE_STRING && //track name m.getArgType(1) == OFXOSC_TYPE_STRING) //file path { string trackName = m.getArgAsString(0); ofPtr header = getHeaderWithDisplayName(trackName); if(header != NULL){ if(header->getTrackType() == ""Colors""){ receivedPaletteToLoad = true; paletteTrack = (ofxTLColorTrack*)header->getTrack(); palettePath = m.getArgAsString(1); } } else { ofLogError(""Duration:OSC"") << ""Set color palette failed, could not find track "" << trackName; } } else{ ofLogError(""Duration:OSC"") << ""Set color palette failed, incorrectly formatted arguments \\n usage: /duration/colorpalette trackname:string imagefilepath:string""; } } else if(m.getAddress() == ""/duration/audioclip""){ if(m.getNumArgs() == 1 && m.getArgType(0) == OFXOSC_TYPE_STRING){ if(audioTrack != NULL){ if(!audioTrack->loadSoundfile(m.getArgAsString(0))){ ofLogError(""Duration:OSC"") << ""Set audio clip failed, clip failed to load. "" << m.getArgAsString(0); } } else { ofLogError(""Duration:OSC"") << ""Set audio clip failed, first add an audio track to the composition.""; } } else{ ofLogError(""Duration:OSC"") << ""Set audio clip failed, incorrectly formatted arguments. \\n usage /duration/audioclip filepath:string ""; } } } } void DurationController::handleOscOut(){ if(!settings.oscOutEnabled){ return; } unsigned long bundleTime = recordTimer.getAppTimeMillis(); if(lastOSCBundleSent+oscFrequency > bundleTime){ return; } //cout << ""OSC RATE IS "" << settings.oscRate << "" osc FREQUENCY is "" << oscFrequency << "" sending num at record timer "" << recordTimer.getAppTimeMillis() << endl; unsigned long timelineSampleTime = timeline.getCurrentTimeMillis(); int numMessages = 0; ofxOscBundle bundle; //lock(); vector& pages = timeline.getPages(); for(int i = 0; i < pages.size(); i++){ vector& tracks = pages[i]->getTracks(); for(int t = 0; t < tracks.size(); t++){ ofPtr header = headers[tracks[t]->getName()]; if(!header->sendOSC()){ continue; } unsigned long trackSampleTime = tracks[t]->getIsPlaying() ? tracks[t]->currentTrackTime() : timelineSampleTime; string trackType = tracks[t]->getTrackType(); if(trackType == ""Curves"" || trackType == ""Switches"" || trackType == ""Colors"" || trackType == ""Audio"" || trackType == ""LFO""){ bool messageValid = false; ofxOscMessage m; if(trackType == ""Curves"" || trackType == ""LFO""){ ofxTLKeyframes* curves = (ofxTLKeyframes*)tracks[t]; float value = curves->getValueAtTimeInMillis(trackSampleTime); if(value != header->lastFloatSent || !header->hasSentValue || refreshAllOscOut){ m.addFloatArg(value); header->lastFloatSent = value; header->hasSentValue = true; messageValid = true; } } else if(trackType == ""Switches""){ ofxTLSwitches* switches = (ofxTLSwitches*)tracks[t]; bool on = switches->isOnAtMillis(trackSampleTime); if(on != header->lastBoolSent || !header->hasSentValue || refreshAllOscOut){ m.addIntArg(on ? 1 : 0); header->lastBoolSent = on; header->hasSentValue = true; messageValid = true; } } else if(trackType == ""Colors""){ ofxTLColorTrack* colors = (ofxTLColorTrack*)tracks[t]; ofColor color = colors->getColorAtMillis(trackSampleTime); if(color != header->lastColorSent || !header->hasSentValue || refreshAllOscOut){ m.addIntArg(color.r); m.addIntArg(color.g); m.addIntArg(color.b); header->lastColorSent = color; header->hasSentValue = true; messageValid = true; } } else if(trackType == ""Audio""){ ofxTLAudioTrack* audio = (ofxTLAudioTrack*)tracks[t]; if(audio->getIsPlaying() || timeline.getIsPlaying()){ vector& bins = audio->getFFT(); for(int b = 0; b < bins.size(); b++){ m.addFloatArg(bins[b]); } messageValid = true; } } if(messageValid){ m.setAddress(ofFilePath::addLeadingSlash(tracks[t]->getDisplayName())); bundle.addMessage(m); numMessages++; } } } } //unlock(); //any bangs that came our way this frame send them out too for(int i = 0; i < bangsReceived.size(); i++){ // cout << ""FOUND BANGS!"" << endl; bundle.addMessage(bangsReceived[i]); } numMessages += bangsReceived.size(); if(numMessages > 0){ sender.sendBundle(bundle); refreshAllOscOut = false; } lastOSCBundleSent = bundleTime; bangsReceived.clear(); } //TODO: hook up to record button //and make NO LOOP void DurationController::startRecording(){ recordTimer.setStartTime(); recordTimeOffset = timeline.getCurrentTimeMillis(); //timeline.play(); startPlayback(); } void DurationController::stopRecording(){ } //-------------------------------------------------------------- void DurationController::bangFired(ofxTLBangEventArgs& bang){ // ofLogNotice() << ""Bang from "" << bang.track->getDisplayName() << "" at time "" << bang.currentTime << "" with flag "" << bang.flag; if(!settings.oscOutEnabled){ return; } string trackType = bang.track->getTrackType(); if(!headers[bang.track->getName()]->sendOSC()){ return; } ofxOscMessage m; m.setAddress( ofFilePath::addLeadingSlash(bang.track->getDisplayName()) ); if(trackType == ""Flags""){ m.addStringArg(bang.flag); } bangsReceived.push_back(m); } //-------------------------------------------------------------- void DurationController::guiEvent(ofxUIEventArgs &e){ string name = e.widget->getName(); int kind = e.widget->getKind(); // cout << ""name is "" << name << "" kind is "" << kind << endl; if(e.widget == stopButton && stopButton->getValue()){ if(timeline.getIsPlaying()){ timeline.stop(); } else{ timeline.setCurrentTimeMillis(0); } } else if(name == ""PLAYPAUSE""){ if(!timeline.getIsPlaying()){ startPlayback(); } else{ timeline.stop(); } } else if(name == ""DURATION""){ if(!gui->hasKeyboardFocus()){ string newDuration = durationLabel->getTextString(); timeline.setDurationInTimecode(newDuration); durationLabel->setTextString(timeline.getDurationInTimecode()); needsSave = true; } } else if(e.widget == addTrackDropDown){ if(addTrackDropDown->isOpen()){ timeline.disable(); } else { timeline.enable(); if(addTrackDropDown->getSelected().size() > 0){ lock(); string selectedTrackType = addTrackDropDown->getSelected()[0]->getName(); addTrack(translation.keyForTranslation(selectedTrackType)); unlock(); addTrackDropDown->clearSelected(); } } } else if(e.widget == projectDropDown){ if(projectDropDown->isOpen()){ timeline.disable(); addTrackDropDown->setVisible(false); } else { addTrackDropDown->setVisible(true); addTrackDropDown->close(); timeline.enable(); if(projectDropDown->getSelected().size() > 0){ string selectedProjectName = projectDropDown->getSelected()[0]->getName(); if(selectedProjectName == translation.translateKey(""new project..."")){ shouldCreateNewProject = true; } else if(selectedProjectName == translation.translateKey(""open project..."")){ shouldLoadProject = true; projectToLoad = """"; } else { shouldLoadProject = true; projectToLoad = ofToDataPath(defaultProjectDirectoryPath+selectedProjectName); } projectDropDown->clearSelected(); } } } else if(e.widget == saveButton && saveButton->getValue()){ saveProject(); } //LOOP else if(e.widget == loopToggle){ timeline.setLoopType(loopToggle->getValue() ? OF_LOOP_NORMAL : OF_LOOP_NONE); needsSave = true; } //BPM else if(e.widget == bpmDialer){ if(settings.bpm != bpmDialer->getValue()){ timeline.setBPM(settings.bpm = bpmDialer->getValue()); needsSave = true; } } else if(e.widget == useBPMToggle){ settings.useBPM = useBPMToggle->getValue(); timeline.setShowBPMGrid(settings.useBPM); timeline.enableSnapToBPM(settings.useBPM); needsSave = true; } else if(e.widget == snapToKeysToggle){ timeline.enableSnapToOtherKeyframes(snapToKeysToggle->getValue()); } //OSC INPUT else if(e.widget == enableOSCInToggle){ settings.oscInEnabled = enableOSCInToggle->getValue(); if(settings.oscInEnabled){ oscLock.lock(); receiver.setup(settings.oscInPort); oscLock.unlock(); } needsSave = true; } //INCOMING PORT else if(e.widget == oscInPortInput){ if(!gui->hasKeyboardFocus()){ int newPort = ofToInt(oscInPortInput->getTextString()); if(newPort > 0 && newPort < 65535 && newPort != settings.oscInPort && //don't send messages to ourself (newPort != settings.oscOutPort || (settings.oscIP != ""localhost"" && settings.oscIP != ""127.0.0.1""))){ settings.oscInPort = newPort; oscLock.lock(); receiver.setup(settings.oscInPort); oscLock.unlock(); needsSave = true; } else { oscInPortInput->setTextString( ofToString(settings.oscInPort) ); } } } //OSC OUTPUT else if(e.widget == enableOSCOutToggle){ settings.oscOutEnabled = enableOSCOutToggle->getValue(); if(settings.oscOutEnabled){ oscLock.lock(); sender.setup(settings.oscIP, settings.oscOutPort); oscLock.unlock(); needsSave = true; } } //OUTGOING IP else if(e.widget == oscOutIPInput && !gui->hasKeyboardFocus()){ string newIP = ofToLower(oscOutIPInput->getTextString()); if(newIP == settings.oscIP){ return; } bool valid = (newIP == ""localhost""); if(!valid){ vector ipComponents = ofSplitString(newIP, "".""); if(ipComponents.size() == 4){ valid = true; for(int i = 0; i < 4; i++){ int component = ofToInt(ipComponents[i]); if (component < 0 || component > 255){ valid = false; break; } } } } if((newIP == ""127.0.0.1"" || newIP == ""localhost"") && settings.oscInPort == settings.oscOutPort){ //don't allow us to send messages to ourself valid = false; } if(valid){ settings.oscIP = newIP; oscLock.lock(); sender.setup(settings.oscIP, settings.oscOutPort); oscLock.unlock(); needsSave = true; } oscOutIPInput->setTextString(settings.oscIP); } //OUTGOING PORT else if(e.widget == oscOutPortInput && !gui->hasKeyboardFocus()){ int newPort = ofToInt(oscOutPortInput->getTextString()); if(newPort > 0 && newPort < 65535 && newPort != settings.oscOutPort && //don't send messages to ourself (newPort != settings.oscInPort || (settings.oscIP != ""localhost"" && settings.oscIP != ""127.0.0.1""))){ settings.oscOutPort = newPort; oscLock.lock(); sender.setup(settings.oscIP, settings.oscOutPort); oscLock.unlock(); needsSave = true; } else { oscOutPortInput->setTextString( ofToString(settings.oscOutPort) ); } } } //-------------------------------------------------------------- ofxTLTrack* DurationController::addTrack(string trackType, string trackName, string xmlFileName){ ofxTLTrack* newTrack = NULL; trackType = ofToLower(trackType); if(trackName == """"){ trackName = trackType; } if(xmlFileName == """"){ string uniqueName = timeline.confirmedUniqueName(trackName); xmlFileName = ofToDataPath(settings.path + ""/"" + uniqueName + ""_.xml""); } if(trackType == translation.translateKey(""bangs"") || trackType == ""bangs""){ newTrack = timeline.addBangs(trackName, xmlFileName); } else if(trackType == translation.translateKey(""flags"") || trackType == ""flags""){ newTrack = timeline.addFlags(trackName, xmlFileName); } else if(trackType == translation.translateKey(""curves"") || trackType == ""curves""){ newTrack = timeline.addCurves(trackName, xmlFileName); } else if(trackType == translation.translateKey(""switches"")|| trackType == ""switches""){ newTrack = timeline.addSwitches(trackName, xmlFileName); } else if(trackType == translation.translateKey(""colors"") || trackType == ""colors""){ newTrack = timeline.addColors(trackName, xmlFileName); } else if(trackType == translation.translateKey(""lfo"") || trackType == ""lfo""){ newTrack = timeline.addLFO(trackName, xmlFileName); } else if(trackType == translation.translateKey(""audio"") || trackType == ""audio""){ if(audioTrack != NULL){ ofLogError(""DurationController::addTrack"") << ""Trying to add an additional audio track""; } else{ audioTrack = new ofxTLAudioTrack(); timeline.addTrack(trackName, audioTrack); timeline.bringTrackToTop(audioTrack); newTrack = audioTrack; } } else { ofLogError(""DurationController::addTrack"") << ""Unsupported track type: "" << trackType; } if(newTrack != NULL){ createHeaderForTrack(newTrack); needsSave = true; } return newTrack; } //-------------------------------------------------------------- void DurationController::update(ofEventArgs& args){ gui->update(); if(shouldStartPlayback){ shouldStartPlayback = false; startPlayback(); } timeLabel->setLabel(timeline.getCurrentTimecode()); playpauseToggle->setValue(timeline.getIsPlaying()); if(audioTrack != NULL && audioTrack->isSoundLoaded()){ if(timeline.getTimecontrolTrack() != audioTrack){ timeline.setTimecontrolTrack(audioTrack); } if(audioTrack->getDuration() != timeline.getDurationInSeconds()){ timeline.setDurationInSeconds(audioTrack->getDuration()); } if(durationLabel->getTextString() != timeline.getDurationInTimecode()){ durationLabel->setTextString(timeline.getDurationInTimecode()); } } if(ofGetHeight() < timeline.getDrawRect().getMaxY()){ ofSetWindowShape(ofGetWidth(), timeline.getDrawRect().getMaxY()+30); } if(shouldLoadProject){ shouldLoadProject = false; if(projectToLoad != """"){ loadProject(projectToLoad); projectToLoad = """"; } else{ ofFileDialogResult r = ofSystemLoadDialog(""Load Project"", true); if(r.bSuccess){ loadProject(r.getPath(), r.getName()); } } } if(shouldCreateNewProject){ shouldCreateNewProject = false; if(newProjectPath != """"){ newProject(newProjectPath); newProjectPath = """"; } else{ ofFileDialogResult r = ofSystemSaveDialog(""New Project"", ""NewDuration""); if(r.bSuccess){ newProject(r.getPath(), r.getName()); } } } if(receivedPaletteToLoad){ receivedPaletteToLoad = false; if(!paletteTrack->loadColorPalette(palettePath)){ ofLogError(""Duration:OSC"") << ""Set color palette failed, file not found""; } } if(receivedAddTrack){ lock(); receivedAddTrack = false; addTrack(oscTrackTypeReceived, oscTrackNameReceived, oscTrackFilePathReceived); unlock(); } //check if we deleted an element this frame map >::iterator it = headers.begin(); while(it != headers.end()){ needsSave |= it->second->getModified(); if(timeline.isModal() && it->second->getGui()->isEnabled()){ it->second->getGui()->disable(); } else if(!timeline.isModal() && !it->second->getGui()->isEnabled()){ it->second->getGui()->enable(); } if(it->second->getShouldDelete()){ lock(); timeline.removeTrack(it->first); timeline.setTimecontrolTrack(NULL); if(it->second->getTrackType() == ""Audio""){ if(audioTrack == NULL){ ofLogError(""Audio track inconsistency""); } else{ delete audioTrack; audioTrack = NULL; } } headers.erase(it); unlock(); needsSave = true; break; } it++; } } //-------------------------------------------------------------- ofPtr DurationController::getHeaderWithDisplayName(string name){ map >::iterator trackit; for(trackit = headers.begin(); trackit != headers.end(); trackit++){ if(trackit->second->getTrack()->getDisplayName() == name){ return trackit->second; } } //same as null return ofPtr(); } //-------------------------------------------------------------- void DurationController::draw(ofEventArgs& args){ //go through and draw all the overlay backgrounds to indicate 'hot' track sfor recording ofPushStyle(); map >::iterator trackit; for(trackit = headers.begin(); trackit != headers.end(); trackit++){ //TODO: check to make sure recording is enabled on this track //TODO: find a way to illustrate 'invalid' output sent to this track float timeSinceInput = recordTimer.getAppTimeSeconds() - trackit->second->lastInputReceivedTime; if(timeSinceInput > 0 && timeSinceInput < 1.0){ //oscilating red to indicate active ofSetColor(200,20,0,(1-timeSinceInput)*(80 + (20*sin(ofGetElapsedTimef()*8)*.5+.5))); ofRect(trackit->second->getTrack()->getDrawRect()); } } ofPopStyle(); timeline.draw(); gui->draw(); if(needsSave || timeline.hasUnsavedChanges()){ ofPushStyle(); ofSetColor(200,20,0, 40); ofFill(); ofRect(*saveButton->getRect()); ofPopStyle(); } drawTooltips(); //drawTooltipDebug(); } //-------------------------------------------------------------- void DurationController::keyPressed(ofKeyEventArgs& keyArgs){ if(timeline.isModal()){ return; } if(gui->hasKeyboardFocus()){ return; } int key = keyArgs.key; if(key == ' '){ if(ofGetModifierShiftPressed()){ timeline.togglePlaySelectedTrack(); } else{ if(!timeline.getIsPlaying()){ startPlayback(); } else{ timeline.stop(); } } } if(key == 'i'){ if(ofGetModifierAltPressed()){ timeline.setInPointAtMillis(0); } else{ timeline.setInPointAtPlayhead(); } } if(key == 'o'){ if(ofGetModifierAltPressed()){ timeline.setOutPointAtPercent(1.0); } else{ timeline.setOutPointAtPlayhead(); } } if(ofGetModifierShortcutKeyPressed() && (key == 's' || key=='s'-96) ){ saveProject(); } } //-------------------------------------------------------------- void DurationController::startPlayback(){ if(!timeline.getIsPlaying()){ sendInfoMessage(); timeline.play(); } } //-------------------------------------------------------------- void DurationController::sendInfoMessage(){ if(settings.oscOutEnabled){ ofxOscMessage m; m.setAddress(""/duration/info""); vector& pages = timeline.getPages(); for(int i = 0; i < pages.size(); i++){ vector& tracks = pages[i]->getTracks(); for (int t = 0; t < tracks.size(); t++) { m.addStringArg(tracks[t]->getTrackType()); m.addStringArg(ofFilePath::addLeadingSlash( tracks[t]->getDisplayName() )); if(tracks[t]->getTrackType() == ""Curves"" || tracks[t]->getTrackType() == ""LFO""){ ofxTLCurves* curves = (ofxTLCurves*)tracks[t]; m.addFloatArg(curves->getValueRange().min); m.addFloatArg(curves->getValueRange().max); } } } oscLock.lock(); sender.sendMessage(m); refreshAllOscOut = true; oscLock.unlock(); } } //-------------------------------------------------------------- DurationProjectSettings DurationController::defaultProjectSettings(){ DurationProjectSettings settings; settings.name = ""newProject""; settings.path = defaultProjectDirectoryPath + settings.name; settings.useBPM = false; settings.bpm = 120.0f; settings.snapToBPM = false; settings.snapToKeys = true; settings.oscRate = 30; settings.oscOutEnabled = true; settings.oscInEnabled = true; settings.oscInPort = 12346; settings.oscIP = ""localhost""; settings.oscOutPort = 12345; return settings; } //-------------------------------------------------------------- void DurationController::newProject(string projectPath){ //scrape off the last component of the filename for the project name projectPath = ofFilePath::removeTrailingSlash(projectPath); #ifdef TARGET_WIN32 vector pathComponents = ofSplitString(projectPath, ""\\\\""); #else vector pathComponents = ofSplitString(projectPath, ""/""); #endif newProject(projectPath, pathComponents[pathComponents.size()-1]); } //-------------------------------------------------------------- void DurationController::newProject(string newProjectPath, string newProjectName){ DurationProjectSettings newProjectSettings = defaultProjectSettings(); newProjectSettings.name = newProjectName; newProjectSettings.path = ofToDataPath(newProjectPath); newProjectSettings.settingsPath = ofToDataPath(newProjectSettings.path + ""/.durationproj""); #ifdef TARGET_WIN32 ofStringReplace(newProjectSettings.path,""/"", ""\\\\""); #endif ofDirectory newProjectDirectory(newProjectSettings.path); if(newProjectDirectory.exists()){ ofSystemAlertDialog(translation.translateKey(""Error creating new project. The folder already exists."")+"" "" + newProjectSettings.path); return; } if(!newProjectDirectory.create(true)){ ofSystemAlertDialog(translation.translateKey(""Error creating new project. The folder could not be created."")+"" "" + newProjectSettings.path); return; } //TODO: prompt to save existing project settings = newProjectSettings; lock(); headers.clear(); //smart pointers will call destructor timeline.reset(); unlock(); //saves file with default settings to new directory saveProject(); loadProject(settings.path, settings.name); projectDropDown->addToggle(newProjectName); } //-------------------------------------------------------------- void DurationController::loadProject(string projectPath, bool forceCreate){ //scrape off the last component of the filename for the project name projectPath = ofFilePath::removeTrailingSlash(projectPath); #ifdef TARGET_WIN32 vector pathComponents = ofSplitString(projectPath, ""\\\\""); #else vector pathComponents = ofSplitString(projectPath, ""/""); #endif loadProject(projectPath, pathComponents[pathComponents.size()-1], forceCreate); } //-------------------------------------------------------------- void DurationController::loadProject(string projectPath, string projectName, bool forceCreate){ ofxXmlSettings projectSettings; string projectDataPath = ofToDataPath(projectPath+""/.durationproj""); if(!projectSettings.loadFile(projectDataPath)){ if(forceCreate){ newProject(projectPath, projectName); } else{ ofLogError() << "" failed to load project "" << ofToDataPath(projectPath+""/.durationproj"") << endl; } return; } lock(); timeline.removeFromThread(); headers.clear(); //smart pointers will call destructor timeline.reset(); if(audioTrack != NULL){ delete audioTrack; audioTrack = NULL; } timeline.setWorkingFolder(projectPath); //LOAD ALL TRACKS projectSettings.pushTag(""tracks""); int numPages = projectSettings.getNumTags(""page""); for(int p = 0; p < numPages; p++){ projectSettings.pushTag(""page"", p); string pageName = projectSettings.getValue(""name"", ""defaultPage""); if(p == 0){ timeline.setPageName(pageName, 0); } else{ timeline.addPage(pageName, true); } int numTracks = projectSettings.getNumTags(""track""); for(int i = 0; i < numTracks; i++){ projectSettings.pushTag(""track"", i); string trackType = ofToLower(projectSettings.getValue(""type"", """")); string xmlFileName = projectSettings.getValue(""xmlFileName"", """"); string trackName = projectSettings.getValue(""trackName"",""""); string trackFilePath = ofToDataPath(projectPath + ""/"" + xmlFileName); //add the track ofxTLTrack* newTrack = addTrack(trackType, trackName, trackFilePath); //custom setup if(newTrack != NULL){ ofPtr headerTrack = headers[newTrack->getName()]; if(newTrack->getTrackType() == ""Curves"" || newTrack->getTrackType() == ""LFO""){ headerTrack->setValueRange(ofRange(projectSettings.getValue(""min"", 0.0), projectSettings.getValue(""max"", 1.0))); } else if(newTrack->getTrackType() == ""Colors""){ ofxTLColorTrack* colors = (ofxTLColorTrack*)newTrack; colors->loadColorPalette(projectSettings.getValue(""palette"", timeline.getDefaultColorPalettePath())); } else if(newTrack->getTrackType() == ""Audio""){ string clipPath = projectSettings.getValue(""clip"", """"); if(clipPath != """"){ audioTrack->loadSoundfile(clipPath); } // int numbins = projectSettings.getValue(""bins"", 256); // headerTrack->setNumberOfbins(numbins); // cout << ""set "" << numbins << "" after load "" << headerTrack->getNumberOfBins() << endl; //audioTrack->getFFTSpectrum(projectSettings.getValue(""bins"", 256)); } string displayName = projectSettings.getValue(""displayName"",""""); if(displayName != """"){ newTrack->setDisplayName(displayName); } headerTrack->setSendOSC(projectSettings.getValue(""sendOSC"", true)); headerTrack->setReceiveOSC(projectSettings.getValue(""receiveOSC"", true)); } projectSettings.popTag(); //track } projectSettings.popTag(); //page } timeline.moveToThread(); //increases accuracy of bang call backs unlock(); timeline.setCurrentPage(0); projectSettings.popTag(); //tracks //LOAD OTHER SETTINGS projectSettings.pushTag(""timelineSettings""); timeline.setDurationInTimecode(projectSettings.getValue(""duration"", ""00:00:00:000"")); timeline.setCurrentTimecode(projectSettings.getValue(""playhead"", ""00:00:00:000"")); timeline.setInPointAtTimecode(projectSettings.getValue(""inpoint"", ""00:00:00:000"")); timeline.setOutPointAtTimecode(projectSettings.getValue(""outpoint"", ""00:00:00:000"")); bool loops = projectSettings.getValue(""loop"", true); timeline.setLoopType(loops ? OF_LOOP_NORMAL : OF_LOOP_NONE); durationLabel->setTextString(timeline.getDurationInTimecode()); loopToggle->setValue( loops ); projectSettings.popTag(); //timeline settings; DurationProjectSettings newSettings; projectSettings.pushTag(""projectSettings""); useBPMToggle->setValue( newSettings.useBPM = projectSettings.getValue(""useBPM"", true) ); bpmDialer->setValue( newSettings.bpm = projectSettings.getValue(""bpm"", 120.0f) ); // snapToBPMToggle->setValue( newSettings.snapToBPM = projectSettings.getValue(""snapToBPM"", true) ); // snapToKeysToggle->setValue( newSettings.snapToKeys = projectSettings.getValue(""snapToKeys"", true) ); enableOSCInToggle->setValue( newSettings.oscInEnabled = projectSettings.getValue(""oscInEnabled"", true) ); enableOSCOutToggle->setValue( newSettings.oscOutEnabled = projectSettings.getValue(""oscOutEnabled"", true) ); oscInPortInput->setTextString( ofToString(newSettings.oscInPort = projectSettings.getValue(""oscInPort"", 12346)) ); oscOutIPInput->setTextString( newSettings.oscIP = projectSettings.getValue(""oscIP"", ""localhost"") ); oscOutPortInput->setTextString( ofToString(newSettings.oscOutPort = projectSettings.getValue(""oscOutPort"", 12345)) ); newSettings.oscRate = projectSettings.getValue(""oscRate"", 30.0); oscFrequency = 1000 * 1/newSettings.oscRate; //frequence in millis projectSettings.popTag(); //project settings; newSettings.path = projectPath; newSettings.name = projectName; newSettings.settingsPath = ofToDataPath(newSettings.path + ""/.durationproj""); settings = newSettings; projectDropDown->setLabelText(projectName); timeline.setShowBPMGrid(newSettings.useBPM); timeline.enableSnapToBPM(newSettings.useBPM); timeline.setBPM(newSettings.bpm); oscLock.lock(); if(settings.oscInEnabled){ receiver.setup(settings.oscInPort); } if(settings.oscOutEnabled){ sender.setup(settings.oscIP, settings.oscOutPort); } oscLock.unlock(); ofxXmlSettings defaultSettings; defaultSettings.loadFile(""settings.xml""); defaultSettings.setValue(""lastProjectPath"", settings.path); defaultSettings.setValue(""lastProjectName"", settings.name); defaultSettings.saveFile(); needsSave = false; sendInfoMessage(); } //-------------------------------------------------------------- void DurationController::saveProject(){ timeline.save(); ofxXmlSettings projectSettings; //SAVE ALL TRACKS projectSettings.addTag(""tracks""); projectSettings.pushTag(""tracks""); vector& pages = timeline.getPages(); for(int i = 0; i < pages.size(); i++){ projectSettings.addTag(""page""); projectSettings.pushTag(""page"", i); projectSettings.addValue(""name"", pages[i]->getName()); vector& tracks = pages[i]->getTracks(); for (int t = 0; t < tracks.size(); t++) { projectSettings.addTag(""track""); projectSettings.pushTag(""track"", t); //save track properties string trackType = tracks[t]->getTrackType(); string trackName = tracks[t]->getName(); projectSettings.addValue(""type"", trackType); projectSettings.addValue(""xmlFileName"", tracks[t]->getXMLFileName()); projectSettings.addValue(""trackName"",tracks[t]->getName()); projectSettings.addValue(""displayName"",tracks[t]->getDisplayName()); //save custom gui props projectSettings.addValue(""sendOSC"", headers[trackName]->sendOSC()); projectSettings.addValue(""receiveOSC"", headers[trackName]->receiveOSC()); if(trackType == ""Curves"" || trackType == ""LFO""){ ofxTLKeyframes* curves = (ofxTLKeyframes*)tracks[t]; projectSettings.addValue(""min"", curves->getValueRange().min); projectSettings.addValue(""max"", curves->getValueRange().max); } else if(trackType == ""Colors""){ ofxTLColorTrack* colors = (ofxTLColorTrack*)tracks[t]; projectSettings.addValue(""palette"", colors->getPalettePath()); } else if(trackType == ""Audio""){ projectSettings.addValue(""clip"", audioTrack->getSoundfilePath()); // int numbins = audioTrack->getFFTBinCount(); // projectSettings.addValue(""bins"", audioTrack->getFFTBinCount()); } projectSettings.popTag(); } projectSettings.popTag(); //page } projectSettings.popTag(); //tracks //LOAD OTHER SETTINGS projectSettings.addTag(""timelineSettings""); projectSettings.pushTag(""timelineSettings""); projectSettings.addValue(""duration"", timeline.getDurationInTimecode()); projectSettings.addValue(""playhead"", timeline.getCurrentTimecode()); projectSettings.addValue(""inpoint"", timeline.getInPointTimecode()); projectSettings.addValue(""outpoint"", timeline.getOutPointTimecode()); projectSettings.addValue(""loop"", timeline.getLoopType() == OF_LOOP_NORMAL); projectSettings.popTag();// timelineSettings //UI SETTINGS projectSettings.addTag(""projectSettings""); projectSettings.pushTag(""projectSettings""); projectSettings.addValue(""useBPM"", settings.useBPM); projectSettings.addValue(""bpm"", settings.bpm); projectSettings.addValue(""snapToBPM"", settings.snapToBPM); projectSettings.addValue(""snapToKeys"", settings.snapToKeys); projectSettings.addValue(""oscInEnabled"", settings.oscInEnabled); projectSettings.addValue(""oscOutEnabled"", settings.oscOutEnabled); projectSettings.addValue(""oscInPort"", settings.oscInPort); projectSettings.addValue(""oscIP"", settings.oscIP); projectSettings.addValue(""oscOutPort"", settings.oscOutPort); projectSettings.addValue(""oscRate"", settings.oscRate); // projectSettings.addValue(""zoomViewMin"",timeline.getZoomer()->getSelectedRange().min); // projectSettings.addValue(""zoomViewMax"",timeline.getZoomer()->getSelectedRange().max); projectSettings.popTag(); //projectSettings projectSettings.saveFile(settings.settingsPath); needsSave = false; } //-------------------------------------------------------------- ofxTLUIHeader* DurationController::createHeaderForTrack(ofxTLTrack* track){ ofxTLUIHeader* headerGui = new ofxTLUIHeader(); headerGui->translation = &translation; ofxTLTrackHeader* header = timeline.getTrackHeader(track); headerGui->setTrackHeader(header); headers[track->getName()] = ofPtr( headerGui ); return headerGui; } void DurationController::createTooltips(){ //switch project Tooltip projectTip; projectTip.text = translation.translateKey(""switch project""); projectTip.sourceRect = *projectDropDown->getRect(); projectTip.displayPoint = ofVec2f(projectTip.sourceRect.x, 55); tooltips.push_back(projectTip); //save Tooltip saveTip; saveTip.text = translation.translateKey(""save""); saveTip.sourceRect = *saveButton->getRect(); saveTip.displayPoint = ofVec2f(saveTip.sourceRect.x, 55); tooltips.push_back(saveTip); //play/pause Tooltip playpauseTip; playpauseTip.text = translation.translateKey(""play"")+""/""+translation.translateKey(""pause""); //TODO: switch dynamically playpauseTip.sourceRect = *playpauseToggle->getRect(); playpauseTip.displayPoint = ofVec2f(playpauseTip.sourceRect.x, 55); tooltips.push_back(playpauseTip); ofVec2f zone2 = playpauseTip.displayPoint; //edit duration Tooltip editDurationTip; editDurationTip.text = translation.translateKey(""edit duration""); editDurationTip.displayPoint = zone2; editDurationTip.sourceRect = *durationLabel->getRect(); tooltips.push_back(editDurationTip); //current time Tooltip currentTimeTip; currentTimeTip.text = translation.translateKey(""current time""); currentTimeTip.displayPoint = zone2; currentTimeTip.sourceRect = *timeLabel->getRect(); tooltips.push_back(currentTimeTip); //stop Tooltip stopTip; stopTip.text = translation.translateKey(""stop""); stopTip.sourceRect = *stopButton->getRect(); stopTip.displayPoint = ofVec2f(stopTip.sourceRect.x, 55); tooltips.push_back(stopTip); //loop Tooltip loopTip; loopTip.text = translation.translateKey(""toggle loop""); loopTip.sourceRect = *loopToggle->getRect(); loopTip.displayPoint = ofVec2f(loopTip.sourceRect.x, 55); tooltips.push_back(loopTip); //enable Snap to BPM Tooltip bpmTip; bpmTip.text = translation.translateKey(""snap to measures""); bpmTip.sourceRect = *useBPMToggle->getRect(); bpmTip.displayPoint = ofVec2f(bpmTip.sourceRect.x, 55); tooltips.push_back(bpmTip); //set beats per minute Tooltip setBpmTip; setBpmTip.text = translation.translateKey(""set beats per minute""); setBpmTip.sourceRect = *bpmDialer->getRect(); setBpmTip.displayPoint = ofVec2f(setBpmTip.sourceRect.x, 55); tooltips.push_back(setBpmTip); //enable OSC Tooltip oscInTip; oscInTip.text = translation.translateKey(""enable incoming OSC""); oscInTip.sourceRect = *enableOSCInToggle->getRect(); oscInTip.displayPoint = ofVec2f(oscInTip.sourceRect.x, 55); tooltips.push_back(oscInTip); //osc In Port Tooltip oscInPortTip; oscInPortTip.text = translation.translateKey(""incoming OSC port""); oscInPortTip.sourceRect = *oscInPortInput->getRect(); oscInPortTip.displayPoint = ofVec2f(oscInPortTip.sourceRect.x, 55); tooltips.push_back(oscInPortTip); //osc Out Tooltip oscOutTip; oscOutTip.text = translation.translateKey(""enable outgoing OSC""); oscOutTip.sourceRect = *enableOSCOutToggle->getRect(); oscOutTip.displayPoint = ofVec2f(oscOutTip.sourceRect.x, 55); tooltips.push_back(oscOutTip); //osc Out IP Tooltip oscOutIPTip; oscOutIPTip.text = translation.translateKey(""remote IP""); oscOutIPTip.sourceRect = *oscOutIPInput->getRect(); oscOutIPTip.displayPoint = ofVec2f(oscOutIPTip.sourceRect.x, 55); tooltips.push_back(oscOutIPTip); //osc Out IP Tooltip oscOutPortTip; oscOutPortTip.text = translation.translateKey(""remote port""); oscOutPortTip.sourceRect = *oscOutPortInput->getRect(); oscOutPortTip.displayPoint = ofVec2f(oscOutPortTip.sourceRect.x, 55); tooltips.push_back(oscOutPortTip); for(int i = 0; i < tooltips.size(); i++){ tooltips[i].debugColor = ofColor::fromHsb(ofRandom(255), ofRandom(255,200), ofRandom(255,200)); } } void DurationController::drawTooltips(){ ofVec2f mousepoint(ofGetMouseX(), ofGetMouseY()); for(int i = 0; i < tooltips.size(); i++){ if(tooltips[i].sourceRect.inside(mousepoint)){ tooltipFont.drawString(tooltips[i].text, tooltips[i].displayPoint.x, tooltips[i].displayPoint.y); } } } void DurationController::drawTooltipDebug(){ //draw tool tip position finder tooltipFont.drawString(""(""+ofToString(ofGetMouseX())+"",""+ofToString(ofGetMouseY())+"")"", ofGetMouseX(), ofGetMouseY()); //draw tooltip debug balloons ofPushStyle(); for(int i = 0; i < tooltips.size(); i++){ ofNoFill(); ofSetColor(tooltips[i].debugColor, 200); ofRect(tooltips[i].sourceRect); ofLine(tooltips[i].sourceRect.getMax(), tooltips[i].displayPoint); ofFill(); ofSetColor(tooltips[i].debugColor, 50); ofRect(tooltips[i].sourceRect); ofSetColor(255); tooltipFont.drawString(tooltips[i].text, tooltips[i].sourceRect.x+5,tooltips[i].sourceRect.y+10); } ofPopStyle(); } void DurationController::exit(ofEventArgs& e){ lock(); timeline.removeFromThread(); headers.clear(); timeline.reset(); unlock(); ofLogNotice(""DurationController"") << ""waiting for thread on exit""; waitForThread(true); } ",16260,True,2935.602645297804,median "#include ""pch.h"" /* ** $Id: lcode.c $ ** Code generator for Lua ** See Copyright Notice in lua.h */ #define lcode_c #define LUA_CORE #include ""lprefix.h"" #include #include #include #include ""lua.h"" #include ""lcode.h"" #include ""ldebug.h"" #include ""ldo.h"" #include ""lgc.h"" #include ""llex.h"" #include ""lmem.h"" #include ""lobject.h"" #include ""lopcodes.h"" #include ""lparser.h"" #include ""lstring.h"" #include ""ltable.h"" #include ""lvm.h"" /* Maximum number of registers in a Lua function (must fit in 8 bits) */ #define MAXREGS 255 #define hasjumps(e) ((e)->t != (e)->f) static int codesJ (FuncState *fs, OpCode o, int sj, int k); /* semantic error */ l_noret luaK_semerror (LexState *ls, const char *msg) { ls->t.token = 0; /* remove ""near "" from final message */ luaX_syntaxerror(ls, msg); } /* ** If expression is a numeric constant, fills 'v' with its value ** and returns 1. Otherwise, returns 0. */ static int tonumeral (const expdesc *e, TValue *v) { if (hasjumps(e)) return 0; /* not a numeral */ switch (e->k) { case VKINT: if (v) setivalue(v, e->u.ival); return 1; case VKFLT: if (v) setfltvalue(v, e->u.nval); return 1; default: return 0; } } /* ** Get the constant value from a constant expression */ static TValue *const2val (FuncState *fs, const expdesc *e) { lua_assert(e->k == VCONST); return &fs->ls->dyd->actvar.arr[e->u.info].k; } /* ** If expression is a constant, fills 'v' with its value ** and returns 1. Otherwise, returns 0. */ int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) { if (hasjumps(e)) return 0; /* not a constant */ switch (e->k) { case VFALSE: setbfvalue(v); return 1; case VTRUE: setbtvalue(v); return 1; case VNIL: setnilvalue(v); return 1; case VKSTR: { setsvalue(fs->ls->L, v, e->u.strval); return 1; } case VCONST: { setobj(fs->ls->L, v, const2val(fs, e)); return 1; } default: return tonumeral(e, v); } } /* ** Return the previous instruction of the current code. If there ** may be a jump target between the current instruction and the ** previous one, return an invalid instruction (to avoid wrong ** optimizations). */ static Instruction *previousinstruction (FuncState *fs) { static const Instruction invalidinstruction = ~(Instruction)0; if (fs->pc > fs->lasttarget) return &fs->f->code[fs->pc - 1]; /* previous instruction */ else return cast(Instruction*, &invalidinstruction); } /* ** Create a OP_LOADNIL instruction, but try to optimize: if the previous ** instruction is also OP_LOADNIL and ranges are compatible, adjust ** range of previous instruction instead of emitting a new one. (For ** instance, 'local a; local b' will generate a single opcode.) */ void luaK_nil (FuncState *fs, int from, int n) { int l = from + n - 1; /* last register to set nil */ Instruction *previous = previousinstruction(fs); if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */ int pfrom = GETARG_A(*previous); /* get previous range */ int pl = pfrom + GETARG_B(*previous); if ((pfrom <= from && from <= pl + 1) || (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ if (pl > l) l = pl; /* l = max(l, pl) */ SETARG_A(*previous, from); SETARG_B(*previous, l - from); return; } /* else go through */ } luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ } /* ** Gets the destination address of a jump instruction. Used to traverse ** a list of jumps. */ static int getjump (FuncState *fs, int pc) { int offset = GETARG_sJ(fs->f->code[pc]); if (offset == NO_JUMP) /* point to itself represents end of list */ return NO_JUMP; /* end of list */ else return (pc+1)+offset; /* turn offset into absolute position */ } /* ** Fix jump instruction at position 'pc' to jump to 'dest'. ** (Jump addresses are relative in Lua) */ static void fixjump (FuncState *fs, int pc, int dest) { Instruction *jmp = &fs->f->code[pc]; int offset = dest - (pc + 1); lua_assert(dest != NO_JUMP); if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ)) luaX_syntaxerror(fs->ls, ""control structure too long""); lua_assert(GET_OPCODE(*jmp) == OP_JMP); SETARG_sJ(*jmp, offset); } /* ** Concatenate jump-list 'l2' into jump-list 'l1' */ void luaK_concat (FuncState *fs, int *l1, int l2) { if (l2 == NO_JUMP) return; /* nothing to concatenate? */ else if (*l1 == NO_JUMP) /* no original list? */ *l1 = l2; /* 'l1' points to 'l2' */ else { int list = *l1; int next; while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ list = next; fixjump(fs, list, l2); /* last element links to 'l2' */ } } /* ** Create a jump instruction and return its position, so its destination ** can be fixed later (with 'fixjump'). */ int luaK_jump (FuncState *fs) { return codesJ(fs, OP_JMP, NO_JUMP, 0); } /* ** Code a 'return' instruction */ void luaK_ret (FuncState *fs, int first, int nret) { OpCode op; switch (nret) { case 0: op = OP_RETURN0; break; case 1: op = OP_RETURN1; break; default: op = OP_RETURN; break; } luaK_codeABC(fs, op, first, nret + 1, 0); } /* ** Code a ""conditional jump"", that is, a test or comparison opcode ** followed by a jump. Return jump position. */ static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) { luaK_codeABCk(fs, op, A, B, C, k); return luaK_jump(fs); } /* ** returns current 'pc' and marks it as a jump target (to avoid wrong ** optimizations with consecutive instructions not in the same basic block). */ int luaK_getlabel (FuncState *fs) { fs->lasttarget = fs->pc; return fs->pc; } /* ** Returns the position of the instruction ""controlling"" a given ** jump (that is, its condition), or the jump itself if it is ** unconditional. */ static Instruction *getjumpcontrol (FuncState *fs, int pc) { Instruction *pi = &fs->f->code[pc]; if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) return pi-1; else return pi; } /* ** Patch destination register for a TESTSET instruction. ** If instruction in position 'node' is not a TESTSET, return 0 (""fails""). ** Otherwise, if 'reg' is not 'NO_REG', set it as the destination ** register. Otherwise, change instruction to a simple 'TEST' (produces ** no register value) */ static int patchtestreg (FuncState *fs, int node, int reg) { Instruction *i = getjumpcontrol(fs, node); if (GET_OPCODE(*i) != OP_TESTSET) return 0; /* cannot patch other instructions */ if (reg != NO_REG && reg != GETARG_B(*i)) SETARG_A(*i, reg); else { /* no register to put value or register already has the value; change instruction to simple test */ *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i)); } return 1; } /* ** Traverse a list of tests ensuring no one produces a value */ static void removevalues (FuncState *fs, int list) { for (; list != NO_JUMP; list = getjump(fs, list)) patchtestreg(fs, list, NO_REG); } /* ** Traverse a list of tests, patching their destination address and ** registers: tests producing values jump to 'vtarget' (and put their ** values in 'reg'), other tests jump to 'dtarget'. */ static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, int dtarget) { while (list != NO_JUMP) { int next = getjump(fs, list); if (patchtestreg(fs, list, reg)) fixjump(fs, list, vtarget); else fixjump(fs, list, dtarget); /* jump to default target */ list = next; } } /* ** Path all jumps in 'list' to jump to 'target'. ** (The assert means that we cannot fix a jump to a forward address ** because we only know addresses once code is generated.) */ void luaK_patchlist (FuncState *fs, int list, int target) { lua_assert(target <= fs->pc); patchlistaux(fs, list, target, NO_REG, target); } void luaK_patchtohere (FuncState *fs, int list) { int hr = luaK_getlabel(fs); /* mark ""here"" as a jump target */ luaK_patchlist(fs, list, hr); } /* limit for difference between lines in relative line info. */ #define LIMLINEDIFF 0x80 /* ** Save line info for a new instruction. If difference from last line ** does not fit in a byte, of after that many instructions, save a new ** absolute line info; (in that case, the special value 'ABSLINEINFO' ** in 'lineinfo' signals the existence of this absolute information.) ** Otherwise, store the difference from last line in 'lineinfo'. */ static void savelineinfo (FuncState *fs, Proto *f, int line) { int linedif = line - fs->previousline; int pc = fs->pc - 1; /* last instruction coded */ if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) { luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo, f->sizeabslineinfo, AbsLineInfo, MAX_INT, ""lines""); f->abslineinfo[fs->nabslineinfo].pc = pc; f->abslineinfo[fs->nabslineinfo++].line = line; linedif = ABSLINEINFO; /* signal that there is absolute information */ fs->iwthabs = 1; /* restart counter */ } luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte, MAX_INT, ""opcodes""); f->lineinfo[pc] = linedif; fs->previousline = line; /* last line saved */ } /* ** Remove line information from the last instruction. ** If line information for that instruction is absolute, set 'iwthabs' ** above its max to force the new (replacing) instruction to have ** absolute line info, too. */ static void removelastlineinfo (FuncState *fs) { Proto *f = fs->f; int pc = fs->pc - 1; /* last instruction coded */ if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */ fs->previousline -= f->lineinfo[pc]; /* correct last line saved */ fs->iwthabs--; /* undo previous increment */ } else { /* absolute line information */ lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc); fs->nabslineinfo--; /* remove it */ fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */ } } /* ** Remove the last instruction created, correcting line information ** accordingly. */ static void removelastinstruction (FuncState *fs) { removelastlineinfo(fs); fs->pc--; } /* ** Emit instruction 'i', checking for array sizes and saving also its ** line information. Return 'i' position. */ int luaK_code (FuncState *fs, Instruction i) { Proto *f = fs->f; /* put new instruction in code array */ luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, MAX_INT, ""opcodes""); f->code[fs->pc++] = i; savelineinfo(fs, f, fs->ls->lastline); return fs->pc - 1; /* index of new instruction */ } /* ** Format and emit an 'iABC' instruction. (Assertions check consistency ** of parameters versus opcode.) */ int luaK_codeABCk (FuncState *fs, OpCode o, int a, int b, int c, int k) { lua_assert(getOpMode(o) == iABC); lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C && (k & ~1) == 0); return luaK_code(fs, CREATE_ABCk(o, a, b, c, k)); } /* ** Format and emit an 'iABx' instruction. */ int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { lua_assert(getOpMode(o) == iABx); lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); return luaK_code(fs, CREATE_ABx(o, a, bc)); } /* ** Format and emit an 'iAsBx' instruction. */ int luaK_codeAsBx (FuncState *fs, OpCode o, int a, int bc) { unsigned int b = bc + OFFSET_sBx; lua_assert(getOpMode(o) == iAsBx); lua_assert(a <= MAXARG_A && b <= MAXARG_Bx); return luaK_code(fs, CREATE_ABx(o, a, b)); } /* ** Format and emit an 'isJ' instruction. */ static int codesJ (FuncState *fs, OpCode o, int sj, int k) { unsigned int j = sj + OFFSET_sJ; lua_assert(getOpMode(o) == isJ); lua_assert(j <= MAXARG_sJ && (k & ~1) == 0); return luaK_code(fs, CREATE_sJ(o, j, k)); } /* ** Emit an ""extra argument"" instruction (format 'iAx') */ static int codeextraarg (FuncState *fs, int a) { lua_assert(a <= MAXARG_Ax); return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); } /* ** Emit a ""load constant"" instruction, using either 'OP_LOADK' ** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX' ** instruction with ""extra argument"". */ static int luaK_codek (FuncState *fs, int reg, int k) { if (k <= MAXARG_Bx) return luaK_codeABx(fs, OP_LOADK, reg, k); else { int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); codeextraarg(fs, k); return p; } } /* ** Check register-stack level, keeping track of its maximum size ** in field 'maxstacksize' */ void luaK_checkstack (FuncState *fs, int n) { int newstack = fs->freereg + n; if (newstack > fs->f->maxstacksize) { if (newstack >= MAXREGS) luaX_syntaxerror(fs->ls, ""function or expression needs too many registers""); fs->f->maxstacksize = cast_byte(newstack); } } /* ** Reserve 'n' registers in register stack */ void luaK_reserveregs (FuncState *fs, int n) { luaK_checkstack(fs, n); fs->freereg += n; } /* ** Free register 'reg', if it is neither a constant index nor ** a local variable. ) */ static void freereg (FuncState *fs, int reg) { if (reg >= luaY_nvarstack(fs)) { fs->freereg--; lua_assert(reg == fs->freereg); } } /* ** Free two registers in proper order */ static void freeregs (FuncState *fs, int r1, int r2) { if (r1 > r2) { freereg(fs, r1); freereg(fs, r2); } else { freereg(fs, r2); freereg(fs, r1); } } /* ** Free register used by expression 'e' (if any) */ static void freeexp (FuncState *fs, expdesc *e) { if (e->k == VNONRELOC) freereg(fs, e->u.info); } /* ** Free registers used by expressions 'e1' and 'e2' (if any) in proper ** order. */ static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) { int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1; int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1; freeregs(fs, r1, r2); } /* ** Add constant 'v' to prototype's list of constants (field 'k'). ** Use scanner's table to cache position of constants in constant list ** and try to reuse constants. Because some values should not be used ** as keys (nil cannot be a key, integer keys can collapse with float ** keys), the caller must provide a useful 'key' for indexing the cache. ** Note that all functions share the same table, so entering or exiting ** a function can make some indices wrong. */ static int addk (FuncState *fs, TValue *key, TValue *v) { TValue val; lua_State *L = fs->ls->L; Proto *f = fs->f; const TValue *idx = luaH_get(fs->ls->h, key); /* query scanner table */ int k, oldsize; if (ttisinteger(idx)) { /* is there an index there? */ k = cast_int(ivalue(idx)); /* correct value? (warning: must distinguish floats from integers!) */ if (k < fs->nk && ttypetag(&f->k[k]) == ttypetag(v) && luaV_rawequalobj(&f->k[k], v)) return k; /* reuse index */ } /* constant not found; create a new entry */ oldsize = f->sizek; k = fs->nk; /* numerical value does not need GC barrier; table has no metatable, so it does not need to invalidate cache */ setivalue(&val, k); luaH_finishset(L, fs->ls->h, key, idx, &val); luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, ""constants""); while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); setobj(L, &f->k[k], v); fs->nk++; luaC_barrier(L, f, v); return k; } /* ** Add a string to list of constants and return its index. */ static int stringK (FuncState *fs, TString *s) { TValue o; setsvalue(fs->ls->L, &o, s); return addk(fs, &o, &o); /* use string itself as key */ } /* ** Add an integer to list of constants and return its index. ** Integers use userdata as keys to avoid collision with floats with ** same value; conversion to 'void*' is used only for hashing, so there ** are no ""precision"" problems. */ static int luaK_intK (FuncState *fs, lua_Integer n) { TValue k, o; setpvalue(&k, cast_voidp(cast_sizet(n))); setivalue(&o, n); return addk(fs, &k, &o); } /* ** Add a float to list of constants and return its index. */ static int luaK_numberK (FuncState *fs, lua_Number r) { TValue o; setfltvalue(&o, r); return addk(fs, &o, &o); /* use number itself as key */ } /* ** Add a false to list of constants and return its index. */ static int boolF (FuncState *fs) { TValue o; setbfvalue(&o); return addk(fs, &o, &o); /* use boolean itself as key */ } /* ** Add a true to list of constants and return its index. */ static int boolT (FuncState *fs) { TValue o; setbtvalue(&o); return addk(fs, &o, &o); /* use boolean itself as key */ } /* ** Add nil to list of constants and return its index. */ static int nilK (FuncState *fs) { TValue k, v; setnilvalue(&v); /* cannot use nil as key; instead use table itself to represent nil */ sethvalue(fs->ls->L, &k, fs->ls->h); return addk(fs, &k, &v); } /* ** Check whether 'i' can be stored in an 'sC' operand. Equivalent to ** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of ** overflows in the hidden addition inside 'int2sC'. */ static int fitsC (lua_Integer i) { return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C)); } /* ** Check whether 'i' can be stored in an 'sBx' operand. */ static int fitsBx (lua_Integer i) { return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx); } void luaK_int (FuncState *fs, int reg, lua_Integer i) { if (fitsBx(i)) luaK_codeAsBx(fs, OP_LOADI, reg, cast_int(i)); else luaK_codek(fs, reg, luaK_intK(fs, i)); } static void luaK_float (FuncState *fs, int reg, lua_Number f) { lua_Integer fi; if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi)) luaK_codeAsBx(fs, OP_LOADF, reg, cast_int(fi)); else luaK_codek(fs, reg, luaK_numberK(fs, f)); } /* ** Convert a constant in 'v' into an expression description 'e' */ static void const2exp (TValue *v, expdesc *e) { switch (ttypetag(v)) { case LUA_VNUMINT: e->k = VKINT; e->u.ival = ivalue(v); break; case LUA_VNUMFLT: e->k = VKFLT; e->u.nval = fltvalue(v); break; case LUA_VFALSE: e->k = VFALSE; break; case LUA_VTRUE: e->k = VTRUE; break; case LUA_VNIL: e->k = VNIL; break; case LUA_VSHRSTR: case LUA_VLNGSTR: e->k = VKSTR; e->u.strval = tsvalue(v); break; default: lua_assert(0); } } /* ** Fix an expression to return the number of results 'nresults'. ** 'e' must be a multi-ret expression (function call or vararg). */ void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { Instruction *pc = &getinstruction(fs, e); if (e->k == VCALL) /* expression is an open function call? */ SETARG_C(*pc, nresults + 1); else { lua_assert(e->k == VVARARG); SETARG_C(*pc, nresults + 1); SETARG_A(*pc, fs->freereg); luaK_reserveregs(fs, 1); } } /* ** Convert a VKSTR to a VK */ static void str2K (FuncState *fs, expdesc *e) { lua_assert(e->k == VKSTR); e->u.info = stringK(fs, e->u.strval); e->k = VK; } /* ** Fix an expression to return one result. ** If expression is not a multi-ret expression (function call or ** vararg), it already returns one result, so nothing needs to be done. ** Function calls become VNONRELOC expressions (as its result comes ** fixed in the base register of the call), while vararg expressions ** become VRELOC (as OP_VARARG puts its results where it wants). ** (Calls are created returning one result, so that does not need ** to be fixed.) */ void luaK_setoneret (FuncState *fs, expdesc *e) { if (e->k == VCALL) { /* expression is an open function call? */ /* already returns 1 value */ lua_assert(GETARG_C(getinstruction(fs, e)) == 2); e->k = VNONRELOC; /* result has fixed position */ e->u.info = GETARG_A(getinstruction(fs, e)); } else if (e->k == VVARARG) { SETARG_C(getinstruction(fs, e), 2); e->k = VRELOC; /* can relocate its simple result */ } } /* ** Ensure that expression 'e' is not a variable (nor a ). ** (Expression still may have jump lists.) */ void luaK_dischargevars (FuncState *fs, expdesc *e) { switch (e->k) { case VCONST: { const2exp(const2val(fs, e), e); break; } case VLOCAL: { /* already in a register */ e->u.info = e->u.var.ridx; e->k = VNONRELOC; /* becomes a non-relocatable value */ break; } case VUPVAL: { /* move value to some (pending) register */ e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); e->k = VRELOC; break; } case VINDEXUP: { e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VINDEXI: { freereg(fs, e->u.ind.t); e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VINDEXSTR: { freereg(fs, e->u.ind.t); e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VINDEXED: { freeregs(fs, e->u.ind.t, e->u.ind.idx); e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VVARARG: case VCALL: { luaK_setoneret(fs, e); break; } default: break; /* there is one value available (somewhere) */ } } /* ** Ensure expression value is in register 'reg', making 'e' a ** non-relocatable expression. ** (Expression still may have jump lists.) */ static void discharge2reg (FuncState *fs, expdesc *e, int reg) { luaK_dischargevars(fs, e); switch (e->k) { case VNIL: { luaK_nil(fs, reg, 1); break; } case VFALSE: { luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0); break; } case VTRUE: { luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0); break; } case VKSTR: { str2K(fs, e); } /* FALLTHROUGH */ case VK: { luaK_codek(fs, reg, e->u.info); break; } case VKFLT: { luaK_float(fs, reg, e->u.nval); break; } case VKINT: { luaK_int(fs, reg, e->u.ival); break; } case VRELOC: { Instruction *pc = &getinstruction(fs, e); SETARG_A(*pc, reg); /* instruction will put result in 'reg' */ break; } case VNONRELOC: { if (reg != e->u.info) luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); break; } default: { lua_assert(e->k == VJMP); return; /* nothing to do... */ } } e->u.info = reg; e->k = VNONRELOC; } /* ** Ensure expression value is in a register, making 'e' a ** non-relocatable expression. ** (Expression still may have jump lists.) */ static void discharge2anyreg (FuncState *fs, expdesc *e) { if (e->k != VNONRELOC) { /* no fixed register yet? */ luaK_reserveregs(fs, 1); /* get a register */ discharge2reg(fs, e, fs->freereg-1); /* put value there */ } } static int code_loadbool (FuncState *fs, int A, OpCode op) { luaK_getlabel(fs); /* those instructions may be jump targets */ return luaK_codeABC(fs, op, A, 0, 0); } /* ** check whether list has any jump that do not produce a value ** or produce an inverted value */ static int need_value (FuncState *fs, int list) { for (; list != NO_JUMP; list = getjump(fs, list)) { Instruction i = *getjumpcontrol(fs, list); if (GET_OPCODE(i) != OP_TESTSET) return 1; } return 0; /* not found */ } /* ** Ensures final expression result (which includes results from its ** jump lists) is in register 'reg'. ** If expression has jumps, need to patch these jumps either to ** its final position or to ""load"" instructions (for those tests ** that do not produce values). */ static void exp2reg (FuncState *fs, expdesc *e, int reg) { discharge2reg(fs, e, reg); if (e->k == VJMP) /* expression itself is a test? */ luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ if (hasjumps(e)) { int final; /* position after whole expression */ int p_f = NO_JUMP; /* position of an eventual LOAD false */ int p_t = NO_JUMP; /* position of an eventual LOAD true */ if (need_value(fs, e->t) || need_value(fs, e->f)) { int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */ p_t = code_loadbool(fs, reg, OP_LOADTRUE); /* jump around these booleans if 'e' is not a test */ luaK_patchtohere(fs, fj); } final = luaK_getlabel(fs); patchlistaux(fs, e->f, final, reg, p_f); patchlistaux(fs, e->t, final, reg, p_t); } e->f = e->t = NO_JUMP; e->u.info = reg; e->k = VNONRELOC; } /* ** Ensures final expression result is in next available register. */ void luaK_exp2nextreg (FuncState *fs, expdesc *e) { luaK_dischargevars(fs, e); freeexp(fs, e); luaK_reserveregs(fs, 1); exp2reg(fs, e, fs->freereg - 1); } /* ** Ensures final expression result is in some (any) register ** and return that register. */ int luaK_exp2anyreg (FuncState *fs, expdesc *e) { luaK_dischargevars(fs, e); if (e->k == VNONRELOC) { /* expression already has a register? */ if (!hasjumps(e)) /* no jumps? */ return e->u.info; /* result is already in a register */ if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */ exp2reg(fs, e, e->u.info); /* put final result in it */ return e->u.info; } /* else expression has jumps and cannot change its register to hold the jump values, because it is a local variable. Go through to the default case. */ } luaK_exp2nextreg(fs, e); /* default: use next available register */ return e->u.info; } /* ** Ensures final expression result is either in a register ** or in an upvalue. */ void luaK_exp2anyregup (FuncState *fs, expdesc *e) { if (e->k != VUPVAL || hasjumps(e)) luaK_exp2anyreg(fs, e); } /* ** Ensures final expression result is either in a register ** or it is a constant. */ void luaK_exp2val (FuncState *fs, expdesc *e) { if (hasjumps(e)) luaK_exp2anyreg(fs, e); else luaK_dischargevars(fs, e); } /* ** Try to make 'e' a K expression with an index in the range of R/K ** indices. Return true iff succeeded. */ static int luaK_exp2K (FuncState *fs, expdesc *e) { if (!hasjumps(e)) { int info; switch (e->k) { /* move constants to 'k' */ case VTRUE: info = boolT(fs); break; case VFALSE: info = boolF(fs); break; case VNIL: info = nilK(fs); break; case VKINT: info = luaK_intK(fs, e->u.ival); break; case VKFLT: info = luaK_numberK(fs, e->u.nval); break; case VKSTR: info = stringK(fs, e->u.strval); break; case VK: info = e->u.info; break; default: return 0; /* not a constant */ } if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */ e->k = VK; /* make expression a 'K' expression */ e->u.info = info; return 1; } } /* else, expression doesn't fit; leave it unchanged */ return 0; } /* ** Ensures final expression result is in a valid R/K index ** (that is, it is either in a register or in 'k' with an index ** in the range of R/K indices). ** Returns 1 iff expression is K. */ int luaK_exp2RK (FuncState *fs, expdesc *e) { if (luaK_exp2K(fs, e)) return 1; else { /* not a constant in the right range: put it in a register */ luaK_exp2anyreg(fs, e); return 0; } } static void codeABRK (FuncState *fs, OpCode o, int a, int b, expdesc *ec) { int k = luaK_exp2RK(fs, ec); luaK_codeABCk(fs, o, a, b, ec->u.info, k); } /* ** Generate code to store result of expression 'ex' into variable 'var'. */ void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { switch (var->k) { case VLOCAL: { freeexp(fs, ex); exp2reg(fs, ex, var->u.var.ridx); /* compute 'ex' into proper place */ return; } case VUPVAL: { int e = luaK_exp2anyreg(fs, ex); luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); break; } case VINDEXUP: { codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex); break; } case VINDEXI: { codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex); break; } case VINDEXSTR: { codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex); break; } case VINDEXED: { codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex); break; } default: lua_assert(0); /* invalid var kind to store */ } freeexp(fs, ex); } /* ** Emit SELF instruction (convert expression 'e' into 'e:key(e,'). */ void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { int ereg; luaK_exp2anyreg(fs, e); ereg = e->u.info; /* register where 'e' was placed */ freeexp(fs, e); e->u.info = fs->freereg; /* base register for op_self */ e->k = VNONRELOC; /* self expression has a fixed register */ luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ codeABRK(fs, OP_SELF, e->u.info, ereg, key); freeexp(fs, key); } /* ** Negate condition 'e' (where 'e' is a comparison). */ static void negatecondition (FuncState *fs, expdesc *e) { Instruction *pc = getjumpcontrol(fs, e->u.info); lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && GET_OPCODE(*pc) != OP_TEST); SETARG_k(*pc, (GETARG_k(*pc) ^ 1)); } /* ** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond' ** is true, code will jump if 'e' is true.) Return jump position. ** Optimize when 'e' is 'not' something, inverting the condition ** and removing the 'not'. */ static int jumponcond (FuncState *fs, expdesc *e, int cond) { if (e->k == VRELOC) { Instruction ie = getinstruction(fs, e); if (GET_OPCODE(ie) == OP_NOT) { removelastinstruction(fs); /* remove previous OP_NOT */ return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond); } /* else go through */ } discharge2anyreg(fs, e); freeexp(fs, e); return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond); } /* ** Emit code to go through if 'e' is true, jump otherwise. */ void luaK_goiftrue (FuncState *fs, expdesc *e) { int pc; /* pc of new jump */ luaK_dischargevars(fs, e); switch (e->k) { case VJMP: { /* condition? */ negatecondition(fs, e); /* jump when it is false */ pc = e->u.info; /* save jump position */ break; } case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { pc = NO_JUMP; /* always true; do nothing */ break; } default: { pc = jumponcond(fs, e, 0); /* jump when false */ break; } } luaK_concat(fs, &e->f, pc); /* insert new jump in false list */ luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */ e->t = NO_JUMP; } /* ** Emit code to go through if 'e' is false, jump otherwise. */ void luaK_goiffalse (FuncState *fs, expdesc *e) { int pc; /* pc of new jump */ luaK_dischargevars(fs, e); switch (e->k) { case VJMP: { pc = e->u.info; /* already jump if true */ break; } case VNIL: case VFALSE: { pc = NO_JUMP; /* always false; do nothing */ break; } default: { pc = jumponcond(fs, e, 1); /* jump if true */ break; } } luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */ luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */ e->f = NO_JUMP; } /* ** Code 'not e', doing constant folding. */ static void codenot (FuncState *fs, expdesc *e) { switch (e->k) { case VNIL: case VFALSE: { e->k = VTRUE; /* true == not nil == not false */ break; } case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { e->k = VFALSE; /* false == not ""x"" == not 0.5 == not 1 == not true */ break; } case VJMP: { negatecondition(fs, e); break; } case VRELOC: case VNONRELOC: { discharge2anyreg(fs, e); freeexp(fs, e); e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); e->k = VRELOC; break; } default: lua_assert(0); /* cannot happen */ } /* interchange true and false lists */ { int temp = e->f; e->f = e->t; e->t = temp; } removevalues(fs, e->f); /* values are useless when negated */ removevalues(fs, e->t); } /* ** Check whether expression 'e' is a small literal string */ static int isKstr (FuncState *fs, expdesc *e) { return (e->k == VK && !hasjumps(e) && e->u.info <= MAXARG_B && ttisshrstring(&fs->f->k[e->u.info])); } /* ** Check whether expression 'e' is a literal integer. */ int luaK_isKint (expdesc *e) { return (e->k == VKINT && !hasjumps(e)); } /* ** Check whether expression 'e' is a literal integer in ** proper range to fit in register C */ static int isCint (expdesc *e) { return luaK_isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C)); } /* ** Check whether expression 'e' is a literal integer in ** proper range to fit in register sC */ static int isSCint (expdesc *e) { return luaK_isKint(e) && fitsC(e->u.ival); } /* ** Check whether expression 'e' is a literal integer or float in ** proper range to fit in a register (sB or sC). */ static int isSCnumber (expdesc *e, int *pi, int *isfloat) { lua_Integer i; if (e->k == VKINT) i = e->u.ival; else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq)) *isfloat = 1; else return 0; /* not a number */ if (!hasjumps(e) && fitsC(i)) { *pi = int2sC(cast_int(i)); return 1; } else return 0; } /* ** Create expression 't[k]'. 't' must have its final result already in a ** register or upvalue. Upvalues can only be indexed by literal strings. ** Keys can be literal strings in the constant table or arbitrary ** values in registers. */ void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { if (k->k == VKSTR) str2K(fs, k); lua_assert(!hasjumps(t) && (t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL)); if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */ luaK_exp2anyreg(fs, t); /* put it in a register */ if (t->k == VUPVAL) { t->u.ind.t = t->u.info; /* upvalue index */ t->u.ind.idx = k->u.info; /* literal string */ t->k = VINDEXUP; } else { /* register index of the table */ t->u.ind.t = (t->k == VLOCAL) ? t->u.var.ridx: t->u.info; if (isKstr(fs, k)) { t->u.ind.idx = k->u.info; /* literal string */ t->k = VINDEXSTR; } else if (isCint(k)) { t->u.ind.idx = cast_int(k->u.ival); /* int. constant in proper range */ t->k = VINDEXI; } else { t->u.ind.idx = luaK_exp2anyreg(fs, k); /* register */ t->k = VINDEXED; } } } /* ** Return false if folding can raise an error. ** Bitwise operations need operands convertible to integers; division ** operations cannot have 0 as divisor. */ static int validop (int op, TValue *v1, TValue *v2) { switch (op) { case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */ lua_Integer i; return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) && luaV_tointegerns(v2, &i, LUA_FLOORN2I)); } case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ return (nvalue(v2) != 0); default: return 1; /* everything else is valid */ } } /* ** Try to ""constant-fold"" an operation; return 1 iff successful. ** (In this case, 'e1' has the final result.) */ static int constfolding (FuncState *fs, int op, expdesc *e1, const expdesc *e2) { TValue v1, v2, res; if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2)) return 0; /* non-numeric operands or not safe to fold */ luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */ if (ttisinteger(&res)) { e1->k = VKINT; e1->u.ival = ivalue(&res); } else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */ lua_Number n = fltvalue(&res); if (luai_numisnan(n) || n == 0) return 0; e1->k = VKFLT; e1->u.nval = n; } return 1; } /* ** Emit code for unary expressions that ""produce values"" ** (everything but 'not'). ** Expression to produce final result will be encoded in 'e'. */ static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) { int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */ freeexp(fs, e); e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */ e->k = VRELOC; /* all those operations are relocatable */ luaK_fixline(fs, line); } /* ** Emit code for binary expressions that ""produce values"" ** (everything but logical operators 'and'/'or' and comparison ** operators). ** Expression to produce final result will be encoded in 'e1'. */ static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2, OpCode op, int v2, int flip, int line, OpCode mmop, TMS event) { int v1 = luaK_exp2anyreg(fs, e1); int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0); freeexps(fs, e1, e2); e1->u.info = pc; e1->k = VRELOC; /* all those operations are relocatable */ luaK_fixline(fs, line); luaK_codeABCk(fs, mmop, v1, v2, event, flip); /* to call metamethod */ luaK_fixline(fs, line); } /* ** Emit code for binary expressions that ""produce values"" over ** two registers. */ static void codebinexpval (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2, int line) { int v2 = luaK_exp2anyreg(fs, e2); /* both operands are in registers */ lua_assert(OP_ADD <= op && op <= OP_SHR); finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN, cast(TMS, (op - OP_ADD) + TM_ADD)); } /* ** Code binary operators with immediate operands. */ static void codebini (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2, int flip, int line, TMS event) { int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */ lua_assert(e2->k == VKINT); finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event); } /* Try to code a binary operator negating its second operand. ** For the metamethod, 2nd operand must keep its original value. */ static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2, OpCode op, int line, TMS event) { if (!luaK_isKint(e2)) return 0; /* not an integer constant */ else { lua_Integer i2 = e2->u.ival; if (!(fitsC(i2) && fitsC(-i2))) return 0; /* not in the proper range */ else { /* operating a small integer constant */ int v2 = cast_int(i2); finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event); /* correct metamethod argument */ SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2)); return 1; /* successfully coded */ } } } static void swapexps (expdesc *e1, expdesc *e2) { expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */ } /* ** Code arithmetic operators ('+', '-', ...). If second operand is a ** constant in the proper range, use variant opcodes with K operands. */ static void codearith (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int flip, int line) { TMS event = cast(TMS, opr + TM_ADD); if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) { /* K operand? */ int v2 = e2->u.info; /* K index */ OpCode op = cast(OpCode, opr + OP_ADDK); finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event); } else { /* 'e2' is neither an immediate nor a K operand */ OpCode op = cast(OpCode, opr + OP_ADD); if (flip) swapexps(e1, e2); /* back to original order */ codebinexpval(fs, op, e1, e2, line); /* use standard operators */ } } /* ** Code commutative operators ('+', '*'). If first operand is a ** numeric constant, change order of operands to try to use an ** immediate or K operator. */ static void codecommutative (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2, int line) { int flip = 0; if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */ swapexps(e1, e2); /* change order */ flip = 1; } if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */ codebini(fs, cast(OpCode, OP_ADDI), e1, e2, flip, line, TM_ADD); else codearith(fs, op, e1, e2, flip, line); } /* ** Code bitwise operations; they are all associative, so the function ** tries to put an integer constant as the 2nd operand (a K operand). */ static void codebitwise (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int line) { int flip = 0; int v2; OpCode op; if (e1->k == VKINT && luaK_exp2RK(fs, e1)) { swapexps(e1, e2); /* 'e2' will be the constant operand */ flip = 1; } else if (!(e2->k == VKINT && luaK_exp2RK(fs, e2))) { /* no constants? */ op = cast(OpCode, opr + OP_ADD); codebinexpval(fs, op, e1, e2, line); /* all-register opcodes */ return; } v2 = e2->u.info; /* index in K array */ op = cast(OpCode, opr + OP_ADDK); lua_assert(ttisinteger(&fs->f->k[v2])); finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, cast(TMS, opr + TM_ADD)); } /* ** Emit code for order comparisons. When using an immediate operand, ** 'isfloat' tells whether the original value was a float. */ static void codeorder (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) { int r1, r2; int im; int isfloat = 0; if (isSCnumber(e2, &im, &isfloat)) { /* use immediate operand */ r1 = luaK_exp2anyreg(fs, e1); r2 = im; op = cast(OpCode, (op - OP_LT) + OP_LTI); } else if (isSCnumber(e1, &im, &isfloat)) { /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */ r1 = luaK_exp2anyreg(fs, e2); r2 = im; op = (op == OP_LT) ? OP_GTI : OP_GEI; } else { /* regular case, compare two registers */ r1 = luaK_exp2anyreg(fs, e1); r2 = luaK_exp2anyreg(fs, e2); } freeexps(fs, e1, e2); e1->u.info = condjump(fs, op, r1, r2, isfloat, 1); e1->k = VJMP; } /* ** Emit code for equality comparisons ('==', '~='). ** 'e1' was already put as RK by 'luaK_infix'. */ static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { int r1, r2; int im; int isfloat = 0; /* not needed here, but kept for symmetry */ OpCode op; if (e1->k != VNONRELOC) { lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT); swapexps(e1, e2); } r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */ if (isSCnumber(e2, &im, &isfloat)) { op = OP_EQI; r2 = im; /* immediate operand */ } else if (luaK_exp2RK(fs, e2)) { /* 1st expression is constant? */ op = OP_EQK; r2 = e2->u.info; /* constant index */ } else { op = OP_EQ; /* will compare two registers */ r2 = luaK_exp2anyreg(fs, e2); } freeexps(fs, e1, e2); e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ)); e1->k = VJMP; } /* ** Apply prefix operation 'op' to expression 'e'. */ void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) { static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP}; luaK_dischargevars(fs, e); switch (op) { case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */ if (constfolding(fs, op + LUA_OPUNM, e, &ef)) break; /* else */ /* FALLTHROUGH */ case OPR_LEN: codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line); break; case OPR_NOT: codenot(fs, e); break; default: lua_assert(0); } } /* ** Process 1st operand 'v' of binary operation 'op' before reading ** 2nd operand. */ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { luaK_dischargevars(fs, v); switch (op) { case OPR_AND: { luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */ break; } case OPR_OR: { luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */ break; } case OPR_CONCAT: { luaK_exp2nextreg(fs, v); /* operand must be on the stack */ break; } case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: case OPR_BAND: case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR: { if (!tonumeral(v, NULL)) luaK_exp2anyreg(fs, v); /* else keep numeral, which may be folded with 2nd operand */ break; } case OPR_EQ: case OPR_NE: { if (!tonumeral(v, NULL)) luaK_exp2RK(fs, v); /* else keep numeral, which may be an immediate operand */ break; } case OPR_LT: case OPR_LE: case OPR_GT: case OPR_GE: { int dummy, dummy2; if (!isSCnumber(v, &dummy, &dummy2)) luaK_exp2anyreg(fs, v); /* else keep numeral, which may be an immediate operand */ break; } default: lua_assert(0); } } /* ** Create code for '(e1 .. e2)'. ** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))', ** because concatenation is right associative), merge both CONCATs. */ static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) { Instruction *ie2 = previousinstruction(fs); if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */ int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */ lua_assert(e1->u.info + 1 == GETARG_A(*ie2)); freeexp(fs, e2); SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */ SETARG_B(*ie2, n + 1); /* will concatenate one more element */ } else { /* 'e2' is not a concatenation */ luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */ freeexp(fs, e2); luaK_fixline(fs, line); } } /* ** Finalize code for binary operation, after reading 2nd operand. */ void luaK_posfix (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int line) { luaK_dischargevars(fs, e2); if (foldbinop(opr) && constfolding(fs, opr + LUA_OPADD, e1, e2)) return; /* done by folding */ switch (opr) { case OPR_AND: { lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */ luaK_concat(fs, &e2->f, e1->f); *e1 = *e2; break; } case OPR_OR: { lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */ luaK_concat(fs, &e2->t, e1->t); *e1 = *e2; break; } case OPR_CONCAT: { /* e1 .. e2 */ luaK_exp2nextreg(fs, e2); codeconcat(fs, e1, e2, line); break; } case OPR_ADD: case OPR_MUL: { codecommutative(fs, opr, e1, e2, line); break; } case OPR_SUB: { if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB)) break; /* coded as (r1 + -I) */ /* ELSE */ } /* FALLTHROUGH */ case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: { codearith(fs, opr, e1, e2, 0, line); break; } case OPR_BAND: case OPR_BOR: case OPR_BXOR: { codebitwise(fs, opr, e1, e2, line); break; } case OPR_SHL: { if (isSCint(e1)) { swapexps(e1, e2); codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */ } else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) { /* coded as (r1 >> -I) */; } else /* regular case (two registers) */ codebinexpval(fs, OP_SHL, e1, e2, line); break; } case OPR_SHR: { if (isSCint(e2)) codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */ else /* regular case (two registers) */ codebinexpval(fs, OP_SHR, e1, e2, line); break; } case OPR_EQ: case OPR_NE: { codeeq(fs, opr, e1, e2); break; } case OPR_LT: case OPR_LE: { OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ); codeorder(fs, op, e1, e2); break; } case OPR_GT: case OPR_GE: { /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */ OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ); swapexps(e1, e2); codeorder(fs, op, e1, e2); break; } default: lua_assert(0); } } /* ** Change line information associated with current position, by removing ** previous info and adding it again with new line. */ void luaK_fixline (FuncState *fs, int line) { removelastlineinfo(fs); savelineinfo(fs, fs->f, line); } void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) { Instruction *inst = &fs->f->code[pc]; int rb = (hsize != 0) ? luaO_ceillog2(hsize) + 1 : 0; /* hash size */ int extra = asize / (MAXARG_C + 1); /* higher bits of array size */ int rc = asize % (MAXARG_C + 1); /* lower bits of array size */ int k = (extra > 0); /* true iff needs extra argument */ *inst = CREATE_ABCk(OP_NEWTABLE, ra, rb, rc, k); *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra); } /* ** Emit a SETLIST instruction. ** 'base' is register that keeps table; ** 'nelems' is #table plus those to be stored now; ** 'tostore' is number of values (in registers 'base + 1',...) to add to ** table (or LUA_MULTRET to add up to stack top). */ void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH); if (tostore == LUA_MULTRET) tostore = 0; if (nelems <= MAXARG_C) luaK_codeABC(fs, OP_SETLIST, base, tostore, nelems); else { int extra = nelems / (MAXARG_C + 1); nelems %= (MAXARG_C + 1); luaK_codeABCk(fs, OP_SETLIST, base, tostore, nelems, 1); codeextraarg(fs, extra); } fs->freereg = base + 1; /* free registers with list values */ } /* ** return the final target of a jump (skipping jumps to jumps) */ static int finaltarget (Instruction *code, int i) { int count; for (count = 0; count < 100; count++) { /* avoid infinite loops */ Instruction pc = code[i]; if (GET_OPCODE(pc) != OP_JMP) break; else i += GETARG_sJ(pc) + 1; } return i; } /* ** Do a final pass over the code of a function, doing small peephole ** optimizations and adjustments. */ void luaK_finish (FuncState *fs) { int i; Proto *p = fs->f; for (i = 0; i < fs->pc; i++) { Instruction *pc = &p->code[i]; lua_assert(i == 0 || isOT(*(pc - 1)) == isIT(*pc)); switch (GET_OPCODE(*pc)) { case OP_RETURN0: case OP_RETURN1: { if (!(fs->needclose || p->is_vararg)) break; /* no extra work */ /* else use OP_RETURN to do the extra work */ SET_OPCODE(*pc, OP_RETURN); } /* FALLTHROUGH */ case OP_RETURN: case OP_TAILCALL: { if (fs->needclose) SETARG_k(*pc, 1); /* signal that it needs to close */ if (p->is_vararg) SETARG_C(*pc, p->numparams + 1); /* signal that it is vararg */ break; } case OP_JMP: { int target = finaltarget(p->code, i); fixjump(fs, i, target); break; } default: break; } } } ",16252,True,3396.0530756184344,median "/* * Copyright (c) 2003-2020 Rony Shapiro . * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ /* * unicode2keysym - Contains a map between UNICODE wchar_t values and X keysyms * * This file is auto-generated using Misc/unicode2keysym.pl. Do not edit by hand!! * */ #include #include ""./unicode2keysym.h"" KeySym unicode2keysym(wchar_t wc) { switch (wc) { case 0x0100: return 0x03c0; // Amacron case 0x0101: return 0x03e0; // amacron case 0x0102: return 0x01c3; // Abreve case 0x0103: return 0x01e3; // abreve case 0x0104: return 0x01a1; // Aogonek case 0x0105: return 0x01b1; // aogonek case 0x0106: return 0x01c6; // Cacute case 0x0107: return 0x01e6; // cacute case 0x0108: return 0x02c6; // Ccircumflex case 0x0109: return 0x02e6; // ccircumflex case 0x010A: return 0x02c5; // Cabovedot case 0x010B: return 0x02e5; // cabovedot case 0x010C: return 0x01c8; // Ccaron case 0x010D: return 0x01e8; // ccaron case 0x010E: return 0x01cf; // Dcaron case 0x010F: return 0x01ef; // dcaron case 0x0110: return 0x01d0; // Dstroke case 0x0111: return 0x01f0; // dstroke case 0x0112: return 0x03aa; // Emacron case 0x0113: return 0x03ba; // emacron case 0x0116: return 0x03cc; // Eabovedot case 0x0117: return 0x03ec; // eabovedot case 0x0118: return 0x01ca; // Eogonek case 0x0119: return 0x01ea; // eogonek case 0x011A: return 0x01cc; // Ecaron case 0x011B: return 0x01ec; // ecaron case 0x011C: return 0x02d8; // Gcircumflex case 0x011D: return 0x02f8; // gcircumflex case 0x011E: return 0x02ab; // Gbreve case 0x011F: return 0x02bb; // gbreve case 0x0120: return 0x02d5; // Gabovedot case 0x0121: return 0x02f5; // gabovedot case 0x0122: return 0x03ab; // Gcedilla case 0x0123: return 0x03bb; // gcedilla case 0x0124: return 0x02a6; // Hcircumflex case 0x0125: return 0x02b6; // hcircumflex case 0x0126: return 0x02a1; // Hstroke case 0x0127: return 0x02b1; // hstroke case 0x0128: return 0x03a5; // Itilde case 0x0129: return 0x03b5; // itilde case 0x012A: return 0x03cf; // Imacron case 0x012B: return 0x03ef; // imacron case 0x012E: return 0x03c7; // Iogonek case 0x012F: return 0x03e7; // iogonek case 0x0130: return 0x02a9; // Iabovedot case 0x0131: return 0x02b9; // idotless case 0x0134: return 0x02ac; // Jcircumflex case 0x0135: return 0x02bc; // jcircumflex case 0x0136: return 0x03d3; // Kcedilla case 0x0137: return 0x03f3; // kcedilla case 0x0138: return 0x03a2; // kra case 0x0139: return 0x01c5; // Lacute case 0x013A: return 0x01e5; // lacute case 0x013B: return 0x03a6; // Lcedilla case 0x013C: return 0x03b6; // lcedilla case 0x013D: return 0x01a5; // Lcaron case 0x013E: return 0x01b5; // lcaron case 0x0141: return 0x01a3; // Lstroke case 0x0142: return 0x01b3; // lstroke case 0x0143: return 0x01d1; // Nacute case 0x0144: return 0x01f1; // nacute case 0x0145: return 0x03d1; // Ncedilla case 0x0146: return 0x03f1; // ncedilla case 0x0147: return 0x01d2; // Ncaron case 0x0148: return 0x01f2; // ncaron case 0x014A: return 0x03bd; // ENG case 0x014B: return 0x03bf; // eng case 0x014C: return 0x03d2; // Omacron case 0x014D: return 0x03f2; // omacron case 0x0150: return 0x01d5; // Odoubleacute case 0x0151: return 0x01f5; // odoubleacute case 0x0152: return 0x13bc; // OE case 0x0153: return 0x13bd; // oe case 0x0154: return 0x01c0; // Racute case 0x0155: return 0x01e0; // racute case 0x0156: return 0x03a3; // Rcedilla case 0x0157: return 0x03b3; // rcedilla case 0x0158: return 0x01d8; // Rcaron case 0x0159: return 0x01f8; // rcaron case 0x015A: return 0x01a6; // Sacute case 0x015B: return 0x01b6; // sacute case 0x015C: return 0x02de; // Scircumflex case 0x015D: return 0x02fe; // scircumflex case 0x015E: return 0x01aa; // Scedilla case 0x015F: return 0x01ba; // scedilla case 0x0160: return 0x01a9; // Scaron case 0x0161: return 0x01b9; // scaron case 0x0162: return 0x01de; // Tcedilla case 0x0163: return 0x01fe; // tcedilla case 0x0164: return 0x01ab; // Tcaron case 0x0165: return 0x01bb; // tcaron case 0x0166: return 0x03ac; // Tslash case 0x0167: return 0x03bc; // tslash case 0x0168: return 0x03dd; // Utilde case 0x0169: return 0x03fd; // utilde case 0x016A: return 0x03de; // Umacron case 0x016B: return 0x03fe; // umacron case 0x016C: return 0x02dd; // Ubreve case 0x016D: return 0x02fd; // ubreve case 0x016E: return 0x01d9; // Uring case 0x016F: return 0x01f9; // uring case 0x0170: return 0x01db; // Udoubleacute case 0x0171: return 0x01fb; // udoubleacute case 0x0172: return 0x03d9; // Uogonek case 0x0173: return 0x03f9; // uogonek case 0x0178: return 0x13be; // Ydiaeresis case 0x0179: return 0x01ac; // Zacute case 0x017A: return 0x01bc; // zacute case 0x017B: return 0x01af; // Zabovedot case 0x017C: return 0x01bf; // zabovedot case 0x017D: return 0x01ae; // Zcaron case 0x017E: return 0x01be; // zcaron case 0x0192: return 0x08f6; // function case 0x02C7: return 0x01b7; // caron case 0x02D8: return 0x01a2; // breve case 0x02D9: return 0x01ff; // abovedot case 0x02DB: return 0x01b2; // ogonek case 0x02DD: return 0x01bd; // doubleacute case 0x0385: return 0x07ae; // Greek_accentdieresis case 0x0386: return 0x07a1; // Greek_ALPHAaccent case 0x0388: return 0x07a2; // Greek_EPSILONaccent case 0x0389: return 0x07a3; // Greek_ETAaccent case 0x038A: return 0x07a4; // Greek_IOTAaccent case 0x038C: return 0x07a7; // Greek_OMICRONaccent case 0x038E: return 0x07a8; // Greek_UPSILONaccent case 0x038F: return 0x07ab; // Greek_OMEGAaccent case 0x0390: return 0x07b6; // Greek_iotaaccentdieresis case 0x0391: return 0x07c1; // Greek_ALPHA case 0x0392: return 0x07c2; // Greek_BETA case 0x0393: return 0x07c3; // Greek_GAMMA case 0x0394: return 0x07c4; // Greek_DELTA case 0x0395: return 0x07c5; // Greek_EPSILON case 0x0396: return 0x07c6; // Greek_ZETA case 0x0397: return 0x07c7; // Greek_ETA case 0x0398: return 0x07c8; // Greek_THETA case 0x0399: return 0x07c9; // Greek_IOTA case 0x039A: return 0x07ca; // Greek_KAPPA case 0x039B: return 0x07cb; // Greek_LAMBDA case 0x039C: return 0x07cc; // Greek_MU case 0x039D: return 0x07cd; // Greek_NU case 0x039E: return 0x07ce; // Greek_XI case 0x039F: return 0x07cf; // Greek_OMICRON case 0x03A0: return 0x07d0; // Greek_PI case 0x03A1: return 0x07d1; // Greek_RHO case 0x03A3: return 0x07d2; // Greek_SIGMA case 0x03A4: return 0x07d4; // Greek_TAU case 0x03A5: return 0x07d5; // Greek_UPSILON case 0x03A6: return 0x07d6; // Greek_PHI case 0x03A7: return 0x07d7; // Greek_CHI case 0x03A8: return 0x07d8; // Greek_PSI case 0x03A9: return 0x07d9; // Greek_OMEGA case 0x03AA: return 0x07a5; // Greek_IOTAdieresis case 0x03AB: return 0x07a9; // Greek_UPSILONdieresis case 0x03AC: return 0x07b1; // Greek_alphaaccent case 0x03AD: return 0x07b2; // Greek_epsilonaccent case 0x03AE: return 0x07b3; // Greek_etaaccent case 0x03AF: return 0x07b4; // Greek_iotaaccent case 0x03B0: return 0x07ba; // Greek_upsilonaccentdieresis case 0x03B1: return 0x07e1; // Greek_alpha case 0x03B2: return 0x07e2; // Greek_beta case 0x03B3: return 0x07e3; // Greek_gamma case 0x03B4: return 0x07e4; // Greek_delta case 0x03B5: return 0x07e5; // Greek_epsilon case 0x03B6: return 0x07e6; // Greek_zeta case 0x03B7: return 0x07e7; // Greek_eta case 0x03B8: return 0x07e8; // Greek_theta case 0x03B9: return 0x07e9; // Greek_iota case 0x03BA: return 0x07ea; // Greek_kappa case 0x03BB: return 0x07eb; // Greek_lambda case 0x03BC: return 0x07ec; // Greek_mu case 0x03BD: return 0x07ed; // Greek_nu case 0x03BE: return 0x07ee; // Greek_xi case 0x03BF: return 0x07ef; // Greek_omicron case 0x03C0: return 0x07f0; // Greek_pi case 0x03C1: return 0x07f1; // Greek_rho case 0x03C2: return 0x07f3; // Greek_finalsmallsigma case 0x03C3: return 0x07f2; // Greek_sigma case 0x03C4: return 0x07f4; // Greek_tau case 0x03C5: return 0x07f5; // Greek_upsilon case 0x03C6: return 0x07f6; // Greek_phi case 0x03C7: return 0x07f7; // Greek_chi case 0x03C8: return 0x07f8; // Greek_psi case 0x03C9: return 0x07f9; // Greek_omega case 0x03CA: return 0x07b5; // Greek_iotadieresis case 0x03CB: return 0x07b9; // Greek_upsilondieresis case 0x03CC: return 0x07b7; // Greek_omicronaccent case 0x03CD: return 0x07b8; // Greek_upsilonaccent case 0x03CE: return 0x07bb; // Greek_omegaaccent case 0x0401: return 0x06b3; // Cyrillic_IO case 0x0402: return 0x06b1; // Serbian_DJE case 0x0403: return 0x06b2; // Macedonia_GJE case 0x0404: return 0x06b4; // Ukrainian_IE case 0x0405: return 0x06b5; // Macedonia_DSE case 0x0406: return 0x06b6; // Ukrainian_I case 0x0407: return 0x06b7; // Ukrainian_YI case 0x0408: return 0x06b8; // Cyrillic_JE case 0x0409: return 0x06b9; // Cyrillic_LJE case 0x040A: return 0x06ba; // Cyrillic_NJE case 0x040B: return 0x06bb; // Serbian_TSHE case 0x040C: return 0x06bc; // Macedonia_KJE case 0x040E: return 0x06be; // Byelorussian_SHORTU case 0x040F: return 0x06bf; // Cyrillic_DZHE case 0x0410: return 0x06e1; // Cyrillic_A case 0x0411: return 0x06e2; // Cyrillic_BE case 0x0412: return 0x06f7; // Cyrillic_VE case 0x0413: return 0x06e7; // Cyrillic_GHE case 0x0414: return 0x06e4; // Cyrillic_DE case 0x0415: return 0x06e5; // Cyrillic_IE case 0x0416: return 0x06f6; // Cyrillic_ZHE case 0x0417: return 0x06fa; // Cyrillic_ZE case 0x0418: return 0x06e9; // Cyrillic_I case 0x0419: return 0x06ea; // Cyrillic_SHORTI case 0x041A: return 0x06eb; // Cyrillic_KA case 0x041B: return 0x06ec; // Cyrillic_EL case 0x041C: return 0x06ed; // Cyrillic_EM case 0x041D: return 0x06ee; // Cyrillic_EN case 0x041E: return 0x06ef; // Cyrillic_O case 0x041F: return 0x06f0; // Cyrillic_PE case 0x0420: return 0x06f2; // Cyrillic_ER case 0x0421: return 0x06f3; // Cyrillic_ES case 0x0422: return 0x06f4; // Cyrillic_TE case 0x0423: return 0x06f5; // Cyrillic_U case 0x0424: return 0x06e6; // Cyrillic_EF case 0x0425: return 0x06e8; // Cyrillic_HA case 0x0426: return 0x06e3; // Cyrillic_TSE case 0x0427: return 0x06fe; // Cyrillic_CHE case 0x0428: return 0x06fb; // Cyrillic_SHA case 0x0429: return 0x06fd; // Cyrillic_SHCHA case 0x042A: return 0x06ff; // Cyrillic_HARDSIGN case 0x042B: return 0x06f9; // Cyrillic_YERU case 0x042C: return 0x06f8; // Cyrillic_SOFTSIGN case 0x042D: return 0x06fc; // Cyrillic_E case 0x042E: return 0x06e0; // Cyrillic_YU case 0x042F: return 0x06f1; // Cyrillic_YA case 0x0430: return 0x06c1; // Cyrillic_a case 0x0431: return 0x06c2; // Cyrillic_be case 0x0432: return 0x06d7; // Cyrillic_ve case 0x0433: return 0x06c7; // Cyrillic_ghe case 0x0434: return 0x06c4; // Cyrillic_de case 0x0435: return 0x06c5; // Cyrillic_ie case 0x0436: return 0x06d6; // Cyrillic_zhe case 0x0437: return 0x06da; // Cyrillic_ze case 0x0438: return 0x06c9; // Cyrillic_i case 0x0439: return 0x06ca; // Cyrillic_shorti case 0x043A: return 0x06cb; // Cyrillic_ka case 0x043B: return 0x06cc; // Cyrillic_el case 0x043C: return 0x06cd; // Cyrillic_em case 0x043D: return 0x06ce; // Cyrillic_en case 0x043E: return 0x06cf; // Cyrillic_o case 0x043F: return 0x06d0; // Cyrillic_pe case 0x0440: return 0x06d2; // Cyrillic_er case 0x0441: return 0x06d3; // Cyrillic_es case 0x0442: return 0x06d4; // Cyrillic_te case 0x0443: return 0x06d5; // Cyrillic_u case 0x0444: return 0x06c6; // Cyrillic_ef case 0x0445: return 0x06c8; // Cyrillic_ha case 0x0446: return 0x06c3; // Cyrillic_tse case 0x0447: return 0x06de; // Cyrillic_che case 0x0448: return 0x06db; // Cyrillic_sha case 0x0449: return 0x06dd; // Cyrillic_shcha case 0x044A: return 0x06df; // Cyrillic_hardsign case 0x044B: return 0x06d9; // Cyrillic_yeru case 0x044C: return 0x06d8; // Cyrillic_softsign case 0x044D: return 0x06dc; // Cyrillic_e case 0x044E: return 0x06c0; // Cyrillic_yu case 0x044F: return 0x06d1; // Cyrillic_ya case 0x0451: return 0x06a3; // Cyrillic_io case 0x0452: return 0x06a1; // Serbian_dje case 0x0453: return 0x06a2; // Macedonia_gje case 0x0454: return 0x06a4; // Ukrainian_ie case 0x0455: return 0x06a5; // Macedonia_dse case 0x0456: return 0x06a6; // Ukrainian_i case 0x0457: return 0x06a7; // Ukrainian_yi case 0x0458: return 0x06a8; // Cyrillic_je case 0x0459: return 0x06a9; // Cyrillic_lje case 0x045A: return 0x06aa; // Cyrillic_nje case 0x045B: return 0x06ab; // Serbian_tshe case 0x045C: return 0x06ac; // Macedonia_kje case 0x045E: return 0x06ae; // Byelorussian_shortu case 0x045F: return 0x06af; // Cyrillic_dzhe case 0x0490: return 0x06bd; // Ukrainian_GHE_WITH_UPTURN case 0x0491: return 0x06ad; // Ukrainian_ghe_with_upturn case 0x05D0: return 0x0ce0; // hebrew_aleph case 0x05D1: return 0x0ce1; // hebrew_bet case 0x05D2: return 0x0ce2; // hebrew_gimel case 0x05D3: return 0x0ce3; // hebrew_dalet case 0x05D4: return 0x0ce4; // hebrew_he case 0x05D5: return 0x0ce5; // hebrew_waw case 0x05D6: return 0x0ce6; // hebrew_zain case 0x05D7: return 0x0ce7; // hebrew_chet case 0x05D8: return 0x0ce8; // hebrew_tet case 0x05D9: return 0x0ce9; // hebrew_yod case 0x05DA: return 0x0cea; // hebrew_finalkaph case 0x05DB: return 0x0ceb; // hebrew_kaph case 0x05DC: return 0x0cec; // hebrew_lamed case 0x05DD: return 0x0ced; // hebrew_finalmem case 0x05DE: return 0x0cee; // hebrew_mem case 0x05DF: return 0x0cef; // hebrew_finalnun case 0x05E0: return 0x0cf0; // hebrew_nun case 0x05E1: return 0x0cf1; // hebrew_samech case 0x05E2: return 0x0cf2; // hebrew_ayin case 0x05E3: return 0x0cf3; // hebrew_finalpe case 0x05E4: return 0x0cf4; // hebrew_pe case 0x05E5: return 0x0cf5; // hebrew_finalzade case 0x05E6: return 0x0cf6; // hebrew_zade case 0x05E7: return 0x0cf7; // hebrew_qoph case 0x05E8: return 0x0cf8; // hebrew_resh case 0x05E9: return 0x0cf9; // hebrew_shin case 0x05EA: return 0x0cfa; // hebrew_taw case 0x060C: return 0x05ac; // Arabic_comma case 0x061B: return 0x05bb; // Arabic_semicolon case 0x061F: return 0x05bf; // Arabic_question_mark case 0x0621: return 0x05c1; // Arabic_hamza case 0x0622: return 0x05c2; // Arabic_maddaonalef case 0x0623: return 0x05c3; // Arabic_hamzaonalef case 0x0624: return 0x05c4; // Arabic_hamzaonwaw case 0x0625: return 0x05c5; // Arabic_hamzaunderalef case 0x0626: return 0x05c6; // Arabic_hamzaonyeh case 0x0627: return 0x05c7; // Arabic_alef case 0x0628: return 0x05c8; // Arabic_beh case 0x0629: return 0x05c9; // Arabic_tehmarbuta case 0x062A: return 0x05ca; // Arabic_teh case 0x062B: return 0x05cb; // Arabic_theh case 0x062C: return 0x05cc; // Arabic_jeem case 0x062D: return 0x05cd; // Arabic_hah case 0x062E: return 0x05ce; // Arabic_khah case 0x062F: return 0x05cf; // Arabic_dal case 0x0630: return 0x05d0; // Arabic_thal case 0x0631: return 0x05d1; // Arabic_ra case 0x0632: return 0x05d2; // Arabic_zain case 0x0633: return 0x05d3; // Arabic_seen case 0x0634: return 0x05d4; // Arabic_sheen case 0x0635: return 0x05d5; // Arabic_sad case 0x0636: return 0x05d6; // Arabic_dad case 0x0637: return 0x05d7; // Arabic_tah case 0x0638: return 0x05d8; // Arabic_zah case 0x0639: return 0x05d9; // Arabic_ain case 0x063A: return 0x05da; // Arabic_ghain case 0x0640: return 0x05e0; // Arabic_tatweel case 0x0641: return 0x05e1; // Arabic_feh case 0x0642: return 0x05e2; // Arabic_qaf case 0x0643: return 0x05e3; // Arabic_kaf case 0x0644: return 0x05e4; // Arabic_lam case 0x0645: return 0x05e5; // Arabic_meem case 0x0646: return 0x05e6; // Arabic_noon case 0x0647: return 0x05e7; // Arabic_ha case 0x0648: return 0x05e8; // Arabic_waw case 0x0649: return 0x05e9; // Arabic_alefmaksura case 0x064A: return 0x05ea; // Arabic_yeh case 0x064B: return 0x05eb; // Arabic_fathatan case 0x064C: return 0x05ec; // Arabic_dammatan case 0x064D: return 0x05ed; // Arabic_kasratan case 0x064E: return 0x05ee; // Arabic_fatha case 0x064F: return 0x05ef; // Arabic_damma case 0x0650: return 0x05f0; // Arabic_kasra case 0x0651: return 0x05f1; // Arabic_shadda case 0x0652: return 0x05f2; // Arabic_sukun case 0x0E01: return 0x0da1; // Thai_kokai case 0x0E02: return 0x0da2; // Thai_khokhai case 0x0E03: return 0x0da3; // Thai_khokhuat case 0x0E04: return 0x0da4; // Thai_khokhwai case 0x0E05: return 0x0da5; // Thai_khokhon case 0x0E06: return 0x0da6; // Thai_khorakhang case 0x0E07: return 0x0da7; // Thai_ngongu case 0x0E08: return 0x0da8; // Thai_chochan case 0x0E09: return 0x0da9; // Thai_choching case 0x0E0A: return 0x0daa; // Thai_chochang case 0x0E0B: return 0x0dab; // Thai_soso case 0x0E0C: return 0x0dac; // Thai_chochoe case 0x0E0D: return 0x0dad; // Thai_yoying case 0x0E0E: return 0x0dae; // Thai_dochada case 0x0E0F: return 0x0daf; // Thai_topatak case 0x0E10: return 0x0db0; // Thai_thothan case 0x0E11: return 0x0db1; // Thai_thonangmontho case 0x0E12: return 0x0db2; // Thai_thophuthao case 0x0E13: return 0x0db3; // Thai_nonen case 0x0E14: return 0x0db4; // Thai_dodek case 0x0E15: return 0x0db5; // Thai_totao case 0x0E16: return 0x0db6; // Thai_thothung case 0x0E17: return 0x0db7; // Thai_thothahan case 0x0E18: return 0x0db8; // Thai_thothong case 0x0E19: return 0x0db9; // Thai_nonu case 0x0E1A: return 0x0dba; // Thai_bobaimai case 0x0E1B: return 0x0dbb; // Thai_popla case 0x0E1C: return 0x0dbc; // Thai_phophung case 0x0E1D: return 0x0dbd; // Thai_fofa case 0x0E1E: return 0x0dbe; // Thai_phophan case 0x0E1F: return 0x0dbf; // Thai_fofan case 0x0E20: return 0x0dc0; // Thai_phosamphao case 0x0E21: return 0x0dc1; // Thai_moma case 0x0E22: return 0x0dc2; // Thai_yoyak case 0x0E23: return 0x0dc3; // Thai_rorua case 0x0E24: return 0x0dc4; // Thai_ru case 0x0E25: return 0x0dc5; // Thai_loling case 0x0E26: return 0x0dc6; // Thai_lu case 0x0E27: return 0x0dc7; // Thai_wowaen case 0x0E28: return 0x0dc8; // Thai_sosala case 0x0E29: return 0x0dc9; // Thai_sorusi case 0x0E2A: return 0x0dca; // Thai_sosua case 0x0E2B: return 0x0dcb; // Thai_hohip case 0x0E2C: return 0x0dcc; // Thai_lochula case 0x0E2D: return 0x0dcd; // Thai_oang case 0x0E2E: return 0x0dce; // Thai_honokhuk case 0x0E2F: return 0x0dcf; // Thai_paiyannoi case 0x0E30: return 0x0dd0; // Thai_saraa case 0x0E31: return 0x0dd1; // Thai_maihanakat case 0x0E32: return 0x0dd2; // Thai_saraaa case 0x0E33: return 0x0dd3; // Thai_saraam case 0x0E34: return 0x0dd4; // Thai_sarai case 0x0E35: return 0x0dd5; // Thai_saraii case 0x0E36: return 0x0dd6; // Thai_saraue case 0x0E37: return 0x0dd7; // Thai_sarauee case 0x0E38: return 0x0dd8; // Thai_sarau case 0x0E39: return 0x0dd9; // Thai_sarauu case 0x0E3A: return 0x0dda; // Thai_phinthu case 0x0E3F: return 0x0ddf; // Thai_baht case 0x0E40: return 0x0de0; // Thai_sarae case 0x0E41: return 0x0de1; // Thai_saraae case 0x0E42: return 0x0de2; // Thai_sarao case 0x0E43: return 0x0de3; // Thai_saraaimaimuan case 0x0E44: return 0x0de4; // Thai_saraaimaimalai case 0x0E45: return 0x0de5; // Thai_lakkhangyao case 0x0E46: return 0x0de6; // Thai_maiyamok case 0x0E47: return 0x0de7; // Thai_maitaikhu case 0x0E48: return 0x0de8; // Thai_maiek case 0x0E49: return 0x0de9; // Thai_maitho case 0x0E4A: return 0x0dea; // Thai_maitri case 0x0E4B: return 0x0deb; // Thai_maichattawa case 0x0E4C: return 0x0dec; // Thai_thanthakhat case 0x0E4D: return 0x0ded; // Thai_nikhahit case 0x0E50: return 0x0df0; // Thai_leksun case 0x0E51: return 0x0df1; // Thai_leknung case 0x0E52: return 0x0df2; // Thai_leksong case 0x0E53: return 0x0df3; // Thai_leksam case 0x0E54: return 0x0df4; // Thai_leksi case 0x0E55: return 0x0df5; // Thai_lekha case 0x0E56: return 0x0df6; // Thai_lekhok case 0x0E57: return 0x0df7; // Thai_lekchet case 0x0E58: return 0x0df8; // Thai_lekpaet case 0x0E59: return 0x0df9; // Thai_lekkao case 0x2002: return 0x0aa2; // enspace case 0x2003: return 0x0aa1; // emspace case 0x2004: return 0x0aa3; // em3space case 0x2005: return 0x0aa4; // em4space case 0x2007: return 0x0aa5; // digitspace case 0x2008: return 0x0aa6; // punctspace case 0x2009: return 0x0aa7; // thinspace case 0x200A: return 0x0aa8; // hairspace case 0x2012: return 0x0abb; // figdash case 0x2013: return 0x0aaa; // endash case 0x2014: return 0x0aa9; // emdash case 0x2015: return 0x07af; // Greek_horizbar case 0x2017: return 0x0cdf; // hebrew_doublelowline case 0x2018: return 0x0ad0; // leftsinglequotemark case 0x2019: return 0x0ad1; // rightsinglequotemark case 0x201A: return 0x0afd; // singlelowquotemark case 0x201C: return 0x0ad2; // leftdoublequotemark case 0x201D: return 0x0ad3; // rightdoublequotemark case 0x201E: return 0x0afe; // doublelowquotemark case 0x2020: return 0x0af1; // dagger case 0x2021: return 0x0af2; // doubledagger case 0x2022: return 0x0ae6; // enfilledcircbullet case 0x2025: return 0x0aaf; // doubbaselinedot case 0x2026: return 0x0aae; // ellipsis case 0x2030: return 0x0ad5; // permille case 0x2032: return 0x0ad6; // minutes case 0x2033: return 0x0ad7; // seconds case 0x2038: return 0x0afc; // caret case 0x203E: return 0x047e; // overline case 0x20A9: return 0x0eff; // Korean_Won case 0x20AC: return 0x20ac; // EuroSign case 0x2105: return 0x0ab8; // careof case 0x2116: return 0x06b0; // numerosign case 0x2117: return 0x0afb; // phonographcopyright case 0x211E: return 0x0ad4; // prescription case 0x2122: return 0x0ac9; // trademark case 0x2153: return 0x0ab0; // onethird case 0x2154: return 0x0ab1; // twothirds case 0x2155: return 0x0ab2; // onefifth case 0x2156: return 0x0ab3; // twofifths case 0x2157: return 0x0ab4; // threefifths case 0x2158: return 0x0ab5; // fourfifths case 0x2159: return 0x0ab6; // onesixth case 0x215A: return 0x0ab7; // fivesixths case 0x215B: return 0x0ac3; // oneeighth case 0x215C: return 0x0ac4; // threeeighths case 0x215D: return 0x0ac5; // fiveeighths case 0x215E: return 0x0ac6; // seveneighths case 0x2190: return 0x08fb; // leftarrow case 0x2191: return 0x08fc; // uparrow case 0x2192: return 0x08fd; // rightarrow case 0x2193: return 0x08fe; // downarrow case 0x21D2: return 0x08ce; // implies case 0x21D4: return 0x08cd; // ifonlyif case 0x2202: return 0x08ef; // partialderivative case 0x2207: return 0x08c5; // nabla case 0x2218: return 0x0bca; // jot case 0x221A: return 0x08d6; // radical case 0x221D: return 0x08c1; // variation case 0x221E: return 0x08c2; // infinity case 0x2227: return 0x08de; // logicaland case 0x2228: return 0x08df; // logicalor case 0x2229: return 0x08dc; // intersection case 0x222A: return 0x08dd; // union case 0x222B: return 0x08bf; // integral case 0x2234: return 0x08c0; // therefore case 0x223C: return 0x08c8; // approximate case 0x2243: return 0x08c9; // similarequal case 0x2260: return 0x08bd; // notequal case 0x2261: return 0x08cf; // identical case 0x2264: return 0x08bc; // lessthanequal case 0x2265: return 0x08be; // greaterthanequal case 0x2282: return 0x08da; // includedin case 0x2283: return 0x08db; // includes case 0x22A2: return 0x0bfc; // righttack case 0x22A3: return 0x0bdc; // lefttack case 0x22A4: return 0x0bc2; // downtack case 0x22A5: return 0x0bce; // uptack case 0x2308: return 0x0bd3; // upstile case 0x230A: return 0x0bc4; // downstile case 0x2315: return 0x0afa; // telephonerecorder case 0x2320: return 0x08a4; // topintegral case 0x2321: return 0x08a5; // botintegral case 0x2395: return 0x0bcc; // quad case 0x239B: return 0x08ab; // topleftparens case 0x239D: return 0x08ac; // botleftparens case 0x239E: return 0x08ad; // toprightparens case 0x23A0: return 0x08ae; // botrightparens case 0x23A1: return 0x08a7; // topleftsqbracket case 0x23A3: return 0x08a8; // botleftsqbracket case 0x23A4: return 0x08a9; // toprightsqbracket case 0x23A6: return 0x08aa; // botrightsqbracket case 0x23A8: return 0x08af; // leftmiddlecurlybrace case 0x23AC: return 0x08b0; // rightmiddlecurlybrace case 0x23B7: return 0x08a1; // leftradical case 0x23BA: return 0x09ef; // horizlinescan1 case 0x23BB: return 0x09f0; // horizlinescan3 case 0x23BC: return 0x09f2; // horizlinescan7 case 0x23BD: return 0x09f3; // horizlinescan9 case 0x2409: return 0x09e2; // ht case 0x240A: return 0x09e5; // lf case 0x240B: return 0x09e9; // vt case 0x240C: return 0x09e3; // ff case 0x240D: return 0x09e4; // cr case 0x2423: return 0x0aac; // signifblank case 0x2424: return 0x09e8; // nl case 0x2500: return 0x09f1; // horizlinescan5 case 0x2502: return 0x09f8; // vertbar case 0x250C: return 0x09ec; // upleftcorner case 0x2510: return 0x09eb; // uprightcorner case 0x2514: return 0x09ed; // lowleftcorner case 0x2518: return 0x09ea; // lowrightcorner case 0x251C: return 0x09f4; // leftt case 0x2524: return 0x09f5; // rightt case 0x252C: return 0x09f7; // topt case 0x2534: return 0x09f6; // bott case 0x253C: return 0x09ee; // crossinglines case 0x2592: return 0x09e1; // checkerboard case 0x25AA: return 0x0ae7; // enfilledsqbullet case 0x25AB: return 0x0ae1; // enopensquarebullet case 0x25AC: return 0x0adb; // filledrectbullet case 0x25AD: return 0x0ae2; // openrectbullet case 0x25AE: return 0x0adf; // emfilledrect case 0x25AF: return 0x0acf; // emopenrectangle case 0x25B2: return 0x0ae8; // filledtribulletup case 0x25B3: return 0x0ae3; // opentribulletup case 0x25B6: return 0x0add; // filledrighttribullet case 0x25B7: return 0x0acd; // rightopentriangle case 0x25BC: return 0x0ae9; // filledtribulletdown case 0x25BD: return 0x0ae4; // opentribulletdown case 0x25C0: return 0x0adc; // filledlefttribullet case 0x25C1: return 0x0acc; // leftopentriangle case 0x25C6: return 0x09e0; // soliddiamond case 0x25CB: return 0x0bcf; // circle case 0x25CF: return 0x0ade; // emfilledcircle case 0x25E6: return 0x0ae0; // enopencircbullet case 0x2606: return 0x0ae5; // openstar case 0x260E: return 0x0af9; // telephone case 0x2613: return 0x0aca; // signaturemark case 0x261C: return 0x0aea; // leftpointer case 0x261E: return 0x0aeb; // rightpointer case 0x2640: return 0x0af8; // femalesymbol case 0x2642: return 0x0af7; // malesymbol case 0x2663: return 0x0aec; // club case 0x2665: return 0x0aee; // heart case 0x2666: return 0x0aed; // diamond case 0x266D: return 0x0af6; // musicalflat case 0x266F: return 0x0af5; // musicalsharp case 0x2713: return 0x0af3; // checkmark case 0x2717: return 0x0af4; // ballotcross case 0x271D: return 0x0ad9; // latincross case 0x2720: return 0x0af0; // maltesecross case 0x27E8: return 0x0abc; // leftanglebracket case 0x27E9: return 0x0abe; // rightanglebracket case 0x3001: return 0x04a4; // kana_comma case 0x3002: return 0x04a1; // kana_fullstop case 0x300C: return 0x04a2; // kana_openingbracket case 0x300D: return 0x04a3; // kana_closingbracket case 0x309B: return 0x04de; // voicedsound case 0x309C: return 0x04df; // semivoicedsound case 0x30A1: return 0x04a7; // kana_a case 0x30A2: return 0x04b1; // kana_A case 0x30A3: return 0x04a8; // kana_i case 0x30A4: return 0x04b2; // kana_I case 0x30A5: return 0x04a9; // kana_u case 0x30A6: return 0x04b3; // kana_U case 0x30A7: return 0x04aa; // kana_e case 0x30A8: return 0x04b4; // kana_E case 0x30A9: return 0x04ab; // kana_o case 0x30AA: return 0x04b5; // kana_O case 0x30AB: return 0x04b6; // kana_KA case 0x30AD: return 0x04b7; // kana_KI case 0x30AF: return 0x04b8; // kana_KU case 0x30B1: return 0x04b9; // kana_KE case 0x30B3: return 0x04ba; // kana_KO case 0x30B5: return 0x04bb; // kana_SA case 0x30B7: return 0x04bc; // kana_SHI case 0x30B9: return 0x04bd; // kana_SU case 0x30BB: return 0x04be; // kana_SE case 0x30BD: return 0x04bf; // kana_SO case 0x30BF: return 0x04c0; // kana_TA case 0x30C1: return 0x04c1; // kana_CHI case 0x30C3: return 0x04af; // kana_tsu case 0x30C4: return 0x04c2; // kana_TSU case 0x30C6: return 0x04c3; // kana_TE case 0x30C8: return 0x04c4; // kana_TO case 0x30CA: return 0x04c5; // kana_NA case 0x30CB: return 0x04c6; // kana_NI case 0x30CC: return 0x04c7; // kana_NU case 0x30CD: return 0x04c8; // kana_NE case 0x30CE: return 0x04c9; // kana_NO case 0x30CF: return 0x04ca; // kana_HA case 0x30D2: return 0x04cb; // kana_HI case 0x30D5: return 0x04cc; // kana_FU case 0x30D8: return 0x04cd; // kana_HE case 0x30DB: return 0x04ce; // kana_HO case 0x30DE: return 0x04cf; // kana_MA case 0x30DF: return 0x04d0; // kana_MI case 0x30E0: return 0x04d1; // kana_MU case 0x30E1: return 0x04d2; // kana_ME case 0x30E2: return 0x04d3; // kana_MO case 0x30E3: return 0x04ac; // kana_ya case 0x30E4: return 0x04d4; // kana_YA case 0x30E5: return 0x04ad; // kana_yu case 0x30E6: return 0x04d5; // kana_YU case 0x30E7: return 0x04ae; // kana_yo case 0x30E8: return 0x04d6; // kana_YO case 0x30E9: return 0x04d7; // kana_RA case 0x30EA: return 0x04d8; // kana_RI case 0x30EB: return 0x04d9; // kana_RU case 0x30EC: return 0x04da; // kana_RE case 0x30ED: return 0x04db; // kana_RO case 0x30EF: return 0x04dc; // kana_WA case 0x30F2: return 0x04a6; // kana_WO case 0x30F3: return 0x04dd; // kana_N case 0x30FB: return 0x04a5; // kana_conjunctive case 0x30FC: return 0x04b0; // prolongedsound default: return NoSymbol; }; } ",16348,True,4461.977704707686,median "/******************************************************************************* * Copyright 2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include ""c_types_map.hpp"" #include ""mkldnn_thread.hpp"" #include ""nstl.hpp"" #include ""type_helpers.hpp"" #include ""utils.hpp"" #include #include ""jit_avx512_common_conv_winograd_kernel_f32.hpp"" #ifndef KERNEL_SIZE_THRESHOLD #define KERNEL_SIZE_THRESHOLD 16 #endif #define MIN_REQUIRED_DIMN_REG_BLOCK 14 namespace mkldnn { namespace impl { namespace cpu { namespace { using namespace mkldnn::impl::utils; unsigned int L1_cache_size = get_cache_size(1, true); unsigned int L2_cache_size = get_cache_size(2, true); unsigned int LLC_data_size = get_cache_size(3, false); // the test funtion takes jcp, the candidate and the current best. // it returns true if the new candidate is better int get_divisor_satisfying_cond(jit_conv_winograd_conf_t &jcp, int number, int default_best, bool (*test)(jit_conv_winograd_conf_t &, int, int)) { int best_divisor = default_best; auto test_num = [&best_divisor, test](jit_conv_winograd_conf_t &jcp, int num) { if (test(jcp, num, best_divisor)) { best_divisor = num; } }; for (int divisor = 1; divisor <= ::sqrt(number); divisor++) { if (number % divisor == 0) { test_num(jcp, divisor); test_num(jcp, number / divisor); } } return best_divisor; } /* assumes 512 bits registers */ /* TODO: add support for strides */ /* TODO: handle the prefetch distance automatically */ typedef enum cache_t_ { L1, L2, L3 } cache_t; template struct prefetcher_t { prefetcher_t(jit_generator *generator, Xbyak::Reg64 reg_base_addr, cache_t cache_type, size_t block_size, /* in number of elements*/ int nb_instructions_in_block, int fma_ipc) : cg_(generator) , reg_base_addr_(reg_base_addr) , cache_type_(cache_type) , cache_block_size_(block_size) { nb_cache_lines_to_prefetch_ = cache_block_size_ / (64 / sizeof(data_t)); prefetch_spread_ = div_up(nb_instructions_in_block, nb_cache_lines_to_prefetch_); prefetch_blk_ = div_up(nb_cache_lines_to_prefetch_, nb_instructions_in_block); /* assumption: when fetch in Li, data is already in L(i+1) */ int cache_latency; switch (cache_type_) { case L1: cache_latency = 14; break; case L2: cache_latency = 250; break; case L3: cache_latency = 250; break; } prefetch_distance_ = div_up(cache_latency, nb_cache_lines_to_prefetch_); } void prefetch(int instruction_number) { if (instruction_number % prefetch_spread_ == 0) { for (int i = 0; (i < prefetch_blk_) && (prefetches_issued_ < nb_cache_lines_to_prefetch_); i++, prefetches_issued_++) { prefetch_inst_(cg_->EVEX_compress_addr( reg_base_addr_, (cache_block_size_ * prefetch_distance_) * sizeof(data_t) + (prefetches_issued_ * 64))); } } } private: void prefetch_inst_(const Xbyak::Address &addr) { switch (cache_type_) { case L1: cg_->prefetcht0(addr); break; case L2: cg_->prefetcht1(addr); break; case L3: cg_->prefetcht2(addr); break; default: break; // TODO: raise an exception or put an assert } } jit_generator *cg_; Xbyak::Reg64 reg_base_addr_; cache_t cache_type_; int cache_block_size_ = 0; int nb_cache_lines_to_prefetch_ = 0; int prefetches_issued_ = 0; int prefetch_spread_ = 0; int prefetch_blk_ = 0; int prefetch_distance_ = 0; }; // utilities to support kernel parameter selection bool check_L2_block_per_thread(jit_conv_winograd_conf_t &jcp, int dimN_block, float C2_min, float C2_max) { /* V_L2_block + M_L2_block + W */ float block_size = (jcp.alpha * jcp.alpha * (jcp.oc + jcp.ic) * dimN_block * jcp.dimN_reg_block + jcp.ic * jcp.oc) * (float)sizeof(float); float L2_lb = C2_min * L2_cache_size; float L2_ub = C2_max * L2_cache_size; return (block_size > L2_lb && block_size < L2_ub); } bool check_L1_block_gemm(jit_conv_winograd_conf_t &jcp, int dimK_block, int dimM_block, float C1_min, float C1_max) { float gemm_block_size = (dimM_block * jcp.dimM_simd_block * dimK_block * jcp.dimK_reg_block + dimK_block * jcp.dimK_reg_block * jcp.dimN_reg_block + dimM_block * jcp.dimM_simd_block * jcp.dimN_reg_block) * (float)sizeof(float); float L1_lb = C1_min * L1_cache_size; float L1_ub = C1_max * L1_cache_size; return (gemm_block_size > L1_lb && gemm_block_size < L1_ub); } bool check_cond1(int dimN_reg_block, int dimK_block, int dimK_reg_block, int dimM_block, int dimM_simd_block, float C) { float lhs = (dimM_block * dimN_reg_block * dimM_simd_block + dimM_block * dimK_block * dimK_reg_block * dimM_simd_block + dimK_block * dimN_reg_block * dimK_reg_block) * (float)sizeof(float); float rhs = C * L1_cache_size; return (lhs < rhs); } bool check_cond1_bis(int dimN_reg_block, int dimK_block, int dimK_reg_block, int dimM_block, int dimM_simd_block, float C) { float lhs = (dimM_block * dimK_block * dimK_reg_block * dimM_simd_block + dimK_block * dimN_reg_block * dimK_reg_block) * (float)sizeof(float); float rhs = C * L1_cache_size; return (lhs < rhs); } bool check_cond2(int nb_dimN_reg_block, int dimN_reg_block, int dimK_nb_block, int dimK_block, int dimK_reg_block, int dimM_block, int dimM_simd_block, float C) { float lhs = (nb_dimN_reg_block * dimM_block * dimN_reg_block * dimM_simd_block + dimK_nb_block * dimM_block * dimK_block * dimK_reg_block * dimM_simd_block + nb_dimN_reg_block * dimK_nb_block * dimK_block * dimN_reg_block * dimK_reg_block) * (float)sizeof(float); float rhs = C * L2_cache_size; return (lhs < rhs); } } using namespace mkldnn::impl::memory_format; using namespace mkldnn::impl::utils; using namespace Xbyak; void _jit_avx512_common_conv_winograd_data_kernel_f32::gemm_loop_generate( bool is_beta_zero) { // const int dimK_simd_block = jcp.dimK_reg_block; // for (int dimM_block =0; dimM_block < jcp.dimM_block; dimM_block++) // for (int dimK_block = 0; dimK_block < jcp.dimK_block; dimK_block++) // for (int dimK_reg_block= 0; dimK_reg_block < jcp.dimK_reg_block; // dimK_reg_block++) // for (int tile =0; tile < jcp.dimN_reg_block; tile++) // C[dimM_block][tile] += // A[dimM_block][dimK_block][dimK_reg_block] * // broadcast(B[dimK_block][tile][dimK_reg_block]); // 1) We do register blocking on A[dimM_block][dimK_block][dimK_reg_block], // so we load it before the loop on tile // 2) the loop on tile must be fully unrolled. Don't know about the one on // dimK_reg_block. I think it should be auto inner_loops = [=]() { Label dimM_block_loop, dimK_block_loop; const int inc_dimK_reg_block = jcp.ver == ver_4fma ? 4 : 1; const int fma_ipc = jcp.ver == ver_4fma ? 1 : 2; prefetcher_t L1_pf(this, reg_srcB, L1, jcp.dimN_reg_block * jcp.dimK_reg_block, jcp.dimK_reg_block * jcp.dimN_reg_block / inc_dimK_reg_block, fma_ipc); prefetcher_t L2_pf(this, reg_srcB, L2, jcp.dimN_reg_block * jcp.dimK_reg_block, jcp.dimK_reg_block * jcp.dimN_reg_block / inc_dimK_reg_block, fma_ipc); if (jcp.dimM_block > 1) { mov(reg_dimM_block_loop_cnt, jcp.dimM_block); L(dimM_block_loop); } { // First, we zero the accumulators if first nb_ic iteration, // otherwise we load them for (int tile = 0; tile < jcp.dimN_reg_block; tile++) { Zmm zmm(jcp.zmm_start + tile); if (is_beta_zero) vpxord(zmm, zmm, zmm); else vmovups(zmm, zword[reg_dstC + 64 * tile]); } if (jcp.dimK_block > 1) { mov(reg_dimK_block_loop_cnt, jcp.dimK_block); L(dimK_block_loop); } { auto load_A = [=](int reg_idx, int offset) { for (int i = 0; i < inc_dimK_reg_block; i++) vmovups(Zmm(reg_idx + i), zword[reg_srcA + 64 * (offset + i)]); }; // Used when doing double buffering int next = 0; if (jcp.double_buffering) { load_A(next, 0); } for (int dimK_reg_block = 0; dimK_reg_block < jcp.dimK_reg_block; dimK_reg_block += inc_dimK_reg_block) { int current; /* Loading the next vector from A */ current = next; if (jcp.double_buffering) { next = (dimK_reg_block + inc_dimK_reg_block) % (2 * inc_dimK_reg_block); load_A(next, dimK_reg_block + inc_dimK_reg_block); } else { next = 0; load_A(next, dimK_reg_block); } /* Performing the fmas */ for (int tile = 0; tile < jcp.dimN_reg_block; tile++) { Zmm zmm(jcp.zmm_start + tile); if (jcp.ver != ver_avx512_core) L1_pf.prefetch( dimK_reg_block * jcp.dimN_reg_block + tile); if (jcp.ver == ver_4fma) v4fmaddps(zmm, Zmm(current), EVEX_compress_addr(reg_srcB, 64 * tile + dimK_reg_block * 4)); else vfmadd231ps(zmm, Zmm(current), EVEX_compress_addr(reg_srcB, 64 * tile + dimK_reg_block * 4, true)); if (jcp.ver != ver_avx512_core) L2_pf.prefetch( dimK_reg_block * jcp.dimN_reg_block + tile); } } add(reg_srcA, jcp.dimK_reg_block * 64); add(reg_srcB, jcp.dimN_reg_block * 64); if (jcp.dimK_block > 1) { sub(reg_dimK_block_loop_cnt, 1); jnz(dimK_block_loop); } } for (int tile = 0; tile < jcp.dimN_reg_block; tile++) { Zmm zmm(jcp.zmm_start + tile); // In W_SGD, output will be reused. if (jcp.dimK_nb_block == 1 && jcp.sched_policy == WSCHED_DATA_W_S_G_D && (jcp.dimN * jcp.dimM * jcp.alpha * jcp.alpha * sizeof(float) > 2 * LLC_data_size)) vmovntps(zword[reg_dstC + 64 * tile], zmm); else vmovups(zword[reg_dstC + 64 * tile], zmm); } if (jcp.dimM_block > 1) { sub(reg_srcB, jcp.dimK_block * jcp.dimN_reg_block * 64); add(reg_dstC, jcp.dimN_reg_block * 64); sub(reg_dimM_block_loop_cnt, 1); jnz(dimM_block_loop); } } }; /* Preamble */ // register used to handle long fma encoding push(reg_EVEX_max_8b_offt); mov(reg_EVEX_max_8b_offt, 2 * EVEX_max_8b_offt); /* kernel */ inner_loops(); /* Postamble */ pop(reg_EVEX_max_8b_offt); ret(); } status_t _jit_avx512_common_conv_winograd_data_kernel_f32::init_conf_common( jit_conv_winograd_conf_t &jcp, const convolution_desc_t &cd, const memory_desc_wrapper &src_d, const memory_desc_wrapper &weights_d, const memory_desc_wrapper &dst_d) { if (!mayiuse(avx512_common)) return status::unimplemented; else if (mayiuse(avx512_core)) jcp.ver = ver_avx512_core; else if (mayiuse(avx512_mic_4ops)) jcp.ver = ver_4fma; else jcp.ver = ver_fma; const bool with_groups = weights_d.ndims() == src_d.ndims() + 1; const int simd_w = 16; jcp.ngroups = with_groups ? weights_d.dims()[0] : 1; jcp.mb = src_d.dims()[0]; jcp.oc = dst_d.dims()[1] / jcp.ngroups; jcp.ic = src_d.dims()[1] / jcp.ngroups; jcp.ih = src_d.dims()[2]; jcp.iw = src_d.dims()[3]; jcp.oh = dst_d.dims()[2]; jcp.ow = dst_d.dims()[3]; jcp.kh = weights_d.dims()[with_groups + 2]; jcp.kw = weights_d.dims()[with_groups + 3]; jcp.t_pad = cd.padding[0][0]; jcp.l_pad = cd.padding[0][1]; jcp.stride_h = cd.strides[0]; jcp.stride_w = cd.strides[1]; jcp.dilate_h = cd.dilates[0]; jcp.dilate_w = cd.dilates[1]; jcp.r_pad = nstl::max( 0, (jcp.ow - 1) * jcp.stride_w + jcp.kw - jcp.iw - jcp.l_pad); jcp.b_pad = nstl::max( 0, (jcp.oh - 1) * jcp.stride_h + jcp.kh - jcp.ih - jcp.t_pad); jcp.ihp = jcp.ih + jcp.t_pad + jcp.b_pad; jcp.iwp = jcp.iw + jcp.l_pad + jcp.r_pad; jcp.ohp = jcp.oh; jcp.owp = jcp.ow; // Checking conditions not supported by these kernels if (jcp.ngroups != 1) return status::unimplemented; if ((jcp.kh != 3) || (jcp.kw != 3)) return status::unimplemented; if ((jcp.dilate_h != 0) || (jcp.dilate_w != 0)) return status::unimplemented; if ((jcp.stride_h != 1) || (jcp.stride_w != 1)) return status::unimplemented; if ((jcp.ic % simd_w) != 0 || (jcp.oc % simd_w) != 0) return status::unimplemented; if (src_d.format() != nChw16c) return status::unimplemented; if (weights_d.format() != (with_groups ? gOIhw16i16o : OIhw16i16o)) return status::unimplemented; if (dst_d.format() != nChw16c) return status::unimplemented; return status::success; } status_t set_wsched_DATA_W_SGD(jit_conv_winograd_conf_t &jcp) { if (jcp.ver != ver_avx512_core) return status::unimplemented; /* ----------- dimN reg block ---------------------*/ auto test_cond_dimN_reg_block = [](jit_conv_winograd_conf_t &jcp, int dimN_reg_block, int current_best) { return (dimN_reg_block >= MIN_REQUIRED_DIMN_REG_BLOCK) && (dimN_reg_block <= jcp.nb_reg) && (dimN_reg_block < current_best); }; jcp.dimN_reg_block = get_divisor_satisfying_cond( jcp, jcp.dimN, jcp.dimN, test_cond_dimN_reg_block); if (jcp.dimN_reg_block >= jcp.nb_reg) { auto test_cond_dimN_reg_block = [](jit_conv_winograd_conf_t &jcp, int dimN_reg_block, int current_best) { return (dimN_reg_block < jcp.nb_reg) && (dimN_reg_block > current_best); }; jcp.dimN_reg_block = get_divisor_satisfying_cond( jcp, jcp.dimN, 1, test_cond_dimN_reg_block); } /*-------------- L2 blocking for dimN block ---------*/ auto test_cond_dimN_block = [](jit_conv_winograd_conf_t &jcp, int dimN_block, int current_best) { return check_L2_block_per_thread(jcp, dimN_block, 0.1, 1.3) && (dimN_block > current_best) && ((jcp.dimN / dimN_block / jcp.dimN_reg_block) > 2 * omp_get_max_threads()); }; jcp.dimN_block = get_divisor_satisfying_cond( jcp, jcp.dimN / jcp.dimN_reg_block, 1, test_cond_dimN_block); if (check_L2_block_per_thread(jcp, jcp.dimN_block, 0.1, 1.3) && jcp.dimN/ jcp.dimN_block/ jcp.dimN_reg_block > 2 * omp_get_max_threads()) { jcp.dimN_nb_block = jcp.dimN / jcp.dimN_block / jcp.dimN_reg_block; /* ------------------- L1 blocking for GEMM --------------*/ /* -------------------- Choose dimK block ----------------*/ auto test_cond_dimK_block = [](jit_conv_winograd_conf_t &jcp, int dimK_block, int current_best) { return check_L1_block_gemm(jcp, dimK_block, 1, 0.1, 0.6) && (dimK_block > current_best); }; jcp.dimK_block = get_divisor_satisfying_cond( jcp, jcp.dimK / jcp.dimK_reg_block, 1, test_cond_dimK_block); if (check_L1_block_gemm(jcp, jcp.dimK_block, 1, 0.1, 0.6)) { jcp.dimK_nb_block = jcp.dimK / jcp.dimK_block / jcp.dimK_reg_block; /* -------------- Choose dimM block -------------------*/ auto test_cond_dimM_block = [](jit_conv_winograd_conf_t &jcp, int dimM_block, int current_best) { return check_L1_block_gemm(jcp, jcp.dimK_block, dimM_block, 0.1, 0.7) && (dimM_block > current_best); }; jcp.dimM_block = get_divisor_satisfying_cond( jcp, jcp.dimM / jcp.dimM_simd_block, 1, test_cond_dimM_block); jcp.dimM_nb_block = jcp.dimM / jcp.dimM_block / jcp.dimM_simd_block; jcp.sched_policy = WSCHED_DATA_W_SGD; return status::success; } } return status::unimplemented; } status_t set_wsched_DATA_W_S_G_D(jit_conv_winograd_conf_t &jcp) { auto test_cond_dimN_reg_block = [](jit_conv_winograd_conf_t &jcp, int dimN_reg_block, int current_best) { return (dimN_reg_block >= MIN_REQUIRED_DIMN_REG_BLOCK) && (dimN_reg_block < jcp.nb_reg) && (dimN_reg_block < current_best); }; jcp.dimN_reg_block = get_divisor_satisfying_cond( jcp, jcp.dimN, jcp.dimN, test_cond_dimN_reg_block); if (jcp.dimN_reg_block >= jcp.nb_reg) { auto test_cond_dimN_reg_block = [](jit_conv_winograd_conf_t &jcp, int dimN_reg_block, int current_best) { return (dimN_reg_block < jcp.nb_reg) && (dimN_reg_block > current_best); }; jcp.dimN_reg_block = get_divisor_satisfying_cond( jcp, jcp.dimN, 1, test_cond_dimN_reg_block); } //********************* Choosing dimK_block **********************// auto test_cond1_dimK_block = []( jit_conv_winograd_conf_t &jcp, int dimK_block, int current_best) { return check_cond1(jcp.dimN_reg_block, dimK_block, jcp.dimK_reg_block, 1, jcp.dimM_simd_block, .75f) && (dimK_block > current_best); }; auto test_cond1_bis_dimK_block = []( jit_conv_winograd_conf_t &jcp, int dimK_block, int current_best) { return check_cond1_bis(jcp.dimN_reg_block, dimK_block, jcp.dimK_reg_block, 1, jcp.dimM_simd_block, .9f) && (dimK_block > current_best); }; jcp.dimK_block = get_divisor_satisfying_cond( jcp, jcp.dimK / jcp.dimK_reg_block, 1, test_cond1_bis_dimK_block); // If we are not able to use streams, we fall back to condition [1] if (jcp.dimK_block < jcp.dimK / jcp.dimK_reg_block) jcp.dimK_block = get_divisor_satisfying_cond( jcp, jcp.dimK / jcp.dimK_reg_block, 1, test_cond1_dimK_block); jcp.dimK_nb_block = (jcp.dimK / jcp.dimK_reg_block) / jcp.dimK_block; //********************* Choosing dimM_block **********************// jcp.dimM_simd_block = 16; /*XXX: Why C=0.5 here but C=0.75 for dimK_block?*/ auto test_cond1_dimM_block = []( jit_conv_winograd_conf_t &jcp, int dimM_block, int current_best) { return check_cond1(jcp.dimN_reg_block, jcp.dimK_block, jcp.dimK_reg_block, dimM_block, jcp.dimM_simd_block, .5f) && (dimM_block > current_best); }; auto test_cond1_bis_dimM_block = []( jit_conv_winograd_conf_t &jcp, int dimM_block, int current_best) { return check_cond1_bis(jcp.dimN_reg_block, jcp.dimK_block, jcp.dimK_reg_block, dimM_block, jcp.dimM_simd_block, .3f) && (dimM_block > current_best); }; if (jcp.dimK_block < jcp.dimK / jcp.dimK_reg_block) jcp.dimM_block = get_divisor_satisfying_cond( jcp, jcp.dimM / jcp.dimM_simd_block, 1, test_cond1_dimM_block); else jcp.dimM_block = get_divisor_satisfying_cond(jcp, jcp.dimM / jcp.dimM_simd_block, 1, test_cond1_bis_dimM_block); jcp.dimM_nb_block = (jcp.dimM / jcp.dimM_simd_block) / jcp.dimM_block; //******************* Choosing dimN_block *******************// auto test_cond2_dimN_block = []( jit_conv_winograd_conf_t &jcp, int dimN_block, int current_best) { return check_cond2(dimN_block, jcp.dimN_reg_block, jcp.dimK_nb_block, jcp.dimK_block, jcp.dimK_reg_block, jcp.dimM_block, jcp.dimM_simd_block, .5f) && (dimN_block > current_best); }; jcp.dimN_block = get_divisor_satisfying_cond( jcp, jcp.dimN / jcp.dimN_reg_block, 1, test_cond2_dimN_block); jcp.dimN_nb_block = jcp.dimN / (jcp.dimN_reg_block * jcp.dimN_block); jcp.sched_policy = WSCHED_DATA_W_S_G_D; return status::success; //return status::unimplemented; } status_t _jit_avx512_common_conv_winograd_data_kernel_f32::init_conf_kernel( jit_conv_winograd_conf_t &jcp, int dimM, int dimN, int dimK) { jcp.dimK_reg_block = 16; jcp.dimM_simd_block = 16; // TODO: replace double buffering with nuple buffering to maximize register // usage. // the choice of the number of buffers will then come after choosing // dimN_reg_block jcp.double_buffering = true; if (jcp.double_buffering) jcp.zmm_start = 2 * ((jcp.ver == ver_4fma) ? 4 : 2); else jcp.zmm_start = 1; jcp.nb_reg = 32 - jcp.zmm_start; jcp.dimN = dimN; jcp.dimK = dimK; jcp.dimM = dimM; jcp.sched_policy = WSCHED_INVALID; if (!(set_wsched_DATA_W_SGD(jcp) == status::success)) set_wsched_DATA_W_S_G_D(jcp); assert(jcp.sched_policy != WSCHED_INVALID); return status::success; } status_t jit_avx512_common_conv_winograd_fwd_kernel_f32::init_conf( jit_conv_winograd_conf_t &jcp, const convolution_desc_t &cd, const memory_desc_wrapper &src_d, const memory_desc_wrapper &weights_d, const memory_desc_wrapper &dst_d, bool with_relu, float relu_negative_slope) { status_t st = init_conf_common(jcp, cd, src_d, weights_d, dst_d); if (st != status::success) return st; // Winograd specific initialization const int tile_size = jcp.alpha - 2; jcp.itiles = (jcp.ow + tile_size - 1) / tile_size; jcp.jtiles = (jcp.oh + tile_size - 1) / tile_size; jcp.ntiles = jcp.mb * jcp.itiles * jcp.jtiles; jcp.with_bias = cd.bias_desc.format != memory_format::undef; jcp.with_relu = with_relu; jcp.relu_negative_slope = relu_negative_slope; status_t res = init_conf_kernel(jcp, jcp.oc, jcp.ntiles, jcp.ic); jcp.ic_simd_block = jcp.dimK_reg_block; jcp.ic_block = jcp.dimK_block; jcp.nb_ic = jcp.dimK_nb_block; jcp.oc_simd_block = jcp.dimM_simd_block; jcp.oc_block = jcp.dimM_block; jcp.nb_oc = jcp.dimM_nb_block; jcp.tile_block_ur = jcp.dimN_reg_block; jcp.nb_tile_block_ur = jcp.dimN_block; jcp.tile_block = jcp.dimN_nb_block; jcp.tile_4fma_padding = 0; // only relevant for backward weights return res; } status_t jit_avx512_common_conv_winograd_bwd_data_kernel_f32::init_conf( jit_conv_winograd_conf_t &jcp, const convolution_desc_t &cd, const memory_desc_wrapper &diff_src_d, const memory_desc_wrapper &weights_d, const memory_desc_wrapper &diff_dst_d) { status_t st = init_conf_common(jcp, cd, diff_src_d, weights_d, diff_dst_d); if (st != status::success) return st; const int tile_size = jcp.alpha - 2; jcp.itiles = (jcp.iw + tile_size - 1) / tile_size; jcp.jtiles = (jcp.ih + tile_size - 1) / tile_size; jcp.ntiles = jcp.mb * jcp.itiles * jcp.jtiles; status_t res = init_conf_kernel(jcp, jcp.ic, jcp.ntiles, jcp.oc); jcp.oc_simd_block = jcp.dimK_reg_block; jcp.oc_block = jcp.dimK_block; jcp.nb_oc = jcp.dimK_nb_block; jcp.ic_simd_block = jcp.dimM_simd_block; jcp.ic_block = jcp.dimM_block; jcp.nb_ic = jcp.dimM_nb_block; jcp.tile_block_ur = jcp.dimN_reg_block; jcp.nb_tile_block_ur = jcp.dimN_block; jcp.tile_block = jcp.dimN_nb_block; jcp.tile_4fma_padding = 0; // only relevant for backward weights return res; } void jit_avx512_common_conv_winograd_bwd_weights_kernel_f32::transpose_ker_generate() { auto load_B = [=](int reg_idx, int offset) { for (int i = 0; i < 4; i++) { vmovups(Zmm(reg_idx + i), zword[reg_origB + (offset + i) * jcp.dimN_reg_block * sizeof(float)]); } }; int curr = 0; for (int j = 0; j < jcp.alpha; j++) { for (int i = 0; i < jcp.alpha; i++) { int origB_offset = (j * jcp.alpha + i) * jcp.dimK_4fma; int transB_offset = (j * jcp.alpha + i) * jcp.dimK_nb_block * jcp.dimN_block * jcp.dimK_block * jcp.dimK_reg_block * jcp.dimK_4fma * jcp.dimN_reg_block; for (int tb = 0; tb < jcp.dimK_4fma; tb+=4) { /*double buffering to hide load latencies*/ int next = (curr + 4) % 8; if (i == 0 && tb == 0) { load_B(0, origB_offset); } if (tb + 4 < (jcp.dimK_4fma -1)) { load_B(next, origB_offset + 4); } else if (i < jcp.alpha - 1) { load_B(next, origB_offset + jcp.dimK_4fma); } vunpcklps(Zmm(8), Zmm(curr), Zmm(curr + 1)); vunpcklps(Zmm(9), Zmm(curr + 2), Zmm(curr + 3)); vunpckhps(Zmm(curr), Zmm(curr), Zmm(curr + 1)); vunpckhps(Zmm(curr + 1), Zmm(curr + 2), Zmm(curr + 3)); vunpcklpd(Zmm(curr + 2), Zmm(8), Zmm(9)); vunpckhpd(Zmm(curr + 3), Zmm(8), Zmm(9)); vunpcklpd(Zmm(8), Zmm(curr), Zmm(curr + 1)); vunpckhpd(Zmm(9), Zmm(curr), Zmm(curr + 1)); vmovntps(zword[reg_transB + sizeof(float) * (transB_offset + tb * jcp.dimN_reg_block)], Zmm(curr+2)); vmovntps(zword[reg_transB + sizeof(float) * (transB_offset + (tb + 1) * jcp.dimN_reg_block)], Zmm(curr+3)); vmovntps(zword[reg_transB + sizeof(float) * (transB_offset + (tb + 2) * jcp.dimN_reg_block)], Zmm(8)); vmovntps(zword[reg_transB + sizeof(float) * (transB_offset + (tb + 3) * jcp.dimN_reg_block)], Zmm(9)); curr = next; } } } ret(); } void jit_avx512_common_conv_winograd_bwd_weights_kernel_f32::gemm_loop_generate( bool is_first_tile) { // for (int ofm2 = 0; ofm2 < jcp.oc_block; ofm2++) // for (int ifm2 = 0; ifm2 < jcp.ic_block; ifm2++) // for (int nb_tile_block_ur = 0; nb_tile_block_ur < // jcp.nb_tile_block_ur; nb_tile_block_ur++) // for (int tile_block_ur = 0; tile_block_ur < // jcp.tile_block_ur; tile_block_ur++) // for (int ifm3 = 0; ifm3 < jcp.ic_reg_block; ++ifm3) // U[ofm2][ifm2][ofm3][ifm3][0:oc_simd_block] += // M[ofm2][ofm3][nb_tile_block_ur][tile_block_ur][0:oc_simd_block] // * // broadcast(V[ifm2][nb_tile_block_ur][ifm3][tile_block_ur]) auto inner_loops = [=]() { int inc_fma = jcp.ver == ver_4fma ? 4 : 1; const int fma_ipc = jcp.ver == ver_4fma ? 1 : 2; prefetcher_t L1_pf(this, reg_srcB, L1, jcp.dimK_reg_block * jcp.dimN_reg_block * jcp.dimK_4fma, jcp.dimK_reg_block * jcp.dimN_reg_block * jcp.dimK_4fma / inc_fma, fma_ipc); prefetcher_t L2_pf(this, reg_srcB, L2, jcp.dimK_reg_block * jcp.dimN_reg_block * jcp.dimK_4fma, jcp.dimK_reg_block * jcp.dimN_reg_block * jcp.dimK_4fma / inc_fma, fma_ipc); auto load_A = [=](int reg_idx, int offset) { for (int i = 0; i < inc_fma; i++) { vmovups(Zmm(reg_idx + i), zword[reg_srcA + sizeof(float) * jcp.dimM_simd_block * (offset + i)]); } }; Label dimM_block_loop, dimK_block_loop, dimN_block_loop; if (jcp.dimM_block > 1) { mov(reg_dimM_block_loop_cnt, jcp.dimM_block); L(dimM_block_loop); } { /************* OC_block (M) loop ***********/ if (jcp.dimN_block > 1) { mov(reg_dimN_block_loop_cnt, jcp.dimN_block); L(dimN_block_loop); } { /*************** IC_block (N) loop *********/ for (int dimN_reg_block = 0; dimN_reg_block < jcp.dimN_reg_block; ++dimN_reg_block) { Zmm zmm(jcp.zmm_start + dimN_reg_block); if (is_first_tile) vpxord(zmm, zmm, zmm); else vmovups(zmm, zword[reg_dstC + dimN_reg_block * jcp.dimM_simd_block * sizeof(float)]); } if (jcp.dimK_block > 1) { mov(reg_dimK_block_loop_cnt, jcp.dimK_block); L(dimK_block_loop); } { /************* nb_tile_ur(K) loop ********/ int next = 0; if (jcp.double_buffering) { load_A(next, 0); } for (int dimK_reg_block = 0; dimK_reg_block < jcp.dimK_reg_block; dimK_reg_block++) { int srcB_offset = dimK_reg_block * jcp.dimK_4fma * jcp.dimN_reg_block; for (int dimK_4fma = 0; dimK_4fma < jcp.dimK_4fma; dimK_4fma += inc_fma) { int current = next; if (jcp.double_buffering) { next = (dimK_reg_block * jcp.dimK_4fma + dimK_4fma + inc_fma) % (2 * inc_fma); load_A(next, dimK_reg_block * jcp.dimK_4fma + dimK_4fma + inc_fma); } else { next = 0; load_A(next, dimK_reg_block * jcp.dimK_4fma + dimK_4fma); } for (int dimN_reg_block = 0; dimN_reg_block < jcp.dimN_reg_block; ++dimN_reg_block) { L1_pf.prefetch(srcB_offset / inc_fma + dimK_4fma / inc_fma * jcp.dimN_reg_block + dimN_reg_block); L2_pf.prefetch(srcB_offset / inc_fma + dimK_4fma / inc_fma * jcp.dimN_reg_block + dimN_reg_block); if (jcp.ver == ver_4fma) { int srcB_trans_offset = (dimK_4fma / 4) * 64 + dimK_4fma % 4; v4fmaddps( Zmm(jcp.zmm_start + dimN_reg_block), Zmm(current), EVEX_compress_addr(reg_srcB, sizeof(float) * ( srcB_offset + srcB_trans_offset + (dimN_reg_block % 4) * 16 + (dimN_reg_block / 4) * 4))); } else { vfmadd231ps( Zmm(jcp.zmm_start + dimN_reg_block), Zmm(current), EVEX_compress_addr(reg_srcB, sizeof(float) * (srcB_offset + dimN_reg_block), true)); } } } } } add(reg_srcA, jcp.dimK_reg_block * jcp.dimK_4fma * jcp.dimM_simd_block * sizeof(float)); add(reg_srcB, jcp.dimK_reg_block * jcp.dimN_reg_block * jcp.dimK_4fma * sizeof(float)); if (jcp.dimK_block > 1) { sub(reg_dimK_block_loop_cnt, 1); jnz(dimK_block_loop); } /******** Write C back to memory *******/ for (int dimN_reg_block = 0; dimN_reg_block < jcp.dimN_reg_block; ++dimN_reg_block) { Zmm zmm(jcp.zmm_start + dimN_reg_block); vmovups(zword[reg_dstC + dimN_reg_block * jcp.dimM_simd_block * sizeof(float)], zmm); } sub(reg_srcA, jcp.dimK_block * jcp.dimK_reg_block * jcp.dimK_4fma * jcp.dimM_simd_block * sizeof(float)); add(reg_dstC, jcp.dimN_reg_block * jcp.dimM_simd_block * sizeof(float)); if (jcp.dimN_block > 1) { sub(reg_dimN_block_loop_cnt, 1); jnz(dimN_block_loop); } } if (jcp.dimM_block > 1) { sub(reg_srcB, jcp.dimN_block * jcp.dimK_block * jcp.dimK_reg_block * jcp.dimN_reg_block * jcp.dimK_4fma * sizeof(float)); add(reg_srcA, jcp.dimK_block * jcp.dimK_reg_block * jcp.dimK_4fma * jcp.dimM_simd_block * sizeof(float)); sub(reg_dimM_block_loop_cnt, 1); jnz(dimM_block_loop); } } }; /* Preamble */ // register used to handle long fma encoding push(reg_EVEX_max_8b_offt); push(reg_dimK_block_loop_cnt); mov(reg_EVEX_max_8b_offt, 2 * EVEX_max_8b_offt); mov(reg_srcA, reg_srcA_const); inner_loops(); /* Postamble */ pop(reg_dimK_block_loop_cnt); pop(reg_EVEX_max_8b_offt); ret(); } namespace { bool check_cond1_wu(int dimM_block, int dimM_simdw, int dimK_block, int dimK_reg_block, int dimK_4fma, int dimN_reg_block, float C) { float lhs = 1.0f * dimM_block * dimN_reg_block * dimM_simdw; lhs += dimM_block * dimK_block * dimK_reg_block * dimK_4fma * dimM_simdw; lhs += dimK_block * dimN_reg_block * dimK_reg_block * dimK_4fma; lhs *= sizeof(float); float rhs = C * L1_cache_size; return (lhs <= rhs); } bool check_cond1bis_wu(int dimM_block, int dimM_simdw, int dimK_block, int dimK_reg_block, int dimK_4fma, int dimN_reg_block, float C) { float lhs = 1.0f * dimM_block * dimK_block * dimK_reg_block * dimK_4fma * dimM_simdw; lhs += dimK_block * dimN_reg_block * dimK_reg_block * dimK_4fma; lhs *= sizeof(float); float rhs = C * L1_cache_size; return (lhs <= rhs); } bool check_cond2bis_wu(int dimM_block, int dimM_simdw, int dimK_block, int dimK_reg_block, int dimK_4fma, int dimN_block, int dimN_reg_block, float C) { float lhs = 1.0f * dimM_block * dimM_simdw * dimK_block * dimK_reg_block * dimK_4fma; lhs += dimK_block * dimK_reg_block * dimK_4fma * dimN_block * dimN_reg_block; lhs *= sizeof(float); float rhs = C * L2_cache_size; return (lhs <= rhs); } bool check_cond2_wu(int dimM_block, int dimM_simdw, int dimK_block, int dimK_reg_block, int dimK_4fma, int dimN_block, int dimN_reg_block, float C) { float lhs = 1.0f * dimM_block * dimM_simdw * dimN_block * dimN_reg_block; lhs += dimM_block * dimM_simdw * dimK_block * dimK_reg_block * dimK_4fma; lhs += dimK_block * dimK_reg_block * dimK_4fma * dimN_block * dimN_reg_block; lhs *= sizeof(float); float rhs = C * L2_cache_size; return (lhs <= rhs); } } // namespace bool set_wsched_WEI_S_D_G_W(jit_conv_winograd_conf_t &jcp) { /*************** Choose dimN_reg_block (ic_simd_block) * *******************************/ jcp.dimN = jcp.ic; /*Hardcoded to 16 because N = ic for bwd weights and innermost dimension for ic is assumed 16 in src transforms. This choice covers load latencies while maintaining simplicity of kernel for POR topologies. FIXME in future??: Will not work for future topologies when ic%16 != 0*/ jcp.dimN_reg_block = jcp.ic_simd_block; /****************************** Choose dimK_block * **************************/ // No freedom for choosing dimM_simd_block because ic_simd_block // is determined by input data format jcp.dimM_simd_block = jcp.oc_simd_block; auto test_cond1bis_dimK_block = []( jit_conv_winograd_conf_t &jcp, int dimK_block, int current_best) { return check_cond1bis_wu(1, jcp.dimM_simd_block, dimK_block, 1, jcp.dimK_4fma, jcp.dimN_reg_block, 0.4f) && (dimK_block > current_best); }; auto test_cond1_dimK_block = []( jit_conv_winograd_conf_t &jcp, int dimK_block, int current_best) { return check_cond1_wu(1, jcp.dimM_simd_block, dimK_block, 1, jcp.dimK_4fma, jcp.dimN_reg_block, 0.4f) && (dimK_block > current_best); }; auto test_cond2bis_dimK_block = []( jit_conv_winograd_conf_t &jcp, int dimK_block, int current_best) { return check_cond2bis_wu(1, jcp.dimM_simd_block, dimK_block, 1, jcp.dimK_4fma, 1, jcp.dimN_reg_block, 0.5f) && (dimK_block > current_best); }; auto test_cond2_dimK_block = []( jit_conv_winograd_conf_t &jcp, int dimK_block, int current_best) { return check_cond2_wu(1, jcp.dimM_simd_block, dimK_block, 1, jcp.dimK_4fma, 1, jcp.dimN_reg_block, 0.1f) && (dimK_block > current_best); }; jcp.dimK_block = get_divisor_satisfying_cond( jcp, jcp.dimK / jcp.dimK_4fma, 1, test_cond2bis_dimK_block); if (jcp.dimK_block < jcp.dimK / jcp.dimK_4fma) jcp.dimK_block = get_divisor_satisfying_cond( jcp, jcp.dimK / jcp.dimK_4fma, 1, test_cond2_dimK_block); jcp.dimK_reg_block = get_divisor_satisfying_cond( jcp, jcp.dimK_block, 1, test_cond1bis_dimK_block); if (jcp.dimK_reg_block < jcp.dimK_block) { jcp.dimK_reg_block = get_divisor_satisfying_cond( jcp, jcp.dimK_block, 1, test_cond1_dimK_block); } jcp.dimK_block /= jcp.dimK_reg_block; jcp.dimK_nb_block = jcp.dimK / jcp.dimK_4fma / jcp.dimK_reg_block / jcp.dimK_block; jcp.tile_block_ur = jcp.dimK_reg_block; jcp.nb_tile_block_ur = jcp.dimK_block; jcp.tile_block = jcp.dimK_nb_block; /***************************** Chose dimN block * ****************************/ auto test_cond2_dimN_block = []( jit_conv_winograd_conf_t &jcp, int dimN_block, int current_best) { return check_cond2_wu(1, jcp.dimM_simd_block, jcp.dimK_block, jcp.dimK_reg_block, jcp.dimK_4fma, dimN_block, jcp.dimN_reg_block, 0.5f) && (dimN_block > current_best); }; jcp.dimN_block = get_divisor_satisfying_cond( jcp, jcp.dimN / jcp.dimN_reg_block, 1, test_cond2_dimN_block); jcp.ic_block = jcp.dimN_block; jcp.dimN_nb_block = jcp.dimN / jcp.dimN_reg_block / jcp.dimN_block; jcp.nb_ic = jcp.dimN_nb_block; /********************************* Choose dimM block * ************************/ jcp.dimM = jcp.oc; auto test_cond1_dimM_block = []( jit_conv_winograd_conf_t &jcp, int dimM_block, int current_best) { return check_cond1_wu(dimM_block, jcp.dimM_simd_block, 1, jcp.dimK_reg_block, jcp.dimK_4fma, jcp.dimN_reg_block, 1.0f) && (dimM_block > current_best) && (jcp.dimM / jcp.dimM_simd_block / dimM_block) >= 2; }; jcp.dimM_block = get_divisor_satisfying_cond( jcp, jcp.dimM / jcp.dimM_simd_block, 1, test_cond1_dimM_block); jcp.dimM_nb_block = (jcp.dimM / jcp.dimM_simd_block) / jcp.dimM_block; jcp.sched_policy = WSCHED_WEI_S_D_G_W; return true; } namespace { bool is_in_L1_range(int v, float C1, float C2) { return ((v > C1 * L1_cache_size) && (v < C2 * L1_cache_size)); } bool is_in_L2_range(int v, float C1, float C2) { return ((v > C1 * L2_cache_size) && (v < C2 * L2_cache_size)); } void set_jcp_WEI_params(jit_conv_winograd_conf_t &jcp, int tile_block_ur, int tile_block, int nb_ic, int nb_oc) { jcp.tile_block_ur = tile_block_ur; jcp.tile_block = tile_block; jcp.nb_ic = nb_ic; jcp.nb_oc = nb_oc; jcp.nb_tile_block_ur = jcp.ntiles / jcp.tile_block / jcp.tile_block_ur; jcp.ic_block = jcp.ic / jcp.ic_simd_block / jcp.nb_ic; jcp.oc_block = jcp.oc / jcp.oc_simd_block / jcp.nb_oc; jcp.dimK_reg_block = jcp.tile_block_ur; jcp.dimK_block = jcp.nb_tile_block_ur; jcp.dimK_nb_block = jcp.tile_block; jcp.dimN_reg_block = jcp.ic_simd_block; jcp.dimN_block = jcp.ic_block; jcp.dimN_nb_block = jcp.nb_ic; jcp.dimM_simd_block = jcp.oc_simd_block; jcp.dimM_block = jcp.oc_block; jcp.dimM_nb_block = jcp.nb_oc; } } // namespace bool set_wsched_WEI_SDGt_W(jit_conv_winograd_conf_t &jcp) { jcp.ic_simd_block = jcp.oc_simd_block = 16; int nb_ic_simd_block = jcp.ic / jcp.ic_simd_block; int nb_oc_simd_block = jcp.oc / jcp.oc_simd_block; int min_tile_block_ur = 8; int max_tile_block_ur = 64; int max_tile_block = jcp.ntiles / min_tile_block_ur; // Consider L2 + L3 together on SKX const float C1_min = .1, C1_0 = .4, C1_max = .5; const float C2_0 = .4, C2_max = .5; const float TC2_0 = .7, TC2_max = 1.2; const int T_min = 2, T0 = 20; float C1, C2, TC2; int T, tile_block, tile_block_ur, nb_oc, nb_ic; auto blocking_ok = [&]() -> bool { // V:tile_block + M:tile_block + U int thread_size = jcp.alpha * jcp.alpha * jcp.oc * (jcp.ntiles / tile_block) * sizeof(float) + jcp.alpha * jcp.alpha * jcp.ic * (jcp.ntiles / tile_block) * sizeof(float) + jcp.alpha * jcp.alpha * jcp.ic * jcp.oc * sizeof(float); // V:tile_block + M:tile_block int L2_reuse = jcp.alpha * jcp.alpha * jcp.oc * (jcp.ntiles / tile_block) * sizeof(float) + jcp.alpha * jcp.alpha * jcp.ic * (jcp.ntiles / tile_block) * sizeof(float); // V:nb_ic + M:nb_tile_block_ur // Use M:nb_oc + V:nb_ic as an superset estimation int L1_reuse = (jcp.ic / nb_ic) * (jcp.ntiles / tile_block) * sizeof(float) + (jcp.oc / nb_oc) * (jcp.ntiles / tile_block) * sizeof(float); return jcp.ntiles % tile_block == 0 && (jcp.ntiles / tile_block) % tile_block_ur == 0 && is_in_L2_range(thread_size, TC2, TC2_max) && is_in_L2_range(L2_reuse, C2, C2_max) && tile_block > T * omp_get_max_threads() && nb_oc_simd_block % nb_oc == 0 && nb_ic_simd_block % nb_ic == 0 && is_in_L1_range(L1_reuse, C1, C1_max); }; for (C1 = C1_0, C2 = C2_0, TC2 = TC2_0; C1 > C1_min; C1 -= .02, C2 -= .02, TC2 -= .04) { for (T = T0; T >= T_min; --T) { for (tile_block = 1; tile_block <= max_tile_block; ++tile_block) { for (tile_block_ur = max_tile_block_ur; tile_block_ur >= min_tile_block_ur; --tile_block_ur) { for (nb_oc = 1; nb_oc <= nb_oc_simd_block; ++nb_oc) { for (nb_ic = nb_ic_simd_block; nb_ic >= 1; --nb_ic) { if (blocking_ok()) { set_jcp_WEI_params(jcp, tile_block_ur, tile_block, nb_ic, nb_oc); jcp.sched_policy = WSCHED_WEI_SDGt_W; return true; } } } } } } } return false; } bool set_wsched_WEI_SDGtWo(jit_conv_winograd_conf_t &jcp) { jcp.ic_simd_block = jcp.oc_simd_block = 16; int nb_ic_simd_block = jcp.ic / jcp.ic_simd_block; int nb_oc_simd_block = jcp.oc / jcp.oc_simd_block; int min_tile_block_ur = 12; int max_tile_block_ur = 64; int max_tile_block = jcp.ntiles / min_tile_block_ur; const float C1_min = .1, C1_0 = .4, C1_max = .5; const float C2_0 = .4, C2_max = .6; const float TC2_0 = .7, TC2_max = 1.6; const int max_nb_oc = 2; // Limit the # of sequential execution const int T0 = 12, T_min = 8; float C1, C2, TC2; int T, tile_block, tile_block_ur, nb_oc, nb_ic; auto blocking_ok = [&]() -> bool { // M:tile_block:nb_oc + V:tile_block + U:nb_oc int thread_size = jcp.alpha * jcp.alpha * (jcp.oc / nb_oc) * (jcp.ntiles / tile_block) * sizeof(float) + jcp.alpha * jcp.alpha * jcp.ic * (jcp.ntiles / tile_block) * sizeof(float) + jcp.alpha * jcp.alpha * jcp.ic * (jcp.oc / nb_oc) * sizeof(float); // M:tile_block:nb_oc + V:tile_block int L2_reuse = jcp.alpha * jcp.alpha * (jcp.oc / nb_oc) * (jcp.ntiles / tile_block) * sizeof(float) + jcp.alpha * jcp.alpha * jcp.ic * (jcp.ntiles / tile_block) * sizeof(float); // V:nb_ic + M:nb_tile_block_ur // Use M:nb_oc + V:nb_ic as an superset estimation int L1_reuse = (jcp.ic / nb_ic) * (jcp.ntiles / tile_block) * sizeof(float) + (jcp.oc / nb_oc) * (jcp.ntiles / tile_block) * sizeof(float); return jcp.ntiles % tile_block == 0 && (jcp.ntiles / tile_block) % tile_block_ur == 0 && is_in_L2_range(thread_size, TC2, TC2_max) && is_in_L2_range(L2_reuse, C2, C2_max) && tile_block > T * omp_get_max_threads() && nb_oc_simd_block % nb_oc == 0 && nb_ic_simd_block % nb_ic == 0 && is_in_L1_range(L1_reuse, C1, C1_max); }; for (T = T0; T >= T_min; --T) { for (C1 = C1_0, C2 = C2_0, TC2 = TC2_0; C1 > C1_min; C1 -= .02, C2 -= .02, TC2 -= .04) { for (nb_oc = 1; nb_oc <= max_nb_oc; ++nb_oc) { for (tile_block = max_tile_block; tile_block >= 1; --tile_block) { for (tile_block_ur = min_tile_block_ur; tile_block_ur <= max_tile_block_ur; ++tile_block_ur) { for (nb_ic = 1; nb_ic <= nb_ic_simd_block; ++nb_ic) { if (blocking_ok()) { set_jcp_WEI_params(jcp, tile_block_ur, tile_block, nb_ic, nb_oc); jcp.sched_policy = WSCHED_WEI_SDGtWo; return true; } } } } } } } return false; } bool set_wsched_WEI_S_D_Giot_W(jit_conv_winograd_conf_t &jcp) { jcp.ic_simd_block = jcp.oc_simd_block = 16; int nb_ic_simd_block = jcp.ic / jcp.ic_simd_block; int min_tile_block_ur = 8; int max_tile_block_ur = 64; const float C1_min = .2, C1_0 = .4, C1_max = .9; const float C2_min = .1, C2_0 = .4, C2_max = .5; const int T0 = 16, T_min = 12; float C1, C2; int T, tile_block, tile_block_ur, nb_ic; int nb_oc = 1; // Keep nb_oc small to increase // oc_block, for better reuse of V in // L2 auto blocking_ok = [&]() -> bool { // V[:ic_block][][][] int L2_reuse = (jcp.ic / nb_ic) * (jcp.ntiles / tile_block) * sizeof(float); // M[:nb_tile_block_ur][][] + V[:nb_tile_block_ur][][] int L1_reuse = (jcp.ntiles / tile_block) * jcp.oc_simd_block * sizeof(float); int work_amount = tile_block * nb_ic * nb_oc * jcp.alpha * jcp.alpha; return (jcp.ntiles / tile_block_ur) % tile_block == 0 && jcp.ntiles % tile_block_ur == 0 && nb_ic_simd_block % nb_ic == 0 && is_in_L2_range(L2_reuse, C2, C2_max) && is_in_L1_range(L1_reuse, C1, C1_max) && work_amount > T * omp_get_max_threads(); }; for (T = T0; T >= T_min; --T) { for (C1 = C1_0; C1 > C1_min; C1 -= .02) { for (C2 = C2_0; C2 > C2_min; C2 -= .02) { for (nb_ic = 1; nb_ic <= nb_ic_simd_block; ++nb_ic) { for (tile_block_ur = min_tile_block_ur; tile_block_ur <= max_tile_block_ur; ++tile_block_ur) { for (tile_block = 1; tile_block <= jcp.ntiles / min_tile_block_ur; ++tile_block) { if (blocking_ok()) { set_jcp_WEI_params(jcp, tile_block_ur, tile_block, nb_ic, nb_oc); jcp.sched_policy = WSCHED_WEI_S_D_Giot_W; return true; } } } } } } } return false; } status_t jit_avx512_common_conv_winograd_bwd_weights_kernel_f32::init_conf( jit_conv_winograd_conf_t &jcp, const convolution_desc_t &cd, const memory_desc_wrapper &src_d, const memory_desc_wrapper &diff_dst_d, const memory_desc_wrapper &diff_weights_d) { if (!mayiuse(avx512_common)) return status::unimplemented; const bool with_groups = diff_weights_d.ndims() == src_d.ndims() + 1; const int simd_w = 16; jcp.ngroups = with_groups ? diff_weights_d.dims()[0] : 1; jcp.mb = src_d.dims()[0]; jcp.oc = diff_dst_d.dims()[1] / jcp.ngroups; jcp.ic = src_d.dims()[1] / jcp.ngroups; jcp.ih = src_d.dims()[2]; jcp.iw = src_d.dims()[3]; jcp.oh = diff_dst_d.dims()[2]; jcp.ow = diff_dst_d.dims()[3]; jcp.kh = diff_weights_d.dims()[with_groups + 2]; jcp.kw = diff_weights_d.dims()[with_groups + 3]; jcp.t_pad = cd.padding[0][0]; jcp.l_pad = cd.padding[0][1]; jcp.stride_h = cd.strides[0]; jcp.stride_w = cd.strides[1]; jcp.r_pad = nstl::max( 0, (jcp.ow - 1) * jcp.stride_w + jcp.kw - jcp.iw - jcp.l_pad); jcp.b_pad = nstl::max( 0, (jcp.oh - 1) * jcp.stride_h + jcp.kh - jcp.ih - jcp.t_pad); jcp.ihp = jcp.ih + jcp.t_pad + jcp.b_pad; jcp.iwp = jcp.iw + jcp.l_pad + jcp.r_pad; jcp.ohp = jcp.oh; jcp.owp = jcp.ow; jcp.with_bias = (cd.diff_bias_desc.format != memory_format::undef); jcp.dilate_h = cd.dilates[0]; jcp.dilate_w = cd.dilates[1]; if (!mayiuse(avx512_common)) return status::unimplemented; else if (mayiuse(avx512_core)) jcp.ver = ver_avx512_core; else if (mayiuse(avx512_mic_4ops)) jcp.ver = ver_4fma; else jcp.ver = ver_fma; // Winograd specific initialization const int tile_size = jcp.alpha - 2; jcp.itiles = (jcp.ow + tile_size - 1) / tile_size; jcp.jtiles = (jcp.oh + tile_size - 1) / tile_size; jcp.ntiles = jcp.mb * jcp.itiles * jcp.jtiles; // Winograd kernel works only for 3x3 convolution with stride 1 if (jcp.ngroups != 1) return status::unimplemented; if ((jcp.kh != 3) || (jcp.kw != 3)) return status::unimplemented; if ((jcp.dilate_h != 0) || (jcp.dilate_w != 0)) return status::unimplemented; if ((jcp.stride_h != 1) || (jcp.stride_w != 1)) return status::unimplemented; if ((jcp.ic % simd_w) != 0 || (jcp.oc % simd_w) != 0) return status::unimplemented; if (src_d.format() != nChw16c) return status::unimplemented; if (diff_weights_d.format() != (with_groups ? gOIhw16i16o : OIhw16i16o)) return status::unimplemented; if (diff_dst_d.format() != nChw16c) return status::unimplemented; /*************************** New Kernel Parameters * *****************************/ jcp.ic_simd_block = simd_w; jcp.oc_simd_block = simd_w; jcp.dimK_4fma = 1; jcp.tile_4fma_padding = 0; #define MAX_4FMA_UR 8 if (jcp.ver == ver_4fma) { auto test_cond_4fma = [](jit_conv_winograd_conf_t &jcp, int dimK_4fma, int current_best) { return (dimK_4fma % 4 == 0) && (dimK_4fma <= MAX_4FMA_UR) && (dimK_4fma > current_best); }; jcp.dimK_4fma = get_divisor_satisfying_cond( jcp, jcp.itiles * jcp.jtiles, 4, test_cond_4fma); if (jcp.dimK_4fma == 1) jcp.dimK_4fma = 4; if ((jcp.itiles * jcp.jtiles) % jcp.dimK_4fma != 0) jcp.tile_4fma_padding = jcp.dimK_4fma - ((jcp.itiles * jcp.jtiles) % jcp.dimK_4fma); } jcp.tile_4fma = jcp.dimK_4fma; /*NOTE: When (itiles * jtiles) % dimK_4fma != 0, transpose in diff_src * transform * will not work correctly, this is solved by applying padding.*/ jcp.dimK = jcp.mb * (jcp.itiles * jcp.jtiles + jcp.tile_4fma_padding); jcp.dimN = jcp.ic; jcp.dimM = jcp.oc; jcp.double_buffering = true; if (jcp.double_buffering) jcp.zmm_start = jcp.ver == ver_4fma ? 8 : 2; else jcp.zmm_start = jcp.ver == ver_4fma ? 4 : 1; jcp.nb_reg = 32 - jcp.zmm_start; status_t res; jcp.sched_policy = WSCHED_INVALID; if ((jcp.ver == ver_avx512_core && (set_wsched_WEI_SDGt_W(jcp) || set_wsched_WEI_SDGtWo(jcp) || set_wsched_WEI_S_D_Giot_W(jcp))) || set_wsched_WEI_S_D_G_W(jcp)) res = status::success; else return status::unimplemented; jcp.tile_block_ur = jcp.dimK_reg_block; jcp.nb_tile_block_ur = jcp.dimK_block; jcp.tile_block = jcp.dimK_nb_block; jcp.ic_block = jcp.dimN_block; jcp.nb_ic = jcp.dimN_nb_block; jcp.oc_block = jcp.dimM_block; jcp.nb_oc = jcp.dimM_nb_block; return res; } } } } // vim: et ts=4 sw=4 cindent cino^=l0,\\:0,N-s ",16194,True,3423.2880613638804,median "[[netty-component]] = Netty Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-netty/src/main/docs/netty-component.adoc :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with the Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/netty.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 72 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | *Deprecated* Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. There are 2 enums and the value can be one of: tcp, udp | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== [NOTE] ==== Read below about using non shareable encoders/decoders. ==== === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSLTLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. [TIP] ==== The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. [NOTE] ==== Read further above about using non shareable encoders/decoders. ==== The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- [TIP] ==== For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. [NOTE] ==== We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. ==== You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. include::camel-spring-boot::page$netty-starter.adoc[] ",12463,False,2334.5860328488197,median "///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2009 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_RBTREE_HPP #define BOOST_INTRUSIVE_RBTREE_HPP #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace boost { namespace intrusive { /// @cond template struct setopt { typedef ValueTraits value_traits; typedef Compare compare; typedef SizeType size_type; static const bool constant_time_size = ConstantTimeSize; }; template struct set_defaults : pack_options < none , base_hook , constant_time_size , size_type , compare > >::type {}; /// @endcond //! The class template rbtree is an intrusive red-black tree container, that //! is used to construct intrusive set and multiset containers. The no-throw //! guarantee holds only, if the value_compare object //! doesn't throw. //! //! The template parameter \\c T is the type to be managed by the container. //! The user can specify additional options and if no options are provided //! default options are used. //! //! The container supports the following options: //! \\c base_hook<>/member_hook<>/value_traits<>, //! \\c constant_time_size<>, \\c size_type<> and //! \\c compare<>. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template #else template #endif class rbtree_impl : private detail::clear_on_destructor_base > { template friend class detail::clear_on_destructor_base; public: typedef typename Config::value_traits value_traits; /// @cond static const bool external_value_traits = detail::external_value_traits_is_true::value; typedef typename detail::eval_if_c < external_value_traits , detail::eval_value_traits , detail::identity >::type real_value_traits; /// @endcond typedef typename real_value_traits::pointer pointer; typedef typename real_value_traits::const_pointer const_pointer; typedef typename std::iterator_traits::value_type value_type; typedef value_type key_type; typedef typename std::iterator_traits::reference reference; typedef typename std::iterator_traits::reference const_reference; typedef typename std::iterator_traits::difference_type difference_type; typedef typename Config::size_type size_type; typedef typename Config::compare value_compare; typedef value_compare key_compare; typedef tree_iterator iterator; typedef tree_iterator const_iterator; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef typename real_value_traits::node_traits node_traits; typedef typename node_traits::node node; typedef typename node_traits::node_ptr node_ptr; typedef typename node_traits::const_node_ptr const_node_ptr; typedef rbtree_algorithms node_algorithms; static const bool constant_time_size = Config::constant_time_size; static const bool stateful_value_traits = detail::is_stateful_value_traits::value; /// @cond private: typedef detail::size_holder size_traits; //noncopyable BOOST_MOVABLE_BUT_NOT_COPYABLE(rbtree_impl) enum { safemode_or_autounlink = (int)real_value_traits::link_mode == (int)auto_unlink || (int)real_value_traits::link_mode == (int)safe_link }; //Constant-time size is incompatible with auto-unlink hooks! BOOST_STATIC_ASSERT(!(constant_time_size && ((int)real_value_traits::link_mode == (int)auto_unlink))); struct header_plus_size : public size_traits { node header_; }; struct node_plus_pred_t : public detail::ebo_functor_holder { node_plus_pred_t(const value_compare &comp) : detail::ebo_functor_holder(comp) {} header_plus_size header_plus_size_; }; struct data_t : public rbtree_impl::value_traits { typedef typename rbtree_impl::value_traits value_traits; data_t(const value_compare & comp, const value_traits &val_traits) : value_traits(val_traits), node_plus_pred_(comp) {} node_plus_pred_t node_plus_pred_; } data_; const value_compare &priv_comp() const { return data_.node_plus_pred_.get(); } value_compare &priv_comp() { return data_.node_plus_pred_.get(); } const value_traits &priv_value_traits() const { return data_; } value_traits &priv_value_traits() { return data_; } const node &priv_header() const { return data_.node_plus_pred_.header_plus_size_.header_; } node &priv_header() { return data_.node_plus_pred_.header_plus_size_.header_; } static node_ptr uncast(const_node_ptr ptr) { return node_ptr(const_cast(detail::boost_intrusive_get_pointer(ptr))); //iG pending return node_ptr(boost::const_pointer_cast(ptr)); } size_traits &priv_size_traits() { return data_.node_plus_pred_.header_plus_size_; } const size_traits &priv_size_traits() const { return data_.node_plus_pred_.header_plus_size_; } const real_value_traits &get_real_value_traits(detail::bool_) const { return data_; } const real_value_traits &get_real_value_traits(detail::bool_) const { return data_.get_value_traits(*this); } real_value_traits &get_real_value_traits(detail::bool_) { return data_; } real_value_traits &get_real_value_traits(detail::bool_) { return data_.get_value_traits(*this); } protected: value_compare &prot_comp() { return priv_comp(); } const node &prot_header_node() const { return priv_header(); } node &prot_header_node() { return priv_header(); } void prot_set_size(size_type s) { this->priv_size_traits().set_size(s); } /// @endcond public: const real_value_traits &get_real_value_traits() const { return this->get_real_value_traits(detail::bool_()); } real_value_traits &get_real_value_traits() { return this->get_real_value_traits(detail::bool_()); } typedef typename node_algorithms::insert_commit_data insert_commit_data; //! Effects: Constructs an empty tree. //! //! Complexity: Constant. //! //! Throws: If value_traits::node_traits::node //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the copy constructorof the value_compare object throws. Basic guarantee. rbtree_impl( const value_compare &cmp = value_compare() , const value_traits &v_traits = value_traits()) : data_(cmp, v_traits) { node_algorithms::init_header(&priv_header()); this->priv_size_traits().set_size(size_type(0)); } //! Requires: Dereferencing iterator must yield an lvalue of type value_type. //! cmp must be a comparison function that induces a strict weak ordering. //! //! Effects: Constructs an empty tree and inserts elements from //! [b, e). //! //! Complexity: Linear in N if [b, e) is already sorted using //! comp and otherwise N * log N, where N is the distance between first and last. //! //! Throws: If value_traits::node_traits::node //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the copy constructor/operator() of the value_compare object throws. Basic guarantee. template rbtree_impl( bool unique, Iterator b, Iterator e , const value_compare &cmp = value_compare() , const value_traits &v_traits = value_traits()) : data_(cmp, v_traits) { node_algorithms::init_header(&priv_header()); this->priv_size_traits().set_size(size_type(0)); if(unique) this->insert_unique(b, e); else this->insert_equal(b, e); } //! Effects: to-do //! rbtree_impl(BOOST_RV_REF(rbtree_impl) x) : data_(::boost::move(x.priv_comp()), ::boost::move(x.priv_value_traits())) { node_algorithms::init_header(&priv_header()); this->priv_size_traits().set_size(size_type(0)); this->swap(x); } //! Effects: to-do //! rbtree_impl& operator=(BOOST_RV_REF(rbtree_impl) x) { this->swap(x); return *this; } //! Effects: Detaches all elements from this. The objects in the set //! are not deleted (i.e. no destructors are called), but the nodes according to //! the value_traits template parameter are reinitialized and thus can be reused. //! //! Complexity: Linear to elements contained in *this. //! //! Throws: Nothing. ~rbtree_impl() {} //! Effects: Returns an iterator pointing to the beginning of the tree. //! //! Complexity: Constant. //! //! Throws: Nothing. iterator begin() { return iterator (node_traits::get_left(node_ptr(&priv_header())), this); } //! Effects: Returns a const_iterator pointing to the beginning of the tree. //! //! Complexity: Constant. //! //! Throws: Nothing. const_iterator begin() const { return cbegin(); } //! Effects: Returns a const_iterator pointing to the beginning of the tree. //! //! Complexity: Constant. //! //! Throws: Nothing. const_iterator cbegin() const { return const_iterator (node_traits::get_left(const_node_ptr(&priv_header())), this); } //! Effects: Returns an iterator pointing to the end of the tree. //! //! Complexity: Constant. //! //! Throws: Nothing. iterator end() { return iterator (node_ptr(&priv_header()), this); } //! Effects: Returns a const_iterator pointing to the end of the tree. //! //! Complexity: Constant. //! //! Throws: Nothing. const_iterator end() const { return cend(); } //! Effects: Returns a const_iterator pointing to the end of the tree. //! //! Complexity: Constant. //! //! Throws: Nothing. const_iterator cend() const { return const_iterator (uncast(const_node_ptr(&priv_header())), this); } //! Effects: Returns a reverse_iterator pointing to the beginning of the //! reversed tree. //! //! Complexity: Constant. //! //! Throws: Nothing. reverse_iterator rbegin() { return reverse_iterator(end()); } //! Effects: Returns a const_reverse_iterator pointing to the beginning //! of the reversed tree. //! //! Complexity: Constant. //! //! Throws: Nothing. const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } //! Effects: Returns a const_reverse_iterator pointing to the beginning //! of the reversed tree. //! //! Complexity: Constant. //! //! Throws: Nothing. const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); } //! Effects: Returns a reverse_iterator pointing to the end //! of the reversed tree. //! //! Complexity: Constant. //! //! Throws: Nothing. reverse_iterator rend() { return reverse_iterator(begin()); } //! Effects: Returns a const_reverse_iterator pointing to the end //! of the reversed tree. //! //! Complexity: Constant. //! //! Throws: Nothing. const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } //! Effects: Returns a const_reverse_iterator pointing to the end //! of the reversed tree. //! //! Complexity: Constant. //! //! Throws: Nothing. const_reverse_iterator crend() const { return const_reverse_iterator(begin()); } //! Precondition: end_iterator must be a valid end iterator //! of rbtree. //! //! Effects: Returns a const reference to the rbtree associated to the end iterator //! //! Throws: Nothing. //! //! Complexity: Constant. static rbtree_impl &container_from_end_iterator(iterator end_iterator) { return priv_container_from_end_iterator(end_iterator); } //! Precondition: end_iterator must be a valid end const_iterator //! of rbtree. //! //! Effects: Returns a const reference to the rbtree associated to the iterator //! //! Throws: Nothing. //! //! Complexity: Constant. static const rbtree_impl &container_from_end_iterator(const_iterator end_iterator) { return priv_container_from_end_iterator(end_iterator); } //! Precondition: it must be a valid iterator //! of rbtree. //! //! Effects: Returns a const reference to the tree associated to the iterator //! //! Throws: Nothing. //! //! Complexity: Logarithmic. static rbtree_impl &container_from_iterator(iterator it) { return priv_container_from_iterator(it); } //! Precondition: it must be a valid end const_iterator //! of rbtree. //! //! Effects: Returns a const reference to the tree associated to the end iterator //! //! Throws: Nothing. //! //! Complexity: Logarithmic. static const rbtree_impl &container_from_iterator(const_iterator it) { return priv_container_from_iterator(it); } //! Effects: Returns the value_compare object used by the tree. //! //! Complexity: Constant. //! //! Throws: If value_compare copy-constructor throws. value_compare value_comp() const { return priv_comp(); } //! Effects: Returns true if the container is empty. //! //! Complexity: Constant. //! //! Throws: Nothing. bool empty() const { return node_algorithms::unique(const_node_ptr(&priv_header())); } //! Effects: Returns the number of elements stored in the tree. //! //! Complexity: Linear to elements contained in *this //! if constant-time size option is disabled. Constant time otherwise. //! //! Throws: Nothing. size_type size() const { if(constant_time_size) return this->priv_size_traits().get_size(); else{ return (size_type)node_algorithms::size(const_node_ptr(&priv_header())); } } //! Effects: Swaps the contents of two rbtrees. //! //! Complexity: Constant. //! //! Throws: If the comparison functor's swap call throws. void swap(rbtree_impl& other) { //This can throw using std::swap; swap(priv_comp(), priv_comp()); //These can't throw node_algorithms::swap_tree(node_ptr(&priv_header()), node_ptr(&other.priv_header())); if(constant_time_size){ size_type backup = this->priv_size_traits().get_size(); this->priv_size_traits().set_size(other.priv_size_traits().get_size()); other.priv_size_traits().set_size(backup); } } //! Requires: value must be an lvalue //! //! Effects: Inserts value into the tree before the upper bound. //! //! Complexity: Average complexity for insert element is at //! most logarithmic. //! //! Throws: If the internal value_compare ordering function throws. Strong guarantee. //! //! Note: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_equal(reference value) { detail::key_nodeptr_comp key_node_comp(priv_comp(), this); node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); iterator ret(node_algorithms::insert_equal_upper_bound (node_ptr(&priv_header()), to_insert, key_node_comp), this); this->priv_size_traits().increment(); return ret; } //! Requires: value must be an lvalue, and ""hint"" must be //! a valid iterator. //! //! Effects: Inserts x into the tree, using ""hint"" as a hint to //! where it will be inserted. If ""hint"" is the upper_bound //! the insertion takes constant time (two comparisons in the worst case) //! //! Complexity: Logarithmic in general, but it is amortized //! constant time if t is inserted immediately before hint. //! //! Throws: If the internal value_compare ordering function throws. Strong guarantee. //! //! Note: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_equal(const_iterator hint, reference value) { detail::key_nodeptr_comp key_node_comp(priv_comp(), this); node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); iterator ret(node_algorithms::insert_equal (node_ptr(&priv_header()), hint.pointed_node(), to_insert, key_node_comp), this); this->priv_size_traits().increment(); return ret; } //! Requires: Dereferencing iterator must yield an lvalue //! of type value_type. //! //! Effects: Inserts a each element of a range into the tree //! before the upper bound of the key of each element. //! //! Complexity: Insert range is in general O(N * log(N)), where N is the //! size of the range. However, it is linear in N if the range is already sorted //! by value_comp(). //! //! Throws: Nothing. //! //! Note: Does not affect the validity of iterators and references. //! No copy-constructors are called. template void insert_equal(Iterator b, Iterator e) { iterator iend(this->end()); for (; b != e; ++b) this->insert_equal(iend, *b); } //! Requires: value must be an lvalue //! //! Effects: Inserts value into the tree if the value //! is not already present. //! //! Complexity: Average complexity for insert element is at //! most logarithmic. //! //! Throws: Nothing. //! //! Note: Does not affect the validity of iterators and references. //! No copy-constructors are called. std::pair insert_unique(reference value) { insert_commit_data commit_data; std::pair ret = insert_unique_check(value, priv_comp(), commit_data); if(!ret.second) return ret; return std::pair (insert_unique_commit(value, commit_data), true); } //! Requires: value must be an lvalue, and ""hint"" must be //! a valid iterator //! //! Effects: Tries to insert x into the tree, using ""hint"" as a hint //! to where it will be inserted. //! //! Complexity: Logarithmic in general, but it is amortized //! constant time (two comparisons in the worst case) //! if t is inserted immediately before hint. //! //! Throws: Nothing. //! //! Note: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_unique(const_iterator hint, reference value) { insert_commit_data commit_data; std::pair ret = insert_unique_check(hint, value, priv_comp(), commit_data); if(!ret.second) return ret.first; return insert_unique_commit(value, commit_data); } //! Requires: Dereferencing iterator must yield an lvalue //! of type value_type. //! //! Effects: Tries to insert each element of a range into the tree. //! //! Complexity: Insert range is in general O(N * log(N)), where N is the //! size of the range. However, it is linear in N if the range is already sorted //! by value_comp(). //! //! Throws: Nothing. //! //! Note: Does not affect the validity of iterators and references. //! No copy-constructors are called. template void insert_unique(Iterator b, Iterator e) { if(this->empty()){ iterator iend(this->end()); for (; b != e; ++b) this->insert_unique(iend, *b); } else{ for (; b != e; ++b) this->insert_unique(*b); } } //! Requires: key_value_comp must be a comparison function that induces //! the same strict weak ordering as value_compare. The difference is that //! key_value_comp compares an arbitrary key with the contained values. //! //! Effects: Checks if a value can be inserted in the container, using //! a user provided key instead of the value itself. //! //! Returns: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills ""commit_data"" that is meant to be used with //! the ""insert_commit"" function. //! //! Complexity: Average complexity is at most logarithmic. //! //! Throws: If the key_value_comp ordering function throws. Strong guarantee. //! //! Notes: This function is used to improve performance when constructing //! a value_type is expensive: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! node that is used to impose the order is much cheaper to construct //! than the value_type and this function offers the possibility to use that //! part to check if the insertion will be successful. //! //! If the check is successful, the user can construct the value_type and use //! ""insert_commit"" to insert the object in constant-time. This gives a total //! logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)). //! //! ""commit_data"" remains valid for a subsequent ""insert_commit"" only if no more //! objects are inserted or erased from the container. template std::pair insert_unique_check (const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data) { detail::key_nodeptr_comp comp(key_value_comp, this); std::pair ret = (node_algorithms::insert_unique_check (node_ptr(&priv_header()), key, comp, commit_data)); return std::pair(iterator(ret.first, this), ret.second); } //! Requires: key_value_comp must be a comparison function that induces //! the same strict weak ordering as value_compare. The difference is that //! key_value_comp compares an arbitrary key with the contained values. //! //! Effects: Checks if a value can be inserted in the container, using //! a user provided key instead of the value itself, using ""hint"" //! as a hint to where it will be inserted. //! //! Returns: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills ""commit_data"" that is meant to be used with //! the ""insert_commit"" function. //! //! Complexity: Logarithmic in general, but it's amortized //! constant time if t is inserted immediately before hint. //! //! Throws: If the key_value_comp ordering function throws. Strong guarantee. //! //! Notes: This function is used to improve performance when constructing //! a value_type is expensive: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! constructing that is used to impose the order is much cheaper to construct //! than the value_type and this function offers the possibility to use that key //! to check if the insertion will be successful. //! //! If the check is successful, the user can construct the value_type and use //! ""insert_commit"" to insert the object in constant-time. This can give a total //! constant-time complexity to the insertion: check(O(1)) + commit(O(1)). //! //! ""commit_data"" remains valid for a subsequent ""insert_commit"" only if no more //! objects are inserted or erased from the container. template std::pair insert_unique_check (const_iterator hint, const KeyType &key ,KeyValueCompare key_value_comp, insert_commit_data &commit_data) { detail::key_nodeptr_comp comp(key_value_comp, this); std::pair ret = (node_algorithms::insert_unique_check (node_ptr(&priv_header()), hint.pointed_node(), key, comp, commit_data)); return std::pair(iterator(ret.first, this), ret.second); } //! Requires: value must be an lvalue of type value_type. commit_data //! must have been obtained from a previous call to ""insert_check"". //! No objects should have been inserted or erased from the container between //! the ""insert_check"" that filled ""commit_data"" and the call to ""insert_commit"". //! //! Effects: Inserts the value in the avl_set using the information obtained //! from the ""commit_data"" that a previous ""insert_check"" filled. //! //! Returns: An iterator to the newly inserted object. //! //! Complexity: Constant time. //! //! Throws: Nothing. //! //! Notes: This function has only sense if a ""insert_check"" has been //! previously executed to fill ""commit_data"". No value should be inserted or //! erased between the ""insert_check"" and ""insert_commit"" calls. iterator insert_unique_commit(reference value, const insert_commit_data &commit_data) { node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); node_algorithms::insert_unique_commit (node_ptr(&priv_header()), to_insert, commit_data); this->priv_size_traits().increment(); return iterator(to_insert, this); } //! Requires: value must be an lvalue, ""pos"" must be //! a valid iterator (or end) and must be the succesor of value //! once inserted according to the predicate //! //! Effects: Inserts x into the tree before ""pos"". //! //! Complexity: Constant time. //! //! Throws: Nothing. //! //! Note: This function does not check preconditions so if ""pos"" is not //! the successor of ""value"" tree ordering invariant will be broken. //! This is a low-level function to be used only for performance reasons //! by advanced users. iterator insert_before(const_iterator pos, reference value) { node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); this->priv_size_traits().increment(); return iterator(node_algorithms::insert_before (node_ptr(&priv_header()), pos.pointed_node(), to_insert), this); } //! Requires: value must be an lvalue, and it must be no less //! than the greatest inserted key //! //! Effects: Inserts x into the tree in the last position. //! //! Complexity: Constant time. //! //! Throws: Nothing. //! //! Note: This function does not check preconditions so if value is //! less than the greatest inserted key tree ordering invariant will be broken. //! This function is slightly more efficient than using ""insert_before"". //! This is a low-level function to be used only for performance reasons //! by advanced users. void push_back(reference value) { node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); this->priv_size_traits().increment(); node_algorithms::push_back(node_ptr(&priv_header()), to_insert); } //! Requires: value must be an lvalue, and it must be no greater //! than the minimum inserted key //! //! Effects: Inserts x into the tree in the first position. //! //! Complexity: Constant time. //! //! Throws: Nothing. //! //! Note: This function does not check preconditions so if value is //! greater than the minimum inserted key tree ordering invariant will be broken. //! This function is slightly more efficient than using ""insert_before"". //! This is a low-level function to be used only for performance reasons //! by advanced users. void push_front(reference value) { node_ptr to_insert(get_real_value_traits().to_node_ptr(value)); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert)); this->priv_size_traits().increment(); node_algorithms::push_front(node_ptr(&priv_header()), to_insert); } //! Effects: Erases the element pointed to by pos. //! //! Complexity: Average complexity for erase element is constant time. //! //! Throws: Nothing. //! //! Note: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. iterator erase(const_iterator i) { const_iterator ret(i); ++ret; node_ptr to_erase(i.pointed_node()); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!node_algorithms::unique(to_erase)); node_algorithms::erase(&priv_header(), to_erase); this->priv_size_traits().decrement(); if(safemode_or_autounlink) node_algorithms::init(to_erase); return ret.unconst(); } //! Effects: Erases the range pointed to by b end e. //! //! Complexity: Average complexity for erase range is at most //! O(log(size() + N)), where N is the number of elements in the range. //! //! Throws: Nothing. //! //! Note: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. iterator erase(const_iterator b, const_iterator e) { size_type n; return private_erase(b, e, n); } //! Effects: Erases all the elements with the given value. //! //! Returns: The number of erased elements. //! //! Complexity: O(log(size() + N). //! //! Throws: Nothing. //! //! Note: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. size_type erase(const_reference value) { return this->erase(value, priv_comp()); } //! Effects: Erases all the elements with the given key. //! according to the comparison functor ""comp"". //! //! Returns: The number of erased elements. //! //! Complexity: O(log(size() + N). //! //! Throws: Nothing. //! //! Note: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template size_type erase(const KeyType& key, KeyValueCompare comp /// @cond , typename detail::enable_if_c::value >::type * = 0 /// @endcond ) { std::pair p = this->equal_range(key, comp); size_type n; private_erase(p.first, p.second, n); return n; } //! Requires: Disposer::operator()(pointer) shouldn't throw. //! //! Effects: Erases the element pointed to by pos. //! Disposer::operator()(pointer) is called for the removed element. //! //! Complexity: Average complexity for erase element is constant time. //! //! Throws: Nothing. //! //! Note: Invalidates the iterators //! to the erased elements. template iterator erase_and_dispose(const_iterator i, Disposer disposer) { node_ptr to_erase(i.pointed_node()); iterator ret(this->erase(i)); disposer(get_real_value_traits().to_value_ptr(to_erase)); return ret; } #if !defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template iterator erase_and_dispose(iterator i, Disposer disposer) { return this->erase_and_dispose(const_iterator(i), disposer); } #endif //! Requires: Disposer::operator()(pointer) shouldn't throw. //! //! Effects: Erases all the elements with the given value. //! Disposer::operator()(pointer) is called for the removed elements. //! //! Returns: The number of erased elements. //! //! Complexity: O(log(size() + N). //! //! Throws: Nothing. //! //! Note: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template size_type erase_and_dispose(const_reference value, Disposer disposer) { std::pair p = this->equal_range(value); size_type n; private_erase(p.first, p.second, n, disposer); return n; } //! Requires: Disposer::operator()(pointer) shouldn't throw. //! //! Effects: Erases the range pointed to by b end e. //! Disposer::operator()(pointer) is called for the removed elements. //! //! Complexity: Average complexity for erase range is at most //! O(log(size() + N)), where N is the number of elements in the range. //! //! Throws: Nothing. //! //! Note: Invalidates the iterators //! to the erased elements. template iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer) { size_type n; return private_erase(b, e, n, disposer); } //! Requires: Disposer::operator()(pointer) shouldn't throw. //! //! Effects: Erases all the elements with the given key. //! according to the comparison functor ""comp"". //! Disposer::operator()(pointer) is called for the removed elements. //! //! Returns: The number of erased elements. //! //! Complexity: O(log(size() + N). //! //! Throws: Nothing. //! //! Note: Invalidates the iterators //! to the erased elements. template size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer /// @cond , typename detail::enable_if_c::value >::type * = 0 /// @endcond ) { std::pair p = this->equal_range(key, comp); size_type n; private_erase(p.first, p.second, n, disposer); return n; } //! Effects: Erases all of the elements. //! //! Complexity: Linear to the number of elements on the container. //! if it's a safe-mode or auto-unlink value_type. Constant time otherwise. //! //! Throws: Nothing. //! //! Note: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. void clear() { if(safemode_or_autounlink){ this->clear_and_dispose(detail::null_disposer()); } else{ node_algorithms::init_header(&priv_header()); this->priv_size_traits().set_size(0); } } //! Effects: Erases all of the elements calling disposer(p) for //! each node to be erased. //! Complexity: Average complexity for is at most O(log(size() + N)), //! where N is the number of elements in the container. //! //! Throws: Nothing. //! //! Note: Invalidates the iterators (but not the references) //! to the erased elements. Calls N times to disposer functor. template void clear_and_dispose(Disposer disposer) { node_algorithms::clear_and_dispose(node_ptr(&priv_header()) , detail::node_disposer(disposer, this)); node_algorithms::init_header(&priv_header()); this->priv_size_traits().set_size(0); } //! Effects: Returns the number of contained elements with the given value //! //! Complexity: Logarithmic to the number of elements contained plus lineal //! to number of objects with the given value. //! //! Throws: Nothing. size_type count(const_reference value) const { return this->count(value, priv_comp()); } //! Effects: Returns the number of contained elements with the given key //! //! Complexity: Logarithmic to the number of elements contained plus lineal //! to number of objects with the given key. //! //! Throws: Nothing. template size_type count(const KeyType &key, KeyValueCompare comp) const { std::pair ret = this->equal_range(key, comp); return std::distance(ret.first, ret.second); } //! Effects: Returns an iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. iterator lower_bound(const_reference value) { return this->lower_bound(value, priv_comp()); } //! Effects: Returns an iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. const_iterator lower_bound(const_reference value) const { return this->lower_bound(value, priv_comp()); } //! Effects: Returns an iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. template iterator lower_bound(const KeyType &key, KeyValueCompare comp) { detail::key_nodeptr_comp key_node_comp(comp, this); return iterator(node_algorithms::lower_bound (const_node_ptr(&priv_header()), key, key_node_comp), this); } //! Effects: Returns a const iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. template const_iterator lower_bound(const KeyType &key, KeyValueCompare comp) const { detail::key_nodeptr_comp key_node_comp(comp, this); return const_iterator(node_algorithms::lower_bound (const_node_ptr(&priv_header()), key, key_node_comp), this); } //! Effects: Returns an iterator to the first element whose //! key is greater than k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. iterator upper_bound(const_reference value) { return this->upper_bound(value, priv_comp()); } //! Effects: Returns an iterator to the first element whose //! key is greater than k according to comp or end() if that element //! does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. template iterator upper_bound(const KeyType &key, KeyValueCompare comp) { detail::key_nodeptr_comp key_node_comp(comp, this); return iterator(node_algorithms::upper_bound (const_node_ptr(&priv_header()), key, key_node_comp), this); } //! Effects: Returns an iterator to the first element whose //! key is greater than k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. const_iterator upper_bound(const_reference value) const { return this->upper_bound(value, priv_comp()); } //! Effects: Returns an iterator to the first element whose //! key is greater than k according to comp or end() if that element //! does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. template const_iterator upper_bound(const KeyType &key, KeyValueCompare comp) const { detail::key_nodeptr_comp key_node_comp(comp, this); return const_iterator(node_algorithms::upper_bound (const_node_ptr(&priv_header()), key, key_node_comp), this); } //! Effects: Finds an iterator to the first element whose key is //! k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. iterator find(const_reference value) { return this->find(value, priv_comp()); } //! Effects: Finds an iterator to the first element whose key is //! k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. template iterator find(const KeyType &key, KeyValueCompare comp) { detail::key_nodeptr_comp key_node_comp(comp, this); return iterator (node_algorithms::find(const_node_ptr(&priv_header()), key, key_node_comp), this); } //! Effects: Finds a const_iterator to the first element whose key is //! k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. const_iterator find(const_reference value) const { return this->find(value, priv_comp()); } //! Effects: Finds a const_iterator to the first element whose key is //! k or end() if that element does not exist. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. template const_iterator find(const KeyType &key, KeyValueCompare comp) const { detail::key_nodeptr_comp key_node_comp(comp, this); return const_iterator (node_algorithms::find(const_node_ptr(&priv_header()), key, key_node_comp), this); } //! Effects: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. std::pair equal_range(const_reference value) { return this->equal_range(value, priv_comp()); } //! Effects: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. template std::pair equal_range(const KeyType &key, KeyValueCompare comp) { detail::key_nodeptr_comp key_node_comp(comp, this); std::pair ret (node_algorithms::equal_range(const_node_ptr(&priv_header()), key, key_node_comp)); return std::pair(iterator(ret.first, this), iterator(ret.second, this)); } //! Effects: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. std::pair equal_range(const_reference value) const { return this->equal_range(value, priv_comp()); } //! Effects: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! Complexity: Logarithmic. //! //! Throws: Nothing. template std::pair equal_range(const KeyType &key, KeyValueCompare comp) const { detail::key_nodeptr_comp key_node_comp(comp, this); std::pair ret (node_algorithms::equal_range(const_node_ptr(&priv_header()), key, key_node_comp)); return std::pair(const_iterator(ret.first, this), const_iterator(ret.second, this)); } //! Requires: Disposer::operator()(pointer) shouldn't throw. //! Cloner should yield to nodes equivalent to the original nodes. //! //! Effects: Erases all the elements from *this //! calling Disposer::operator()(pointer), clones all the //! elements from src calling Cloner::operator()(const_reference ) //! and inserts them on *this. Copies the predicate from the source container. //! //! If cloner throws, all cloned elements are unlinked and disposed //! calling Disposer::operator()(pointer). //! //! Complexity: Linear to erased plus inserted elements. //! //! Throws: If cloner throws or predicate copy assignment throws. Basic guarantee. template void clone_from(const rbtree_impl &src, Cloner cloner, Disposer disposer) { this->clear_and_dispose(disposer); if(!src.empty()){ detail::exception_disposer rollback(*this, disposer); node_algorithms::clone (const_node_ptr(&src.priv_header()) ,node_ptr(&this->priv_header()) ,detail::node_cloner(cloner, this) ,detail::node_disposer(disposer, this)); this->priv_size_traits().set_size(src.priv_size_traits().get_size()); this->priv_comp() = src.priv_comp(); rollback.release(); } } //! Effects: Unlinks the leftmost node from the tree. //! //! Complexity: Average complexity is constant time. //! //! Throws: Nothing. //! //! Notes: This function breaks the tree and the tree can //! only be used for more unlink_leftmost_without_rebalance calls. //! This function is normally used to achieve a step by step //! controlled destruction of the tree. pointer unlink_leftmost_without_rebalance() { node_ptr to_be_disposed(node_algorithms::unlink_leftmost_without_rebalance (node_ptr(&priv_header()))); if(!to_be_disposed) return 0; this->priv_size_traits().decrement(); if(safemode_or_autounlink)//If this is commented does not work with normal_link node_algorithms::init(to_be_disposed); return get_real_value_traits().to_value_ptr(to_be_disposed); } //! Requires: replace_this must be a valid iterator of *this //! and with_this must not be inserted in any tree. //! //! Effects: Replaces replace_this in its position in the //! tree with with_this. The tree does not need to be rebalanced. //! //! Complexity: Constant. //! //! Throws: Nothing. //! //! Note: This function will break container ordering invariants if //! with_this is not equivalent to *replace_this according to the //! ordering rules. This function is faster than erasing and inserting //! the node, since no rebalancing or comparison is needed. void replace_node(iterator replace_this, reference with_this) { node_algorithms::replace_node( get_real_value_traits().to_node_ptr(*replace_this) , node_ptr(&priv_header()) , get_real_value_traits().to_node_ptr(with_this)); if(safemode_or_autounlink) node_algorithms::init(replace_this.pointed_node()); } //! Requires: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! Effects: Returns: a valid iterator i belonging to the set //! that points to the value //! //! Complexity: Constant. //! //! Throws: Nothing. //! //! Note: This static function is available only if the value traits //! is stateless. static iterator s_iterator_to(reference value) { BOOST_STATIC_ASSERT((!stateful_value_traits)); return iterator (value_traits::to_node_ptr(value), 0); } //! Requires: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! Effects: Returns: a valid const_iterator i belonging to the //! set that points to the value //! //! Complexity: Constant. //! //! Throws: Nothing. //! //! Note: This static function is available only if the value traits //! is stateless. static const_iterator s_iterator_to(const_reference value) { BOOST_STATIC_ASSERT((!stateful_value_traits)); return const_iterator (value_traits::to_node_ptr(const_cast (value)), 0); } //! Requires: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! Effects: Returns: a valid iterator i belonging to the set //! that points to the value //! //! Complexity: Constant. //! //! Throws: Nothing. iterator iterator_to(reference value) { return iterator (value_traits::to_node_ptr(value), this); } //! Requires: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! Effects: Returns: a valid const_iterator i belonging to the //! set that points to the value //! //! Complexity: Constant. //! //! Throws: Nothing. const_iterator iterator_to(const_reference value) const { return const_iterator (value_traits::to_node_ptr(const_cast (value)), this); } //! Requires: value shall not be in a tree. //! //! Effects: init_node puts the hook of a value in a well-known default //! state. //! //! Throws: Nothing. //! //! Complexity: Constant time. //! //! Note: This function puts the hook in the well-known default state //! used by auto_unlink and safe hooks. static void init_node(reference value) { node_algorithms::init(value_traits::to_node_ptr(value)); } //! Effects: removes ""value"" from the container. //! //! Throws: Nothing. //! //! Complexity: Logarithmic time. //! //! Note: This static function is only usable with non-constant //! time size containers that have stateless comparison functors. //! //! If the user calls //! this function with a constant time size container or stateful comparison //! functor a compilation error will be issued. static void remove_node(reference value) { BOOST_STATIC_ASSERT((!constant_time_size)); node_ptr to_remove(value_traits::to_node_ptr(value)); node_algorithms::unlink(to_remove); if(safemode_or_autounlink) node_algorithms::init(to_remove); } /// @cond private: template iterator private_erase(const_iterator b, const_iterator e, size_type &n, Disposer disposer) { for(n = 0; b != e; ++n) this->erase_and_dispose(b++, disposer); return b.unconst(); } iterator private_erase(const_iterator b, const_iterator e, size_type &n) { for(n = 0; b != e; ++n) this->erase(b++); return b.unconst(); } /// @endcond private: static rbtree_impl &priv_container_from_end_iterator(const const_iterator &end_iterator) { header_plus_size *r = detail::parent_from_member ( detail::boost_intrusive_get_pointer(end_iterator.pointed_node()), &header_plus_size::header_); node_plus_pred_t *n = detail::parent_from_member (r, &node_plus_pred_t::header_plus_size_); data_t *d = detail::parent_from_member(n, &data_t::node_plus_pred_); rbtree_impl *rb = detail::parent_from_member(d, &rbtree_impl::data_); return *rb; } static rbtree_impl &priv_container_from_iterator(const const_iterator &it) { return priv_container_from_end_iterator(it.end_iterator_from_it()); } }; #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template #else template #endif inline bool operator< #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const rbtree_impl &x, const rbtree_impl &y) #else (const rbtree_impl &x, const rbtree_impl &y) #endif { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template #else template #endif bool operator== #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const rbtree_impl &x, const rbtree_impl &y) #else (const rbtree_impl &x, const rbtree_impl &y) #endif { typedef rbtree_impl tree_type; typedef typename tree_type::const_iterator const_iterator; if(tree_type::constant_time_size && x.size() != y.size()){ return false; } const_iterator end1 = x.end(); const_iterator i1 = x.begin(); const_iterator i2 = y.begin(); if(tree_type::constant_time_size){ while (i1 != end1 && *i1 == *i2) { ++i1; ++i2; } return i1 == end1; } else{ const_iterator end2 = y.end(); while (i1 != end1 && i2 != end2 && *i1 == *i2) { ++i1; ++i2; } return i1 == end1 && i2 == end2; } } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template #else template #endif inline bool operator!= #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const rbtree_impl &x, const rbtree_impl &y) #else (const rbtree_impl &x, const rbtree_impl &y) #endif { return !(x == y); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template #else template #endif inline bool operator> #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const rbtree_impl &x, const rbtree_impl &y) #else (const rbtree_impl &x, const rbtree_impl &y) #endif { return y < x; } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template #else template #endif inline bool operator<= #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const rbtree_impl &x, const rbtree_impl &y) #else (const rbtree_impl &x, const rbtree_impl &y) #endif { return !(y < x); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template #else template #endif inline bool operator>= #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (const rbtree_impl &x, const rbtree_impl &y) #else (const rbtree_impl &x, const rbtree_impl &y) #endif { return !(x < y); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template #else template #endif inline void swap #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) (rbtree_impl &x, rbtree_impl &y) #else (rbtree_impl &x, rbtree_impl &y) #endif { x.swap(y); } /// @cond #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template #else template #endif struct make_rbtree_opt { typedef typename pack_options < set_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type packed_options; typedef typename detail::get_value_traits ::type value_traits; typedef setopt < value_traits , typename packed_options::compare , typename packed_options::size_type , packed_options::constant_time_size > type; }; /// @endcond //! Helper metafunction to define a \\c rbtree that yields to the same type when the //! same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template #else template #endif struct make_rbtree { /// @cond typedef rbtree_impl < typename make_rbtree_opt::type > implementation_defined; /// @endcond typedef implementation_defined type; }; #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template #else template #endif class rbtree : public make_rbtree::type { typedef typename make_rbtree ::type Base; BOOST_MOVABLE_BUT_NOT_COPYABLE(rbtree) public: typedef typename Base::value_compare value_compare; typedef typename Base::value_traits value_traits; typedef typename Base::real_value_traits real_value_traits; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; //Assert if passed value traits are compatible with the type BOOST_STATIC_ASSERT((detail::is_same::value)); rbtree( const value_compare &cmp = value_compare() , const value_traits &v_traits = value_traits()) : Base(cmp, v_traits) {} template rbtree( bool unique, Iterator b, Iterator e , const value_compare &cmp = value_compare() , const value_traits &v_traits = value_traits()) : Base(unique, b, e, cmp, v_traits) {} rbtree(BOOST_RV_REF(rbtree) x) : Base(::boost::move(static_cast(x))) {} rbtree& operator=(BOOST_RV_REF(rbtree) x) { this->Base::operator=(::boost::move(static_cast(x))); return *this; } static rbtree &container_from_end_iterator(iterator end_iterator) { return static_cast(Base::container_from_end_iterator(end_iterator)); } static const rbtree &container_from_end_iterator(const_iterator end_iterator) { return static_cast(Base::container_from_end_iterator(end_iterator)); } static rbtree &container_from_it(iterator it) { return static_cast(Base::container_from_iterator(it)); } static const rbtree &container_from_it(const_iterator it) { return static_cast(Base::container_from_iterator(it)); } }; #endif } //namespace intrusive } //namespace boost #include #endif //BOOST_INTRUSIVE_RBTREE_HPP ",16153,True,3555.076126924655,median "--- title: ""FreeBSD 10.1-RELEASE Announcement"" sidenav: download --- :thisBranch: 10 :thisRelease: 10.1 :lastRelease: 10.0 :thisEOL: January 1, 2017 include::shared/en/urls.adoc[] include::shared/releases.adoc[] :thisDate: {rel101-current-date} = FreeBSD {thisRelease}-RELEASE Announcement Date: {thisDate} The FreeBSD Release Engineering Team is pleased to announce the availability of FreeBSD {thisRelease}-RELEASE. This is the second release of the stable/{thisBranch} branch, which improves on the stability of FreeBSD {lastRelease}-RELEASE and introduces some new features. Some of the highlights: * The new console driver, vt(4), has been added. * Support for FreeBSD/i386 guests has been added to bhyve(4). * The bhyve(4) hypervisor now supports booting from a zfs(8) filesystem. * Support for SMP was added to the `armv6` kernels and enabled by default in the configuration files for all platforms that contain multi-core CPUs. * Initial support for UEFI boot has been added for the FreeBSD/amd64 architecture. * Support has been added to cache geli(8) passphrases during system boot. * Support for the UDP-Lite protocol (RFC 3828) has been added to the IPv4 and IPv6 stacks. * The new filesystem automount facility, autofs(5), has been added. * The sshd(8) rc.d(8) startup script now generates ED25519 sshd(8) host keys if keys do not already exist when `ssh_keygen_alg()` is invoked. * OpenSSH has been updated to version 6.6p1. * The nc(1) utility has been updated to match the version in OpenBSD 5.5. * Sendmail has been updated to 8.14.9. * The unbound(8) caching resolver and ldns have been updated to version 1.4.22. * OpenPAM has been updated to Ourouparia (20140912). * OpenSSL has been updated to version 1.0.1j. * The pkg(8) package management utility has been updated to version 1.3.8. For a complete list of new features and known problems, please see the online release notes and errata list, available at: * `https://www.FreeBSD.org/releases/{thisRelease}R/relnotes/` * `https://www.FreeBSD.org/releases/{thisRelease}R/errata/` For more information about FreeBSD release engineering activities, please see: * `https://www.FreeBSD.org/releng/` == Availability FreeBSD {thisRelease}-RELEASE is now available for the amd64, i386, ia64, powerpc, powerpc64, sparc64, and armv6 architectures. FreeBSD {thisRelease}-RELEASE can be installed from bootable ISO images or over the network. Some architectures also support installing from a USB memory stick. The required files can be downloaded via FTP as described in the section below. While some of the smaller FTP mirrors may not carry all architectures, they will all generally contain the more common ones such as amd64 and i386. SHA256 and MD5 hashes for the release ISO and memory stick images are included at the bottom of this message. A PGP-signed version of this announcement is available at: * https://www.FreeBSD.org/releases/{thisRelease}R/announce.asc Additional UEFI-capable images are available for the amd64 (x86_64) architecture. The purpose of the images provided as part of the release are as follows: *dvd1*: + This contains everything necessary to install the base FreeBSD operating system, the documentation, and a small set of pre-built packages aimed at getting a graphical workstation up and running. It also supports booting into a ""livefs"" based rescue mode. This should be all you need if you can burn and use DVD-sized media. *disc1*: + This contains the base FreeBSD operating system. It also supports booting into a ""livefs"" based rescue mode. There are no pre-built packages. *bootonly*: + This supports booting a machine using the CDROM drive but does not contain the installation distribution sets for installing FreeBSD from the CD itself. You would need to perform a network based install (e.g., from an FTP server) after booting from the CD. *memstick*: + This can be written to an USB memory stick (flash drive) and used to do an install on machines capable of booting off USB drives. It also supports booting into a ""livefs"" based rescue mode. There are no pre-built packages. As one example of how to use the memstick image, assuming the USB drive appears as /dev/da0 on your machine something like this should work: .... # dd if=FreeBSD-{thisRelease}-RELEASE-amd64-memstick.img of=/dev/da0 bs=10240 conv=sync .... Be careful to make sure you get the target (of=) correct. *mini-memstick*: + This can be written to an USB memory stick (flash drive) and used to boot a machine, but does not contain the installation distribution sets on the medium itself, similar to the bootonly image. It also supports booting into a ""livefs"" based rescue mode. There are no pre-built packages. As one example of how to use the mini-memstick image, assuming the USB drive appears as /dev/da0 on your machine something like this should work: .... # dd if=FreeBSD-{thisRelease}-RELEASE-amd64-mini-memstick.img of=/dev/da0 bs=10240 conv=sync .... Be careful to make sure you get the target (of=) correct. FreeBSD {thisRelease}-RELEASE can also be purchased on CD-ROM or DVD from several vendors. One of the vendors that will be offering FreeBSD {thisRelease}-based products is: * FreeBSD Mall, Inc. https://www.freebsdmall.com Pre-installed virtual machine images are also available for the amd64 (x86_64) and i386 (x86_32) architectures in `QCOW2`, `VHD`, and `VMDK` disk image formats, as well as raw (unformatted) images. FreeBSD {thisRelease}-RELEASE is also available on these cloud hosting platforms: * Amazon(R) EC2(TM) https://aws.amazon.com/marketplace/pp/B00KSS55FY/[FreeBSD/amd64] * Microsoft(R) Azure(TM) https://vmdepot.msopentech.com/Vhd/Show?vhdId=49971&version=51112[FreeBSD/amd64], https://vmdepot.msopentech.com/Vhd/Show?vhdId=49972&version=51113[FreeBSD/i386] == FTP FreeBSD {thisRelease}-RELEASE may be downloaded via ftp from the following site: * `ftp://ftp.freebsd.org/pub/FreeBSD/releases/ISO-IMAGES/{thisRelease}/` However before trying this site, please check your regional mirror(s) first by going to: * `ftp://ftp..FreeBSD.org/pub/FreeBSD` Any additional mirror sites will be labeled ftp2, ftp3 and so on. More information about FreeBSD mirror sites can be found at: * `link:{handbook}#mirrors-ftp[http://www.FreeBSD.org/doc/en_US.ISO8859-1/books/handbook/mirrors-ftp.html]` FreeBSD {thisRelease}-RELEASE virtual machine images may be downloaded via ftp from: * `ftp://ftp.freebsd.org/pub/FreeBSD/releases/VM-IMAGES/{thisRelease}-RELEASE/` For instructions on installing FreeBSD or updating an existing machine to {thisRelease}-RELEASE please see: * `https://www.FreeBSD.org/releases/{thisRelease}R/installation/` == Support FreeBSD {thisRelease}-RELEASE will be supported until {thisEOL}. The End-of-Life dates can be found at: * `https://www.FreeBSD.org/security/` == Other Projects Based on FreeBSD There are many ""third party"" Projects based on FreeBSD. The Projects range from re-packaging FreeBSD into a more ""novice friendly"" distribution to making FreeBSD available on Amazon's EC2 infrastructure. For more information about these Third Party Projects see: * `https://wiki.FreeBSD.org/3rdPartyProjects` == Acknowledgments Many companies donated equipment, network access, or man-hours to support the release engineering activities for FreeBSD {thisRelease} including The FreeBSD Foundation, Yahoo!, NetApp, Internet Systems Consortium, ByteMark Hosting, Sentex Communications, New York Internet, Juniper Networks, NLNet Labs, iXsystems, and Yandex. The release engineering team for {thisRelease}-RELEASE includes: [cols="","",] |=== |Glen Barber |Release Engineering Lead, {thisRelease}-RELEASE Release Engineer |Konstantin Belousov |Release Engineering |Joel Dahl |Release Engineering |Baptiste Daroussin |Package Building |Bryan Drewery |Package Building |Marc Fonvieille |Release Engineering, Documentation |Steven Kreuzer |Release Engineering |Xin Li |Release Engineering, Security Officer |Josh Paetzel |Release Engineering |Colin Percival |Security Officer Emeritus |Craig Rodrigues |Release Engineering |Hiroki Sato |Release Engineering, Documentation |Gleb Smirnoff |Release Engineering |Ken Smith |Release Engineering |Dag-Erling Smørgrav |Security Officer |Marius Strobl |Release Engineering |Robert Watson |Release Engineering, Security |=== == Trademark FreeBSD is a registered trademark of The FreeBSD Foundation. == ISO Image Checksums === amd64 (x86_64): .... SHA256 (FreeBSD-10.1-RELEASE-amd64-bootonly.iso) = 018a36681307ec3e3fe63d7c76ffc4cc53a111c36d9053e43c44856b11547d2a SHA256 (FreeBSD-10.1-RELEASE-amd64-bootonly.iso.xz) = dacc4b752798b282d4f959b241ae87008f0920125f31933425c057b41a08f0bf SHA256 (FreeBSD-10.1-RELEASE-amd64-disc1.iso) = 0c3d64ce48c3ef761761d0fea07e1935e296f8c045c249118bc91a7faf053a6b SHA256 (FreeBSD-10.1-RELEASE-amd64-disc1.iso.xz) = b7249a0b5778225876648214c66d3edfcac3fcf08ecd9dac4a8d87da6678a70c SHA256 (FreeBSD-10.1-RELEASE-amd64-dvd1.iso) = e643b7beb38fe659c255069c883476b5c9e834c66a969dadded801f10cedba37 SHA256 (FreeBSD-10.1-RELEASE-amd64-dvd1.iso.xz) = d3624c7f01a1f99a641d6a1bdc0672bd27bfbf1ffe68670cc8c940b494a85b5b SHA256 (FreeBSD-10.1-RELEASE-amd64-memstick.img) = 7a071894f12454442cf24ee4f19c2d21e2a8a79d54c83541d2cb7b9f48497b3e SHA256 (FreeBSD-10.1-RELEASE-amd64-memstick.img.xz) = 5f44ac7afa902d9258df191916e9e18190cb4321f04e17104caff56026653cc5 SHA256 (FreeBSD-10.1-RELEASE-amd64-mini-memstick.img) = 1be2270ddf487f3129b5fc21955d93cac82905ade4afa3039a87aa60b8236b78 SHA256 (FreeBSD-10.1-RELEASE-amd64-mini-memstick.img.xz) = 91d32e7d3ac31a3eef0217a64ef02eac2b5446bb1dcebb6fd3c94b7bbd28c1f7 SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-bootonly.iso) = 4aacf25cd0aec136da6345d01fa35650b9812b0260e0ce8f6845c4c8b4ca377d SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-bootonly.iso.xz) = cd2009d1935e57cb20e993cba013ebc21242878200640bac2332b633302b3c13 SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-disc1.iso) = a7f606b448683f975597269b3a69783f80e9bdc74230decf182c48abaac222d0 SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-disc1.iso.xz) = 25c07704003ab8ca0f4b4bc5ad4f7693b5dd402d29dcfd0549a8e0bd58e1c6e9 SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-dvd1.iso) = 70f039126e430b9f2cc051d38f648eb3c18215c72fe069a67838debe961f6e5e SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-dvd1.iso.xz) = 1ac32ee17120269427386dbd84f40c61ce1924536634136b84ce94da5c51b19d SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-memstick.img) = a1e4072f07bf7e62499f4a13dbe773f1f07c3f8a0071c05acf7b1924e5bec48f SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-memstick.img.xz) = ac5514085b4c4a8c8a6cda992cb9a0b479f4d1ca753cfa3afde45d5ba05b436c SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-mini-memstick.img) = 11b871cc6a20a6dcd69c16152c40242b2175f464495df0b545074535642c4fa9 SHA256 (FreeBSD-10.1-RELEASE-amd64-uefi-mini-memstick.img.xz) = 13b66fa82a91a1a4f1f1826536639f8cd5a41fe29bc5a0c62d2df0e8805cc55b .... .... MD5 (FreeBSD-10.1-RELEASE-amd64-bootonly.iso) = 7f761efc051e4f48551f1d47217fc964 MD5 (FreeBSD-10.1-RELEASE-amd64-bootonly.iso.xz) = 07cb631f4a62700abe39398a3849743d MD5 (FreeBSD-10.1-RELEASE-amd64-disc1.iso) = d0d4553080b88653569e1871d57fc819 MD5 (FreeBSD-10.1-RELEASE-amd64-disc1.iso.xz) = 10f0b54d23f523b4084187d5f2c8198f MD5 (FreeBSD-10.1-RELEASE-amd64-dvd1.iso) = 843e2ac204fcef35fea4950e546a016c MD5 (FreeBSD-10.1-RELEASE-amd64-dvd1.iso.xz) = f51c6d612e758de517a96cc2c608a5a4 MD5 (FreeBSD-10.1-RELEASE-amd64-memstick.img) = cc904b8f156931d1036c913ec80b192e MD5 (FreeBSD-10.1-RELEASE-amd64-memstick.img.xz) = 6b96f5d1f8b75580436ab799b241b4bb MD5 (FreeBSD-10.1-RELEASE-amd64-mini-memstick.img) = b5cda9ffdeea90d4ec3982529279ccd7 MD5 (FreeBSD-10.1-RELEASE-amd64-mini-memstick.img.xz) = 41272f0fde06735bb148504a721d82cf MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-bootonly.iso) = 6d9d98daa1a8395bc4c71939a9365fe2 MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-bootonly.iso.xz) = a38f0be1bbd91d076783c94542e78119 MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-disc1.iso) = 82fdb43c7b8a77a8119ac5aa7e0ca3fe MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-disc1.iso.xz) = 87e60815eee04e012e7129a4ce6881f5 MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-dvd1.iso) = 12a00b38d33d7af0f3833e78f1bcf8b1 MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-dvd1.iso.xz) = 8274be64a7a38f4ac6d88ff76d0c8a31 MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-memstick.img) = bde386862f0746ee3d12248d29ea4c8f MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-memstick.img.xz) = 1152e3163edd8b91ff0d186c1a246c64 MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-mini-memstick.img) = 45c5246064069d95617bff55d07a572b MD5 (FreeBSD-10.1-RELEASE-amd64-uefi-mini-memstick.img.xz) = 70da2a99275ce4828ebe8158f4e61491 .... === i386 (x86): .... SHA256 (FreeBSD-10.1-RELEASE-i386-bootonly.iso) = 215f11d0cd7a6af7be4129f70ba417af4f239ca2f922277b715a7098bdf8ca38 SHA256 (FreeBSD-10.1-RELEASE-i386-bootonly.iso.xz) = 9ea4681d340e9ea3b049d0e3d00601afa74d95dd6ab3fda73611b83d9f029f50 SHA256 (FreeBSD-10.1-RELEASE-i386-disc1.iso) = fe31790b762b01c99791d33e7fd9ab97323654785ce21f588116c8b4eb381cd0 SHA256 (FreeBSD-10.1-RELEASE-i386-disc1.iso.xz) = b765f92da152c00e3a82dceef61e00a0ccd87d004a81c51630a0907cd986ff4f SHA256 (FreeBSD-10.1-RELEASE-i386-dvd1.iso) = 838f02c547372e8b36b3dbd46169e3cf18464b64f0196e90efdbbeaa3cb49567 SHA256 (FreeBSD-10.1-RELEASE-i386-dvd1.iso.xz) = 231da3aa96ddb90c43aba523dba3d36e445d3b0e8e81c4d9ceaf32e75fd79a26 SHA256 (FreeBSD-10.1-RELEASE-i386-memstick.img) = 583dedeaa95ff76c4384e6589dc882b701a6a40ffdfd4ee2a80ef60092a7d319 SHA256 (FreeBSD-10.1-RELEASE-i386-memstick.img.xz) = 6b304451b026a93e6dc05724043d9ae4036bf8b670f8a3b275fe9983a96e58b8 SHA256 (FreeBSD-10.1-RELEASE-i386-mini-memstick.img) = 20e8692b047000e4e49af0973a0c48b68da198dc1d6ce6c1e0fd134a6d7c8ecd SHA256 (FreeBSD-10.1-RELEASE-i386-mini-memstick.img.xz) = e44e22fd6b8d69501dd5607337b7b2abf3304c1c7917d923e4a57c067ece607d .... .... MD5 (FreeBSD-10.1-RELEASE-i386-bootonly.iso) = 369c3dfc8d8bc6161f394953dbe92497 MD5 (FreeBSD-10.1-RELEASE-i386-bootonly.iso.xz) = 93781f084413d19aaeecb0911b458872 MD5 (FreeBSD-10.1-RELEASE-i386-disc1.iso) = 75c7c7ed926e4c01e015a6ea917532ed MD5 (FreeBSD-10.1-RELEASE-i386-disc1.iso.xz) = a3d223463f7461edfe333b0d6bc3416c MD5 (FreeBSD-10.1-RELEASE-i386-dvd1.iso) = 55c73545418628e84e3571cc5842b72d MD5 (FreeBSD-10.1-RELEASE-i386-dvd1.iso.xz) = 14e7a3fe085a74717957aa6ae28d4328 MD5 (FreeBSD-10.1-RELEASE-i386-memstick.img) = 20a8b7a731192f85ab40802ceb2b3927 MD5 (FreeBSD-10.1-RELEASE-i386-memstick.img.xz) = 659f8d731c1eeb766a8048fad1832629 MD5 (FreeBSD-10.1-RELEASE-i386-mini-memstick.img) = 7186991a4c4a7b040e75c1483c94d417 MD5 (FreeBSD-10.1-RELEASE-i386-mini-memstick.img.xz) = c193ff5de9fd91b556ca75f7cf65d316 .... === ia64: .... SHA256 (FreeBSD-10.1-RELEASE-ia64-bootonly.iso) = 79ebfa826a412c82c39da4a623e1bc09f846175044ff662b493a313ab8b6ef30 SHA256 (FreeBSD-10.1-RELEASE-ia64-bootonly.iso.xz) = 001fe3f0a7ee8a97c32b6988551ca24386fe893af388cc9ba604141aed84f0be SHA256 (FreeBSD-10.1-RELEASE-ia64-disc1.iso) = bf5f0d3950d9490522e802acdbce85f28544ccb536029cace73272223a4fc23d SHA256 (FreeBSD-10.1-RELEASE-ia64-disc1.iso.xz) = 5fbe58dd0b525bd71153db50d7e058ce479c5fb381668ae91c7219bfcb6b3197 SHA256 (FreeBSD-10.1-RELEASE-ia64-memstick.img) = e1e0b8d38dc661e913383e6ceea7b0e424de2219d2e96fbd5069de6a2fad3b29 SHA256 (FreeBSD-10.1-RELEASE-ia64-memstick.img.xz) = 3e68d2ae629814880b6591d6ca00ef5e8f4356dacb4694ed85e5f5d11b545c25 SHA256 (FreeBSD-10.1-RELEASE-ia64-mini-memstick.img) = 05d117e2b5858bba42842b9604efb9462fb2ee7ff58d4449bfd2de89472717ce SHA256 (FreeBSD-10.1-RELEASE-ia64-mini-memstick.img.xz) = de12e8ea731d6c61339f021bd845618642045eda2a2370231655479c1aa055a8 .... .... MD5 (FreeBSD-10.1-RELEASE-ia64-bootonly.iso) = 2f618152831fa9dfdcefd04c575e176a MD5 (FreeBSD-10.1-RELEASE-ia64-bootonly.iso.xz) = b6b0a1325e3ba3efbbb7441f9689835c MD5 (FreeBSD-10.1-RELEASE-ia64-disc1.iso) = 65a64d7c65c888af199038995f794b44 MD5 (FreeBSD-10.1-RELEASE-ia64-disc1.iso.xz) = 501d04715c918f047c9a7694990c68ea MD5 (FreeBSD-10.1-RELEASE-ia64-memstick.img) = e47a348749e33a26ef16847d358b68e3 MD5 (FreeBSD-10.1-RELEASE-ia64-memstick.img.xz) = 10aa6bc0f233f4bed0631faa934a8944 MD5 (FreeBSD-10.1-RELEASE-ia64-mini-memstick.img) = 7b969e5bcf96bc5657453e3ea6439a30 MD5 (FreeBSD-10.1-RELEASE-ia64-mini-memstick.img.xz) = 634ea43a056ee16c70513cd7a9df4274 .... === powerpc: .... SHA256 (FreeBSD-10.1-RELEASE-powerpc-bootonly.iso) = 4bfa59ccbe3503c82ae9a53f3e4f1b9984aa9d1a2c3f62a9554e7b2e7e5f7d5d SHA256 (FreeBSD-10.1-RELEASE-powerpc-bootonly.iso.xz) = ee15a3a8bcbcb8b74253c8b2098b88df9ab47e6916b6c7a879166ff99e919d73 SHA256 (FreeBSD-10.1-RELEASE-powerpc-disc1.iso) = e28732f2023c839ec4157d01efe65e773a267ea195b451fac0c2ca0222b094c6 SHA256 (FreeBSD-10.1-RELEASE-powerpc-disc1.iso.xz) = 875e7492eb78cb105e6aa421fe14290640627a8dfacdee26a5c1ecd1daa9dec2 SHA256 (FreeBSD-10.1-RELEASE-powerpc-memstick.img) = f011296938b30cc3c8f243a6efa1af0337c92a76b71b3e7788772464b93099d0 SHA256 (FreeBSD-10.1-RELEASE-powerpc-memstick.img.xz) = 2eca4233521a9928222289acfc2e035be8868bd269ebd8b9c72fb4faf2fc32f8 SHA256 (FreeBSD-10.1-RELEASE-powerpc-mini-memstick.img) = e32fdefb9db57699cdc8db6ab6dec9d0100a39dabbc22566710f6defffc2cb49 SHA256 (FreeBSD-10.1-RELEASE-powerpc-mini-memstick.img.xz) = 223657c10c76647431c6baab905bc0f49f77262946c77b8856503a378b2533d8 .... .... MD5 (FreeBSD-10.1-RELEASE-powerpc-bootonly.iso) = 8a96adf66bbe1f78c11315ffb87a9418 MD5 (FreeBSD-10.1-RELEASE-powerpc-bootonly.iso.xz) = 0733497177c62f853019ebfe8addc03a MD5 (FreeBSD-10.1-RELEASE-powerpc-disc1.iso) = 00e4236a40ebdd816f821024e9b2ff3f MD5 (FreeBSD-10.1-RELEASE-powerpc-disc1.iso.xz) = 55820da1566f41e551ad81c4772d3b66 MD5 (FreeBSD-10.1-RELEASE-powerpc-memstick.img) = f0d791af2926c39294597382d2b2347b MD5 (FreeBSD-10.1-RELEASE-powerpc-memstick.img.xz) = 443dde38177f9ea832f7b6fb39413821 MD5 (FreeBSD-10.1-RELEASE-powerpc-mini-memstick.img) = ceb1747602f47230f6f5ce547f542802 MD5 (FreeBSD-10.1-RELEASE-powerpc-mini-memstick.img.xz) = a312731e45fb2215390bf3ad456a465f .... === powerpc64: .... SHA256 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-bootonly.iso) = 9019c06aa9adc07c1869e2bed9c17a2efd7506e58757dba829df966562d6734f SHA256 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-bootonly.iso.xz) = a187a73bfbe4d8a5f8367ef81e1bc12b75ecce765d00a86106b34e0a61b17762 SHA256 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-disc1.iso) = b3177b929feee1b1b7e1a11e9de1e853530c5463365e7a8e1c0e8f0b8060a711 SHA256 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-disc1.iso.xz) = 1653cf593867ae097085f26619e47b483621faf9d5e118531f919083a0ac191a SHA256 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-memstick.img) = 76b7f8d1db4f52a1220f8c0aae03953adce20729b18711e0810ca4400a42f00d SHA256 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-memstick.img.xz) = dc6c6344d226c35ea4bdd299582d66cb2c173eb02d9efc5ea827d5dc9c1f6a46 SHA256 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-mini-memstick.img) = 3f491270faf03c130ef8a36355c0f3e43d3edbc2b1961172ab286dd0f5326b79 SHA256 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-mini-memstick.img.xz) = 05f4af0621ab829ffc49414951efd6410033f04c1f82cfa3348a0589874e5839 .... .... MD5 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-bootonly.iso) = 46edbf7e8206d6790fc0338b157186c6 MD5 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-bootonly.iso.xz) = b2e1b21ed727e1e4897b14fc86ecdd3c MD5 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-disc1.iso) = 36bc31330c9bb9ddb2f33a740a34b7e3 MD5 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-disc1.iso.xz) = 7596f5a3806bd9c576e912162cd26c49 MD5 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-memstick.img) = dfd219d603897dea212fed589fab0bb7 MD5 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-memstick.img.xz) = 6c29dbe6a50685ac7fa6195989e17a79 MD5 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-mini-memstick.img) = b33e0a4d07a87167a0e761841033169d MD5 (FreeBSD-10.1-RELEASE-powerpc-powerpc64-mini-memstick.img.xz) = 1d383970297837af1686af41fc0ed3d6 .... === sparc64: .... SHA256 (FreeBSD-10.1-RELEASE-sparc64-bootonly.iso) = 1d16052206ddbf934b9335b1f6ac37eebd202d6103690d29b2871cfce24e09b9 SHA256 (FreeBSD-10.1-RELEASE-sparc64-bootonly.iso.xz) = 2eceee7d1169a540953c39f8fff316b488fac9ffdbc7c708a701fc1235d36383 SHA256 (FreeBSD-10.1-RELEASE-sparc64-disc1.iso) = 09fd3898f126446ccd7ab84c1893a0451fe13172cf4e95b0a139f87063d17965 SHA256 (FreeBSD-10.1-RELEASE-sparc64-disc1.iso.xz) = 3b1c060c444e9bb9b8e4dc3e6a7947c74fd4ec7b89f71a1e5cd031109adac613 .... .... MD5 (FreeBSD-10.1-RELEASE-sparc64-bootonly.iso) = ec1487a3b45fbd67516df508354ca7e6 MD5 (FreeBSD-10.1-RELEASE-sparc64-bootonly.iso.xz) = 3cadc6891b453842f110051dd65a0deb MD5 (FreeBSD-10.1-RELEASE-sparc64-disc1.iso) = 29e14724de8706d6035619e90d1fd275 MD5 (FreeBSD-10.1-RELEASE-sparc64-disc1.iso.xz) = b82a65dfd166e749a343d7c5c7fbe534 .... === armv6 (BEAGLEBONE): .... SHA256 (FreeBSD-10.1-RELEASE-arm-armv6-BEAGLEBONE.img.bz2) = 20427b94faee5400acdafd26fa59be284323f3ebef463fdae07102036bafa5c2 .... .... MD5 (FreeBSD-10.1-RELEASE-arm-armv6-BEAGLEBONE.img.bz2) = 92763ed74756af81205577220f655fb7 .... === armv6 (RPI-B): .... SHA256 (FreeBSD-10.1-RELEASE-arm-armv6-RPI-B.img.bz2) = 3afd6fb5f9d4bf52c03c3ce26ebef658505a86979c2f7bdedca726b79509c68f .... .... MD5 (FreeBSD-10.1-RELEASE-arm-armv6-RPI-B.img.bz2) = a9f4130b305a368ec2ceaf1a45e3de31 .... === armv6 (PANDABOARD): .... SHA256 (FreeBSD-10.1-RELEASE-arm-armv6-PANDABOARD.img.bz2) = 095d850318c5edb3a89a54313fcfc97b56e9b28e512a46bc3a6c2c47168d0c34 .... .... MD5 (FreeBSD-10.1-RELEASE-arm-armv6-PANDABOARD.img.bz2) = c7f98f10436fbfe53a77d1718113a869 .... === armv6 (ZEDBOARD): .... SHA256 (FreeBSD-10.1-RELEASE-arm-armv6-ZEDBOARD.img.bz2) = 664a0da6eb7a97b426510e6b894673604156046c99c2056fa50aaff8fd5c2838 .... .... MD5 (FreeBSD-10.1-RELEASE-arm-armv6-ZEDBOARD.img.bz2) = 1d7046a8eac902b4aaadec2eb80f4739 .... == Virtual Machine Disk Image Checksums === amd64 (x86_64): .... SHA256 (FreeBSD-10.1-RELEASE-amd64.qcow2.xz) = cd7cd17083fc27e61303a4fe958ef7c5d76ff4a5a4dc4e8140f9fcbbe79318aa SHA256 (FreeBSD-10.1-RELEASE-amd64.raw.xz) = 417dcffa96f011f241d0411c8131ff770055182cd5bfac13a14cf5598f7d1fc9 SHA256 (FreeBSD-10.1-RELEASE-amd64.vhd.xz) = dee50dc8fb4b3fade150bd1c83044752cb924c90f7c956ff028fe96cbb249d89 SHA256 (FreeBSD-10.1-RELEASE-amd64.vmdk.xz) = 62365d4c5cb4c0d2166aa17d3055bd1eb11031197cf0f4a941e82c7052d5bd1a .... .... MD5 (FreeBSD-10.1-RELEASE-amd64.qcow2.xz) = 4ccd43ada573bfe59ae5f55e90625573 MD5 (FreeBSD-10.1-RELEASE-amd64.raw.xz) = b82d3d653acc2d1793576e12373fc2bc MD5 (FreeBSD-10.1-RELEASE-amd64.vhd.xz) = 4134062704525d377cc9ed9480830723 MD5 (FreeBSD-10.1-RELEASE-amd64.vmdk.xz) = fd35600f0ed161380f1188f575c5a26a .... === i386 (x86): .... SHA256 (FreeBSD-10.1-RELEASE-i386.qcow2.xz) = 7d41f71f33745edc5c89a97cdc242f5ead847a297b77f2e1c9f5d61519928995 SHA256 (FreeBSD-10.1-RELEASE-i386.raw.xz) = 3391847d935efc885268d398031595ad097eb20dd23ceba0a04d4a975e33d941 SHA256 (FreeBSD-10.1-RELEASE-i386.vhd.xz) = f655fa0b1f3527414770f89dcff7b64bc79ad5269c1a23bc33ca4abea3ab8f7c SHA256 (FreeBSD-10.1-RELEASE-i386.vmdk.xz) = f18217857d59db0b73962d6b28666c40def1cb7d069b3ce657859486755c0422 .... .... MD5 (FreeBSD-10.1-RELEASE-i386.qcow2.xz) = a0de99d75c5004aae54e32d60485bd05 MD5 (FreeBSD-10.1-RELEASE-i386.raw.xz) = 430af5f70e24652067ad21345651e3ef MD5 (FreeBSD-10.1-RELEASE-i386.vhd.xz) = eac51224bfcf81bd14c55266b84d39e1 MD5 (FreeBSD-10.1-RELEASE-i386.vmdk.xz) = 8bc11dadbdb10988d40b583a9167f4c7 .... Love FreeBSD? Support this and future releases with a https://www.freebsdfoundation.org/donate/[donation] to The FreeBSD Foundation! ",12106,True,3619.308801601961,median "[[scoreCalculation]] = Score calculation :doctype: book :sectnums: :icons: font [[scoreTerminology]] == Score terminology [[whatIsAScore]] === What is a score? Every `@PlanningSolution` class has a score. The score is an objective way to compare two solutions. The solution with the higher score is better. The `Solver` aims to find the solution with the highest `Score` of all possible solutions. The _best solution_ is the solution with the highest `Score` that `Solver` has encountered during solving, which might be the __optimal solution__. OptaPlanner cannot automatically know which solution is best for your business, so you need to tell it how to calculate the score of a given `@PlanningSolution` instance according to your business needs. If you forget or are unable to implement an important business constraint, the solution is probably useless: image::score-calculation/optimalWithIncompleteConstraints.png[align=""center""] [[formalizeTheBusinessConstraints]] === Formalize the business constraints To implement a verbal business constraint, it needs to be formalized as a score constraint. Luckily, defining constraints in OptaPlanner is very flexible through the following score techniques: * **Score signum (positive or negative)**: maximize or minimize a constraint type * **Score weight**: put a cost/profit on a constraint type * **Score level (hard, soft, ...)**: prioritize a group of constraint types * *Pareto scoring* (rarely used) Take the time to acquaint yourself with the first three techniques. Once you understand them, formalizing most business constraints becomes straightforward. [NOTE] ==== Do not presume that your business knows all its score constraints in advance. Expect score constraints to be added, changed or removed after the first releases. ==== [[scoreConstraintSignum]] === Score constraint signum (positive or negative) All score techniques are based on constraints. A constraint can be a simple pattern (such as __Maximize the apple harvest in the solution__) or a more complex pattern. A positive constraint is a constraint you want to maximize. A negative constraint is a constraint you want to minimize image::score-calculation/positiveAndNegativeConstraints.png[align=""center""] The image above illustrates that **the optimal solution always has the highest score**, regardless if the constraints are positive or negative. Most planning problems have only negative constraints and therefore have a negative score. In that case, the score is the sum of the weight of the negative constraints being broken, with a perfect score of 0. For example in n queens, the score is the negative of the number of queen pairs which can attack each other. Negative and positive constraints can be combined, even in the same score level. When a constraint activates (because the negative constraint is broken or the positive constraint is fulfilled) on a certain planning entity set, it is called a __constraint match__. [[scoreConstraintWeight]] === Score constraint weight Not all score constraints are equally important. If breaking one constraint is equally bad as breaking another constraint x times, then those two constraints have a different weight (but they are in the same score level). For example in vehicle routing, you can make one _unhappy driver_ constraint match count as much as two _fuel tank usage_ constraint matches: image::score-calculation/scoreWeighting.png[align=""center""] Score weighting is easy in use cases where you can __put a price tag on everything__. In that case, the positive constraints maximize revenue and the negative constraints minimize expenses, so together they maximize profit. Alternatively, score weighting is also often used to create social <>. For example, a nurse, who requests a free day, pays a higher weight on New Years eve than on a normal day. The weight of a constraint match can depend on the planning entities involved. For example in cloud balancing, the weight of the soft constraint match for an active `Computer` is the maintenance `cost` of that `Computer` (which differs per computer). Putting a good weight on a constraint is often a difficult analytical decision, because it is about making choices and trade-offs against other constraints. Different stakeholders have different priorities. *Don't waste time with constraint weight discussions at the start of an implementation, instead add a <> and allow users to change them through a UI.* A non-accurate weight is less damaging than mediocre algorithms: image::score-calculation/scoreTradeoffInPerspective.png[align=""center""] Most use cases use a `Score` with `int` weights, such as <>. [[scoreLevel]] === Score constraint level (hard, soft, ...) Sometimes a score constraint outranks another score constraint, no matter how many times the latter is broken. In that case, those score constraints are in different levels. For example, a nurse cannot do two shifts at the same time (due to the constraints of physical reality), so this outranks all nurse happiness constraints. Most use cases have only two score levels, hard and soft. The levels of two scores are compared lexicographically. The first score level gets compared first. If those differ, the remaining score levels are ignored. For example, a score that breaks `0` hard constraints and `1000000` soft constraints is better than a score that breaks `1` hard constraint and `0` soft constraints. image::score-calculation/scoreLevels.png[align=""center""] If there are two (or more) score levels, for example <>, then a score is _feasible_ if no hard constraints are broken. [NOTE] ==== By default, OptaPlanner will always assign all planning variables a planning value. If there is no feasible solution, this means the best solution will be infeasible. To instead leave some of the planning entities unassigned, apply xref:repeated-planning/repeated-planning.adoc#overconstrainedPlanning[overconstrained planning]. ==== For each constraint, you need to pick a score level, a score weight and a score signum. For example: `-1soft` which has score level of ``soft``, a weight of `1` and a negative signum. Do not use a big constraint weight when your business actually wants different score levels. That hack, known as __score folding__, is broken: image::score-calculation/scoreFoldingIsBroken.png[align=""center""] [NOTE] ==== Your business might tell you that your hard constraints all have the same weight, because they cannot be broken (so the weight does not matter). This is not true because if no feasible solution exists for a specific dataset, the least infeasible solution allows the business to estimate how many business resources they are lacking. For example in cloud balancing, how many new computers to buy. Furthermore, it will likely create a <>. For example in cloud balance if a `Computer` has seven CPU too little for its ``Process``es, then it must be weighted seven times as much as if it had only one CPU too little. ==== Three or more score levels are also supported. For example: a company might decide that profit outranks employee satisfaction (or vice versa), while both are outranked by the constraints of physical reality. [NOTE] ==== To model <>, there is no need to use lots of score levels (even though OptaPlanner can handle many score levels). ==== Most use cases use a `Score` with two or three weights, such as <> and <>. [[paretoScoring]] === Pareto scoring (AKA multi-objective optimization scoring) Far less common is the use case of pareto optimization, which is also known as _multi-objective optimization_. In pareto scoring, score constraints are in the same score level, yet they are not weighted against each other. When two scores are compared, each of the score constraints are compared individually and the score with the most dominating score constraints wins. Pareto scoring can even be combined with score levels and score constraint weighting. Consider this example with positive constraints, where we want to get the most apples and oranges. Since it is impossible to compare apples and oranges, we cannot weigh them against each other. Yet, despite that we cannot compare them, we can state that two apples are better than one apple. Similarly, we can state that two apples and one orange are better than just one orange. So despite our inability to compare some Scores conclusively (at which point we declare them equal), we can find a set of optimal scores. Those are called pareto optimal. image::score-calculation/paretoOptimizationScoring.png[align=""center""] Scores are considered equal far more often. It is left up to a human to choose the better out of a set of best solutions (with equal scores) found by OptaPlanner. In the example above, the user must choose between solution A (three apples and one orange) and solution B (one apple and six oranges). It is guaranteed that OptaPlanner has not found another solution which has more apples or more oranges or even a better combination of both (such as two apples and three oranges). To implement pareto scoring in OptaPlanner, <> (and replace the ``BestSolutionRecaller``). Future versions will provide out-of-the-box support. [NOTE] ==== A pareto ``Score``'s `compareTo` method is not transitive because it does a pareto comparison. For example: having two apples is greater than one apple. One apple is equal to One orange. Yet, two apples are not greater than one orange (but actually equal). Pareto comparison violates the contract of the interface ``java.lang.Comparable``'s `compareTo` method, but Planners systems are __pareto comparison safe__, unless explicitly stated otherwise in this documentation. ==== [[combiningScoreTechniques]] === Combining score techniques All the score techniques mentioned above, can be combined seamlessly: image::score-calculation/scoreComposition.png[align=""center""] [[scoreInterface]] === `Score` interface A score is represented by the `Score` interface, which naturally extends ``Comparable``: [source,java,options=""nowrap""] ---- public interface Score<...> extends Comparable<...> { ... } ---- The `Score` implementation to use depends on your use case. Your score might not efficiently fit in a single `long` value. OptaPlanner has several built-in `Score` implementations, but you can implement a custom `Score` too. Most use cases tend to use the built-in ``HardSoftScore``. image::score-calculation/scoreClassDiagram.png[align=""center""] All Score implementations also have an `initScore` (which is an ``int``).It is mostly intended for internal use in OptaPlanner: it is the negative number of uninitialized planning variables. From a user's perspective this is ``0``, unless a Construction Heuristic is terminated before it could initialize all planning variables (in which case `Score.isSolutionInitialized()` returns ``false``). The `Score` implementation (for example ``HardSoftScore``) must be the same throughout a `Solver` runtime. The `Score` implementation is configured in the solution domain class: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... @PlanningScore private HardSoftScore score; } ---- [[avoidFloatingPointNumbersInScoreCalculation]] === Avoid floating point numbers in score calculation Avoid the use of `float` or `double` in score calculation. Use `BigDecimal` or scaled `long` instead. Floating point numbers (``float`` and ``double``) cannot represent a decimal number correctly. For example: a `double` cannot hold the value `0.05` correctly. Instead, it holds the nearest representable value. Arithmetic (including addition and subtraction) with floating point numbers, especially for planning problems, leads to incorrect decisions: image::score-calculation/scoreWeightType.png[align=""center""] Additionally, floating point number addition is not associative: [source,java,options=""nowrap""] ---- System.out.println( ((0.01 + 0.02) + 0.03) == (0.01 + (0.02 + 0.03)) ); // returns false ---- This leads to __score corruption__. Decimal numbers (``BigDecimal``) have none of these problems. [NOTE] ==== BigDecimal arithmetic is considerably slower than ``int``, `long` or `double` arithmetic. In experiments we have seen the score calculation take five times longer. Therefore, in many cases, it can be worthwhile to multiply _all_ numbers for a single score weight by a plural of ten, so the score weight fits in a scaled `int` or ``long``. For example, if we multiply all weights by ``1000``, a fuelCost of `0.07` becomes a fuelCostMillis of `70` and no longer uses a decimal score weight. ==== [[scoreType]] == Choose a score type Depending on the number of score levels and type of score weights you need, choose a `Score` type. Most use cases use a ``HardSoftScore``. [NOTE] ==== To properly write a `Score` to a database (with JPA/Hibernate) or to XML/JSON (with XStream/JAXB/Jackson), see xref:integration/integration.adoc#integration[the integration chapter]. ==== [[simpleScore]] === `SimpleScore` A `SimpleScore` has a single `int` value, for example ``-123``. It has a single score level. [source,java,options=""nowrap""] ---- @PlanningScore private SimpleScore score; ---- Variants of this `Score` type: * `SimpleLongScore` uses a `long` value instead of an `int` value. * `SimpleBigDecimalScore` uses a `BigDecimal` value instead of an `int` value. [[hardSoftScore]] === `HardSoftScore` (Recommended) A `HardSoftScore` has a hard `int` value and a soft `int` value, for example ``-123hard/-456soft``. It has two score levels (hard and soft). [source,java,options=""nowrap""] ---- @PlanningScore private HardSoftScore score; ---- Variants of this `Score` type: * `HardSoftLongScore` uses `long` values instead of `int` values. * `HardSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[hardMediumSoftScore]] === `HardMediumSoftScore` A `HardMediumSoftScore` which has a hard `int` value, a medium `int` value and a soft `int` value, for example ``-123hard/-456medium/-789soft``. It has three score levels (hard, medium and soft). The hard level determines if the solution is feasible, and the medium level and soft level score values determine how well the solution meets business goals. Higher medium values take precedence over soft values irrespective of the soft value. [source,java,options=""nowrap""] ---- @PlanningScore private HardMediumSoftScore score; ---- Variants of this `Score` type: * `HardMediumSoftLongScore` uses `long` values instead of `int` values. * `HardMediumSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[bendableScore]] === `BendableScore` A `BendableScore` has a configurable number of score levels. It has an array of hard `int` values and an array of soft `int` values, for example with two hard levels and three soft levels, the score can be ``[-123/-456]hard/[-789/-012/-345]soft``. In that case, it has five score levels. A solution is feasible if all hard levels are at least zero. A BendableScore with one hard level and one soft level is equivalent to a HardSoftScore, while a BendableScore with one hard level and two soft levels is equivalent to a HardMediumSoftScore. [source,java,options=""nowrap""] ---- @PlanningScore(bendableHardLevelsSize = 2, bendableSoftLevelsSize = 3) private BendableScore score; ---- The number of hard and soft score levels need to be set at compilation time. It is not flexible to change during solving. [NOTE] ==== Do not use a `BendableScore` with seven levels just because you have seven constraints. It is extremely rare to use a different score level for each constraint, because that means one constraint match on soft 0 outweighs even a million constraint matches of soft 1. Usually, multiple constraints share the same level and are weighted against each other. Use <> to get the weight of individual constraints in the same level. ==== Variants of this `Score` type: * `BendableLongScore` uses `long` values instead of `int` values. * `BendableBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[customScore]] === Implementing a custom score Internally, each `Score` implementation also has a `ScoreDefinition` implementation. For example: `SimpleScore` is defined by ``SimpleScoreDefinition``. The `ScoreDefinition` interface defines the score representation. To implement a custom ``Score``, also implement such a custom ``ScoreDefinition``. Extend `AbstractScoreDefinition` (preferably by copy pasting ``HardSoftScoreDefinition``) and start from there. Then hook your custom `ScoreDefinition` in the domain: [source,java,options=""nowrap""] ---- @PlanningScore(scoreDefinitionClass = MyCustomScoreDefinition.class) private MyCustomScore score; ---- To have it integrate seamlessly with xref:integration/integration.adoc#jpaAndHibernatePersistingAScore[JPA/Hibernate], xref:integration/integration.adoc#integrationWithXStream[XStream], xref:integration/integration.adoc#integrationWithJackson[Jackson], ..., you'll need to write custom glue code too. [[calculateTheScore]] == Calculate the `Score` [[scoreCalculationTypes]] === Score calculation types There are several ways to calculate the `Score` of a solution: * **<>**: Implement all constraints together in a single method in Java (or another JVM language). Does not scale. * **xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams score calculation]**: Implement each constraint as a separate Constraint Stream in Java (or another JVM language). Fast and scalable. * **<>** (not recommended): Implement multiple low-level methods in Java (or another JVM language). Fast and scalable. Very difficult to implement and maintain. * **xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation]**: Implement each constraint as a separate score rule in DRL. Scalable. Every score calculation type can work with any Score definition (such as ``HardSoftScore`` or ``HardMediumSoftScore``). All score calculation types are Object Oriented and can reuse existing Java code. [IMPORTANT] ==== The score calculation must be read-only. It must not change the planning entities or the problem facts in any way. For example, it must not call a setter method on a planning entity in the score calculation. OptaPlanner does not recalculate the score of a solution if it can predict it (unless an xref:planner-configuration/planner-configuration.adoc#environmentMode[environmentMode assertion] is enabled). For example, after a winning step is done, there is no need to calculate the score because that move was done and undone earlier. As a result, there is no guarantee that changes applied during score calculation actually happen. To update planning entities when the planning variable change, use xref:shadow-variable/shadow-variable.adoc#shadowVariable[shadow variables] instead. ==== [[easyJavaScoreCalculation]] === Easy Java score calculation An easy way to implement your score calculation in Java. * Advantages: ** Plain old Java: no learning curve ** Opportunity to delegate score calculation to an existing code base or legacy system * Disadvantages: ** Slower ** Does not scale because there is no <> Implement the one method of the interface ``EasyScoreCalculator``: [source,java,options=""nowrap""] ---- public interface EasyScoreCalculator> { Score_ calculateScore(Solution_ solution); } ---- For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensEasyScoreCalculator implements EasyScoreCalculator { @Override public SimpleScore calculateScore(NQueens nQueens) { int n = nQueens.getN(); List queenList = nQueens.getQueenList(); int score = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { Queen leftQueen = queenList.get(i); Queen rightQueen = queenList.get(j); if (leftQueen.getRow() != null && rightQueen.getRow() != null) { if (leftQueen.getRowIndex() == rightQueen.getRowIndex()) { score--; } if (leftQueen.getAscendingDiagonalIndex() == rightQueen.getAscendingDiagonalIndex()) { score--; } if (leftQueen.getDescendingDiagonalIndex() == rightQueen.getDescendingDiagonalIndex()) { score--; } } } } return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- To configure values of an `EasyScoreCalculator` dynamically in the solver configuration (so the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] can tweak those parameters), add the `easyScoreCalculatorCustomProperties` element and use xref:planner-configuration/planner-configuration.adoc#customPropertiesConfiguration[custom properties]: [source,xml,options=""nowrap""] ---- ...MyEasyScoreCalculator ---- [[incrementalJavaScoreCalculation]] === Incremental Java score calculation A way to implement your score calculation incrementally in Java. * Advantages: ** Very fast and scalable *** Currently the fastest if implemented correctly * Disadvantages: ** Hard to write *** A scalable implementation heavily uses maps, indexes, ... (things the Drools rule engine can do for you) *** You have to learn, design, write and improve all these performance optimizations yourself ** Hard to read *** Regular score constraint changes can lead to a high maintenance cost Implement all the methods of the interface `IncrementalScoreCalculator`: [source,java,options=""nowrap""] ---- public interface IncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution); void beforeEntityAdded(Object entity); void afterEntityAdded(Object entity); void beforeVariableChanged(Object entity, String variableName); void afterVariableChanged(Object entity, String variableName); void beforeEntityRemoved(Object entity); void afterEntityRemoved(Object entity); Score_ calculateScore(); } ---- image::score-calculation/incrementalScoreCalculatorSequenceDiagram.png[align=""center""] For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensAdvancedIncrementalScoreCalculator extends IncrementalScoreCalculator { private Map> rowIndexMap; private Map> ascendingDiagonalIndexMap; private Map> descendingDiagonalIndexMap; private int score; public void resetWorkingSolution(NQueens nQueens) { int n = nQueens.getN(); rowIndexMap = new HashMap>(n); ascendingDiagonalIndexMap = new HashMap>(n * 2); descendingDiagonalIndexMap = new HashMap>(n * 2); for (int i = 0; i < n; i++) { rowIndexMap.put(i, new ArrayList(n)); ascendingDiagonalIndexMap.put(i, new ArrayList(n)); descendingDiagonalIndexMap.put(i, new ArrayList(n)); if (i != 0) { ascendingDiagonalIndexMap.put(n - 1 + i, new ArrayList(n)); descendingDiagonalIndexMap.put((-i), new ArrayList(n)); } } score = 0; for (Queen queen : nQueens.getQueenList()) { insert(queen); } } public void beforeEntityAdded(Object entity) { // Do nothing } public void afterEntityAdded(Object entity) { insert((Queen) entity); } public void beforeVariableChanged(Object entity, String variableName) { retract((Queen) entity); } public void afterVariableChanged(Object entity, String variableName) { insert((Queen) entity); } public void beforeEntityRemoved(Object entity) { retract((Queen) entity); } public void afterEntityRemoved(Object entity) { // Do nothing } private void insert(Queen queen) { Row row = queen.getRow(); if (row != null) { int rowIndex = queen.getRowIndex(); List rowIndexList = rowIndexMap.get(rowIndex); score -= rowIndexList.size(); rowIndexList.add(queen); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); score -= ascendingDiagonalIndexList.size(); ascendingDiagonalIndexList.add(queen); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); score -= descendingDiagonalIndexList.size(); descendingDiagonalIndexList.add(queen); } } private void retract(Queen queen) { Row row = queen.getRow(); if (row != null) { List rowIndexList = rowIndexMap.get(queen.getRowIndex()); rowIndexList.remove(queen); score += rowIndexList.size(); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); ascendingDiagonalIndexList.remove(queen); score += ascendingDiagonalIndexList.size(); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); descendingDiagonalIndexList.remove(queen); score += descendingDiagonalIndexList.size(); } } public SimpleScore calculateScore() { return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensAdvancedIncrementalScoreCalculator ---- [IMPORTANT] ==== A piece of incremental score calculator code can be difficult to write and to review. <> by using an ``EasyScoreCalculator`` to fulfill the assertions triggered by the ``environmentMode``. ==== To configure values of an `IncrementalScoreCalculator` dynamically in the solver configuration (so the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] can tweak those parameters), add the `incrementalScoreCalculatorCustomProperties` element and use xref:planner-configuration/planner-configuration.adoc#customPropertiesConfiguration[custom properties]: [source,xml,options=""nowrap""] ---- ...MyIncrementalScoreCalculator ---- [[constraintMatchAwareIncrementalScoreCalculator]] ==== `ConstraintMatchAwareIncrementalScoreCalculator` Optionally, also implement the `ConstraintMatchAwareIncrementalScoreCalculator` interface to: * Explain a score by splitting it up per score constraint with `ScoreExplanation.getConstraintMatchTotalMap()`. * Visualize or sort planning entities by how many constraints each one breaks with `ScoreExplanation.getIndictmentMap()`. * Receive a detailed analysis if the `IncrementalScoreCalculator` is corrupted in `FAST_ASSERT` or `FULL_ASSERT` `environmentMode`, [source,java,options=""nowrap""] ---- public interface ConstraintMatchAwareIncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution, boolean constraintMatchEnabled); Collection> getConstraintMatchTotals(); Map> getIndictmentMap(); } ---- For example in machine reassignment, create one `ConstraintMatchTotal` per constraint type and call `addConstraintMatch()` for each constraint match: [source,java,options=""nowrap""] ---- public class MachineReassignmentIncrementalScoreCalculator implements ConstraintMatchAwareIncrementalScoreCalculator { ... @Override public void resetWorkingSolution(MachineReassignment workingSolution, boolean constraintMatchEnabled) { resetWorkingSolution(workingSolution); // ignore constraintMatchEnabled, it is always presumed enabled } @Override public Collection> getConstraintMatchTotals() { ConstraintMatchTotal maximumCapacityMatchTotal = new DefaultConstraintMatchTotal<>(CONSTRAINT_PACKAGE, ""maximumCapacity"", HardSoftLongScore.ZERO); ... for (MrMachineScorePart machineScorePart : machineScorePartMap.values()) { for (MrMachineCapacityScorePart machineCapacityScorePart : machineScorePart.machineCapacityScorePartList) { if (machineCapacityScorePart.maximumAvailable < 0L) { maximumCapacityMatchTotal.addConstraintMatch( Arrays.asList(machineCapacityScorePart.machineCapacity), HardSoftLongScore.valueOf(machineCapacityScorePart.maximumAvailable, 0)); } } } ... List> constraintMatchTotalList = new ArrayList<>(4); constraintMatchTotalList.add(maximumCapacityMatchTotal); ... return constraintMatchTotalList; } @Override public Map> getIndictmentMap() { return null; // Calculate it non-incrementally from getConstraintMatchTotals() } } ---- That `getConstraintMatchTotals()` code often duplicates some of the logic of the normal `IncrementalScoreCalculator` methods. Constraint Streams and Drools Score Calculation don't have this disadvantage, because they are constraint match aware automatically when needed, without any extra domain-specific code. [[initializingScoreTrend]] === `InitializingScoreTrend` The `InitializingScoreTrend` specifies how the Score will change as more and more variables are initialized (while the already initialized variables do not change). Some optimization algorithms (such Construction Heuristics and Exhaustive Search) run faster if they have such information. For the Score (or each <> separately), specify a trend: * `ANY` (default): Initializing an extra variable can change the score positively or negatively. Gives no performance gain. * `ONLY_UP` (rare): Initializing an extra variable can only change the score positively. Implies that: ** There are only positive constraints ** And initializing the next variable cannot unmatch a positive constraint that was matched by a previous initialized variable. * ``ONLY_DOWN``: Initializing an extra variable can only change the score negatively. Implies that: ** There are only negative constraints ** And initializing the next variable cannot unmatch a negative constraint that was matched by a previous initialized variable. Most use cases only have negative constraints. Many of those have an `InitializingScoreTrend` that only goes down: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN ---- Alternatively, you can also specify the trend for each score level separately: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN/ONLY_DOWN ---- [[invalidScoreDetection]] === Invalid score detection When you put the xref:planner-configuration/planner-configuration.adoc#environmentMode[`environmentMode`] in `FULL_ASSERT` (or ``FAST_ASSERT``), it will detect score corruption in the <>. However, that will not verify that your score calculator actually implements your score constraints as your business desires. For example, one constraint might consistently match the wrong pattern. To verify the constraints against an independent implementation, configure a ``assertionScoreDirectorFactory``: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... org.optaplanner.examples.nqueens.optional.score.NQueensConstraintProviderorg.optaplanner.examples.nqueens.optional.score.NQueensConstraintProvider org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- This way, the `NQueensConstraintProvider` implementation is validated by the ``EasyScoreCalculator``. [NOTE] ==== This works well to isolate score corruption, but to verify that the constraint implement the real business needs, xref:constraint-streams/constraint-streams.adoc#constraintStreamsTesting[a unit test with a ConstraintVerifier] is usually better. ==== [[scoreCalculationPerformanceTricks]] == Score calculation performance tricks [[scoreCalculationPerformanceTricksOverview]] === Overview The `Solver` will normally spend most of its execution time running the score calculation (which is called in its deepest loops). Faster score calculation will return the same solution in less time with the same algorithm, which normally means a better solution in equal time. [[scoreCalculationSpeed]] === Score calculation speed After solving a problem, the `Solver` will log the __score calculation speed per second__. This is a good measurement of Score calculation performance, despite that it is affected by non score calculation execution time. It depends on the problem scale of the problem dataset. Normally, even for high scale problems, it is higher than ``1000``, except if you are using an ``EasyScoreCalculator``. [IMPORTANT] ==== When improving your score calculation, focus on maximizing the score calculation speed, instead of maximizing the best score. A big improvement in score calculation can sometimes yield little or no best score improvement, for example when the algorithm is stuck in a local or global optima. If you are watching the calculation speed instead, score calculation improvements are far more visible. Furthermore, watching the calculation speed allows you to remove or add score constraints, and still compare it with the original's calculation speed. Comparing the best score with the original's best score is pointless: it's comparing apples and oranges. ==== [[incrementalScoreCalculation]] === Incremental score calculation (with deltas) When a solution changes, incremental score calculation (AKA delta based score calculation) calculates the delta with the previous state to find the new ``Score``, instead of recalculating the entire score on every solution evaluation. For example, when a single queen A moves from row `1` to ``2``, it will not bother to check if queen B and C can attack each other, since neither of them changed: image::score-calculation/incrementalScoreCalculationNQueens04.png[align=""center""] Similarly in employee rostering: image::score-calculation/incrementalScoreCalculationEmployeeRostering.png[align=""center""] This is a huge performance and scalability gain. *xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint Streams] or xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] give you this huge scalability gain without forcing you to write a complicated incremental score calculation algorithm.* Just let the rule engine do the hard work. Notice that the speedup is relative to the size of your planning problem (your __n__), making incremental score calculation far more scalable. [[avoidCallingRemoteServicesDuringScoreCalculation]] === Avoid calling remote services during score calculation Do not call remote services in your score calculation (except if you are bridging `EasyScoreCalculator` to a legacy system). The network latency will kill your score calculation performance. Cache the results of those remote services if possible. If some parts of a constraint can be calculated once, when the `Solver` starts, and never change during solving, then turn them into xref:planner-configuration/planner-configuration.adoc#cachedProblemFact[cached problem facts]. [[pointlessConstraints]] === Pointless constraints If you know a certain constraint can never be broken (or it is always broken), do not write a score constraint for it. For example in n queens, the score calculation does not check if multiple queens occupy the same column, because a ``Queen``'s `column` never changes and every solution starts with each `Queen` on a different ``column``. [NOTE] ==== Do not go overboard with this. If some datasets do not use a specific constraint but others do, just return out of the constraint as soon as you can. There is no need to dynamically change your score calculation based on the dataset. ==== [[buildInHardConstraint]] === Built-in hard constraint Instead of implementing a hard constraint, it can sometimes be built in. For example, if `Lecture` A should never be assigned to `Room` X, but it uses `ValueRangeProvider` on Solution, so the `Solver` will often try to assign it to `Room` X too (only to find out that it breaks a hard constraint). Use xref:planner-configuration/planner-configuration.adoc#valueRangeProviderOnPlanningEntity[a ValueRangeProvider on the planning entity] or xref:move-and-neighborhood-selection/move-and-neighborhood-selection.adoc#filteredSelection[filtered selection] to define that Course A should only be assigned a `Room` different than X. This can give a good performance gain in some use cases, not just because the score calculation is faster, but mainly because most optimization algorithms will spend less time evaluating infeasible solutions. However, usually this is not a good idea because there is a real risk of trading short term benefits for long term harm: * Many optimization algorithms rely on the freedom to break hard constraints when changing planning entities, to get out of local optima. * Both implementation approaches have limitations (feature compatibility, disabling automatic performance optimizations), as explained in their documentation. [[otherScoreCalculationPerformanceTricks]] === Other score calculation performance tricks * Verify that your score calculation happens in the correct `Number` type. If you are making the sum of `int` values, do not sum it in a `double` which takes longer. * For optimal performance, always use server mode (``java -server``). We have seen performance increases of 50% by turning on server mode. * For optimal performance, use the latest Java version. For example, in the past we have seen performance increases of 30% by switching from java 1.5 to 1.6. * Always remember that premature optimization is the root of all evil. Make sure your design is flexible enough to allow configuration based tweaking. [[scoreTrap]] === Score trap Make sure that none of your score constraints cause a score trap. A trapped score constraint uses the same weight for different constraint matches, when it could just as easily use a different weight. It effectively lumps its constraint matches together, which creates a flatlined score function for that constraint. This can cause a solution state in which several moves need to be done to resolve or lower the weight of that single constraint. Some examples of score traps: * You need two doctors at each table, but you are only moving one doctor at a time. So the solver has no incentive to move a doctor to a table with no doctors. Punish a table with no doctors more than a table with only one doctor in that score constraint in the score function. * Two exams need to be conducted at the same time, but you are only moving one exam at a time. So the solver has to move one of those exams to another timeslot without moving the other in the same move. Add a coarse-grained move that moves both exams at the same time. For example, consider this score trap. If the blue item moves from an overloaded computer to an empty computer, the hard score should improve. The trapped score implementation fails to do that: image::score-calculation/scoreTrap.png[align=""center""] The Solver should eventually get out of this trap, but it will take a lot of effort (especially if there are even more processes on the overloaded computer). Before they do that, they might actually start moving more processes into that overloaded computer, as there is no penalty for doing so. [NOTE] ==== Avoiding score traps does not mean that your score function should be smart enough to avoid local optima. Leave it to the optimization algorithms to deal with the local optima. Avoiding score traps means to avoid, for each score constraint individually, a flatlined score function. ==== [IMPORTANT] ==== Always specify the degree of infeasibility. The business will often say ""if the solution is infeasible, it does not matter how infeasible it is."" While that is true for the business, it is not true for score calculation as it benefits from knowing how infeasible it is. In practice, soft constraints usually do this naturally and it is just a matter of doing it for the hard constraints too. ==== There are several ways to deal with a score trap: * Improve the score constraint to make a distinction in the score weight. For example, penalize `-1hard` for every missing CPU, instead of just `-1hard` if any CPU is missing. * If changing the score constraint is not allowed from the business perspective, add a lower score level with a score constraint that makes such a distinction. For example, penalize `-1subsoft` for every missing CPU, on top of `-1hard` if any CPU is missing. The business ignores the subsoft score level. * Add coarse-grained moves and union select them with the existing fine-grained moves. A coarse-grained move effectively does multiple moves to directly get out of a score trap with a single move. For example, move multiple items from the same container to another container. [[stepLimitBenchmark]] === `stepLimit` benchmark Not all score constraints have the same performance cost. Sometimes one score constraint can kill the score calculation performance outright. Use the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] to do a one minute run and check what happens to the score calculation speed if you comment out all but one of the score constraints. [[fairnessScoreConstraints]] === Fairness score constraints Some use cases have a business requirement to provide a fair schedule (usually as a soft score constraint), for example: * Fairly distribute the workload amongst the employees, to avoid envy. * Evenly distribute the workload amongst assets, to improve reliability. Implementing such a constraint can seem difficult (especially because there are different ways to formalize fairness), but usually the _squared workload_ implementation behaves most desirable. For each employee/asset, count the workload `w` and subtract `w²` from the score. image::score-calculation/fairnessScoreConstraint.png[align=""center""] As shown above, the _squared workload_ implementation guarantees that if you select two employees from a given solution and make their distribution between those two employees fairer, then the resulting new solution will have a better overall score. Do not just use the difference from the average workload, as that can lead to unfairness, as demonstrated below. image::score-calculation/fairnessScoreConstraintPitfall.png[align=""center""] [NOTE] ==== Instead of the _squared workload_, it is also possible to use the https://en.wikipedia.org/wiki/Variance[variance] (squared difference to the average) or the http://en.wikipedia.org/wiki/Standard_deviation[standard deviation] (square root of the variance). This has no effect on the score comparison, because the average will not change during planning. It is just more work to implement (because the average needs to be known) and trivially slower (because the calculation is a bit longer). ==== When the workload is perfectly balanced, the user often likes to see a `0` score, instead of the distracting `-34soft` in the image above (for the last solution which is almost perfectly balanced). To nullify this, either add the average multiplied by the number of entities to the score or instead show the variance or standard deviation in the UI. [[constraintConfiguration]] == Constraint configuration: adjust constraint weights dynamically Deciding the correct <> and <> for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: image::score-calculation/parameterizeTheScoreWeights.png[align=""center""] [[createAConstraintConfiguration]] === Create a constraint configuration First, create a new class to hold the constraint weights and other constraint parameters. Annotate it with `@ConstraintConfiguration`: [source,java,options=""nowrap""] ---- @ConstraintConfiguration public class ConferenceConstraintConfiguration { ... } ---- There will be exactly one instance of this class per planning solution. The planning solution and the constraint configuration have a one-to-one relationship, but they serve a different purpose, so they aren't merged into a single class. A `@ConstraintConfiguration` class can extend a parent `@ConstraintConfiguration` class, which can be useful in international use cases with many regional constraints. Add the constraint configuration on the planning solution and annotate that field or property with `@ConstraintConfigurationProvider`: [source,java,options=""nowrap""] ---- @PlanningSolution public class ConferenceSolution { @ConstraintConfigurationProvider private ConferenceConstraintConfiguration constraintConfiguration; ... } ---- The `@ConstraintConfigurationProvider` annotation automatically exposes the constraint configuration as a xref:planner-configuration/planner-configuration.adoc#problemFacts[problem fact], there is no need to add a `@ProblemFactProperty` annotation. The constraint configuration class holds the <>, but it can also hold constraint parameters. For example in conference scheduling, the minimum pause constraint has a constraint weight (like any other constraint), but it also has a constraint parameter that defines the length of the minimum pause between two talks of the same speaker. That pause length depends on the conference (= the planning problem): in some big conferences 20 minutes isn't enough to go from one room to the other. That pause length is a field in the constraint configuration without a `@ConstraintWeight` annotation. [[constraintWeight]] === Add a constraint weight for each constraint In the constraint configuration class, add a `@ConstraintWeight` field or property for each constraint: [source,java,options=""nowrap""] ---- @ConstraintConfiguration(constraintPackage = ""...conferencescheduling.score"") public class ConferenceConstraintConfiguration { @ConstraintWeight(""Speaker conflict"") private HardMediumSoftScore speakerConflict = HardMediumSoftScore.ofHard(10); @ConstraintWeight(""Theme track conflict"") private HardMediumSoftScore themeTrackConflict = HardMediumSoftScore.ofSoft(10); @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ... } ---- The type of the constraint weights must be the same score class as xref:planner-configuration/planner-configuration.adoc#scoreOfASolution[the planning solution's score member]. For example in conference scheduling, `ConferenceSolution.getScore()` and `ConferenceConstraintConfiguration.getSpeakerConflict()` both return a `HardMediumSoftScore`. A constraint weight cannot be null. Give each constraint weight a default value, but expose them in a UI so the business users can tweak them. The example above uses the `ofHard()`, `ofMedium()` and `ofSoft()` methods to do that. Notice how it defaults the _content conflict_ constraint as ten times more important than the _theme track conflict_ constraint. Normally, a constraint weight only uses one score level, but it's possible to use multiple score levels (at a small performance cost). Each constraint has a constraint package and a constraint name, together they form the constraint id. These connect the constraint weight with the constraint implementation. *For each constraint weight, there must be a constraint implementation with the same package and the same name.* * The `@ConstraintConfiguration` annotation has a `constraintPackage` property that defaults to the package of the constraint configuration class. Most cases with xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation], need to override that because the DRLs use another package. For example, the DRL below uses the package `...conferencescheduling.score`, so the constraint configuration above specifies a `constraintPackage`. Cases with xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams], normally don't need to specify it. * The `@ConstraintWeight` annotation has a `value` which is the constraint name (for example ""Speaker conflict""). It inherits the constraint package from the `@ConstraintConfiguration`, but it can override that, for example `@ConstraintWeight(constraintPackage = ""...region.france"", ...)` to use a different constraint package than some of the other weights. So every constraint weight ends up with a constraint package and a constraint name. Each constraint weight links with a constraint implementation, for example in xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation]: [source,options=""nowrap""] ---- package ...conferencescheduling.solver; rule ""Speaker conflict"" when ... then scoreHolder.penalize(kcontext); end rule ""Theme track conflict"" when ... then scoreHolder.penalize(kcontext, ...); end rule ""Content conflict"" when ... then scoreHolder.penalize(kcontext, ...); end ---- Each of the constraint weights defines the score level and score weight of their constraint. The constraint implementation calls `reward()` or `penalize()` and the constraint weight is automatically applied. If the constraint implementation provides a match weight, that *match weight is multiplied with the constraint weight*. For example, the _content conflict_ constraint weight defaults to `100soft` and the constraint implementation penalizes each match based on the number of shared content tags: [source,java,options=""nowrap""] ---- @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ---- [source,options=""nowrap""] ---- rule ""Content conflict"" when $talk1 : Talk(...) $talk2 : Talk(...) then scoreHolder.penalize(kcontext, $talk2.overlappingContentCount($talk1)); end ---- So when 2 overlapping talks share only 1 content tag, the score is impacted by `-100soft`. But when 2 overlapping talks share 3 content tags, the match weight is `3`, so the score is impacted by `-300soft`. [[explainingTheScore]] == Explaining the score: which constraints are broken? The easiest way to explain the score during development is to print the return value of `explainScore()`, but only use that method for diagnostic purposes: [source,java,options=""nowrap""] ---- System.out.println(scoreManager.explainScore(solution)); ---- For example in conference scheduling, this prints that talk `S51` is responsible for breaking the hard constraint `Speaker required room tag`: ---- Explanation of score (-1hard/-806soft): Constraint match totals: -1hard: constraint (Speaker required room tag) has 1 matches: -1hard: justifications ([S51]) -340soft: constraint (Theme track conflict) has 32 matches: -20soft: justifications ([S68, S66]) -20soft: justifications ([S61, S44]) ... ... Indictments (top 5 of 72): -1hard/-22soft: justification (S51) has 12 matches: -1hard: constraint (Speaker required room tag) -10soft: constraint (Theme track conflict) ... ... ---- [IMPORTANT] ==== Do not attempt to parse this string or use it in your UI or exposed services. Instead use the ConstraintMatch API below and do it properly. ==== [[usingScoreCalculationOutsideTheSolver]] === Using score calculation outside the `Solver` If other parts of your application, for example your webUI, need to calculate the score of a solution, use the `ScoreManager` API: [source,java,options=""nowrap""] ---- ScoreManager scoreManager = ScoreManager.create(solverFactory); ScoreExplanation scoreExplanation = scoreManager.explain(cloudBalance); ---- Then use it when you need to calculate the `Score` of a solution: [source,java,options=""nowrap""] ---- HardSoftScore score = scoreExplanation.getScore(); ---- Furthermore, the `ScoreExplanation` can help explain the score through constraint match totals and/or indictments: image::score-calculation/scoreVisualization.png[align=""center""] [[constraintMatchTotal]] === Constraint match total: break down the score by constraint To break down the score per constraint, get the ``ConstraintMatchTotal``s from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Collection> constraintMatchTotals = scoreExplanation.getConstraintMatchTotalMap().values(); for (ConstraintMatchTotal constraintMatchTotal : constraintMatchTotals) { String constraintName = constraintMatchTotal.getConstraintName(); // The score impact of that constraint HardSoftScore totalScore = constraintMatchTotal.getScore(); for (ConstraintMatch constraintMatch : constraintMatchTotal.getConstraintMatchSet()) { List justificationList = constraintMatch.getJustificationList(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `ConstraintMatchTotal` represents one constraint and has a part of the overall score. The sum of all the `ConstraintMatchTotal.getScore()` equals the overall score. [NOTE] ==== xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams] and xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] supports constraint matches automatically, but <> requires <>. ==== [[indictmentHeatMap]] === Indictment heat map: visualize the hot planning entities To show a heat map in the UI that highlights the planning entities and problem facts have an impact on the ``Score``, get the `Indictment` map from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Map> indictmentMap = scoreExplanation.getIndictmentMap(); for (CloudProcess process : cloudBalance.getProcessList()) { Indictment indictment = indictmentMap.get(process); if (indictment == null) { continue; } // The score impact of that planning entity HardSoftScore totalScore = indictment.getScore(); for (ConstraintMatch constraintMatch : indictment.getConstraintMatchSet()) { String constraintName = constraintMatch.getConstraintName(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `Indictment` is the sum of all constraints where that justification object is involved with. The sum of all the `Indictment.getScoreTotal()` differs from the overall score, because multiple ``Indictment``s can share the same `ConstraintMatch`. [NOTE] ==== xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams] and xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] supports constraint matches automatically, but <> requires <>. ==== [[testingScoreConstraints]] == Testing score constraints It's recommended to write a unit test for each score constraint individually to check that it behaves correctly. Different score calculation types come with different tools for testing. For more, see xref:constraint-streams/constraint-streams.adoc#constraintStreamsTesting[testing Constraint Streams] or xref:drools-score-calculation/drools-score-calculation.adoc#testingDroolsConstraints[testing Drools constraints]. ",12529,False,2218.7090018858285,median "// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex ""__omp_offloading_[0-9a-z]+_[0-9a-z]+"" ""reduction_size[.].+[.]"" ""pl_cond[.].+[.|,]"" --prefix-filecheck-ir-name _ // Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -disable-llvm-optzns | FileCheck %s --check-prefix=CHECK // expected-no-diagnostics #ifndef HEADER #define HEADER template tx ftemplate(int n) { tx b[10]; #pragma omp target { tx d = n; #pragma omp parallel for for(int i=0; i<10; i++) { b[i] += d; } b[3] += 1; } return b[3]; } int bar(int n){ int a = 0; a += ftemplate(n); return a; } #endif // CHECK1-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__Z9ftemplateIiET_i_l14_worker // CHECK1-SAME: () #[[ATTR0:[0-9]+]] { // CHECK1-NEXT: entry: // CHECK1-NEXT: [[WORK_FN:%.*]] = alloca i8*, align 8 // CHECK1-NEXT: [[EXEC_STATUS:%.*]] = alloca i8, align 1 // CHECK1-NEXT: store i8* null, i8** [[WORK_FN]], align 8 // CHECK1-NEXT: store i8 0, i8* [[EXEC_STATUS]], align 1 // CHECK1-NEXT: br label [[DOTAWAIT_WORK:%.*]] // CHECK1: .await.work: // CHECK1-NEXT: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0) // CHECK1-NEXT: [[TMP0:%.*]] = call i1 @__kmpc_kernel_parallel(i8** [[WORK_FN]]) // CHECK1-NEXT: [[TMP1:%.*]] = zext i1 [[TMP0]] to i8 // CHECK1-NEXT: store i8 [[TMP1]], i8* [[EXEC_STATUS]], align 1 // CHECK1-NEXT: [[TMP2:%.*]] = load i8*, i8** [[WORK_FN]], align 8 // CHECK1-NEXT: [[SHOULD_TERMINATE:%.*]] = icmp eq i8* [[TMP2]], null // CHECK1-NEXT: br i1 [[SHOULD_TERMINATE]], label [[DOTEXIT:%.*]], label [[DOTSELECT_WORKERS:%.*]] // CHECK1: .select.workers: // CHECK1-NEXT: [[TMP3:%.*]] = load i8, i8* [[EXEC_STATUS]], align 1 // CHECK1-NEXT: [[IS_ACTIVE:%.*]] = icmp ne i8 [[TMP3]], 0 // CHECK1-NEXT: br i1 [[IS_ACTIVE]], label [[DOTEXECUTE_PARALLEL:%.*]], label [[DOTBARRIER_PARALLEL:%.*]] // CHECK1: .execute.parallel: // CHECK1-NEXT: [[TMP4:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB2:[0-9]+]]) // CHECK1-NEXT: [[TMP5:%.*]] = load i8*, i8** [[WORK_FN]], align 8 // CHECK1-NEXT: [[WORK_MATCH:%.*]] = icmp eq i8* [[TMP5]], bitcast (void (i16, i32)* @__omp_outlined___wrapper to i8*) // CHECK1-NEXT: br i1 [[WORK_MATCH]], label [[DOTEXECUTE_FN:%.*]], label [[DOTCHECK_NEXT:%.*]] // CHECK1: .execute.fn: // CHECK1-NEXT: call void @__omp_outlined___wrapper(i16 0, i32 [[TMP4]]) #[[ATTR3:[0-9]+]] // CHECK1-NEXT: br label [[DOTTERMINATE_PARALLEL:%.*]] // CHECK1: .check.next: // CHECK1-NEXT: [[TMP6:%.*]] = bitcast i8* [[TMP2]] to void (i16, i32)* // CHECK1-NEXT: call void [[TMP6]](i16 0, i32 [[TMP4]]) // CHECK1-NEXT: br label [[DOTTERMINATE_PARALLEL]] // CHECK1: .terminate.parallel: // CHECK1-NEXT: call void @__kmpc_kernel_end_parallel() // CHECK1-NEXT: br label [[DOTBARRIER_PARALLEL]] // CHECK1: .barrier.parallel: // CHECK1-NEXT: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0) // CHECK1-NEXT: br label [[DOTAWAIT_WORK]] // CHECK1: .exit: // CHECK1-NEXT: ret void // CHECK1-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__Z9ftemplateIiET_i_l14 // CHECK1-SAME: (i64 [[N:%.*]], [10 x i32]* nonnull align 4 dereferenceable(40) [[B:%.*]]) #[[ATTR1:[0-9]+]] { // CHECK1-NEXT: entry: // CHECK1-NEXT: [[N_ADDR:%.*]] = alloca i64, align 8 // CHECK1-NEXT: [[B_ADDR:%.*]] = alloca [10 x i32]*, align 8 // CHECK1-NEXT: [[CAPTURED_VARS_ADDRS:%.*]] = alloca [2 x i8*], align 8 // CHECK1-NEXT: store i64 [[N]], i64* [[N_ADDR]], align 8 // CHECK1-NEXT: store [10 x i32]* [[B]], [10 x i32]** [[B_ADDR]], align 8 // CHECK1-NEXT: [[CONV:%.*]] = bitcast i64* [[N_ADDR]] to i32* // CHECK1-NEXT: [[TMP0:%.*]] = load [10 x i32]*, [10 x i32]** [[B_ADDR]], align 8 // CHECK1-NEXT: [[NVPTX_TID:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK1-NEXT: [[NVPTX_NUM_THREADS:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK1-NEXT: [[NVPTX_WARP_SIZE:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK1-NEXT: [[THREAD_LIMIT:%.*]] = sub nuw i32 [[NVPTX_NUM_THREADS]], [[NVPTX_WARP_SIZE]] // CHECK1-NEXT: [[TMP1:%.*]] = icmp ult i32 [[NVPTX_TID]], [[THREAD_LIMIT]] // CHECK1-NEXT: br i1 [[TMP1]], label [[DOTWORKER:%.*]], label [[DOTMASTERCHECK:%.*]] // CHECK1: .worker: // CHECK1-NEXT: call void @{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__Z9ftemplateIiET_i_l14_worker() #[[ATTR3]] // CHECK1-NEXT: br label [[DOTEXIT:%.*]] // CHECK1: .mastercheck: // CHECK1-NEXT: [[NVPTX_TID1:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK1-NEXT: [[NVPTX_NUM_THREADS2:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK1-NEXT: [[NVPTX_WARP_SIZE3:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK1-NEXT: [[TMP2:%.*]] = sub nuw i32 [[NVPTX_WARP_SIZE3]], 1 // CHECK1-NEXT: [[TMP3:%.*]] = sub nuw i32 [[NVPTX_NUM_THREADS2]], 1 // CHECK1-NEXT: [[TMP4:%.*]] = xor i32 [[TMP2]], -1 // CHECK1-NEXT: [[MASTER_TID:%.*]] = and i32 [[TMP3]], [[TMP4]] // CHECK1-NEXT: [[TMP5:%.*]] = icmp eq i32 [[NVPTX_TID1]], [[MASTER_TID]] // CHECK1-NEXT: br i1 [[TMP5]], label [[DOTMASTER:%.*]], label [[DOTEXIT]] // CHECK1: .master: // CHECK1-NEXT: [[NVPTX_NUM_THREADS4:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK1-NEXT: [[NVPTX_WARP_SIZE5:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK1-NEXT: [[THREAD_LIMIT6:%.*]] = sub nuw i32 [[NVPTX_NUM_THREADS4]], [[NVPTX_WARP_SIZE5]] // CHECK1-NEXT: call void @__kmpc_kernel_init(i32 [[THREAD_LIMIT6]], i16 1) // CHECK1-NEXT: call void @__kmpc_data_sharing_init_stack() // CHECK1-NEXT: [[TMP6:%.*]] = load i16, i16* @""_openmp_static_kernel$is_shared"", align 2 // CHECK1-NEXT: [[TMP7:%.*]] = load i64, i64* @""_openmp_static_kernel$size"", align 8 // CHECK1-NEXT: call void @__kmpc_get_team_static_memory(i16 0, i8* addrspacecast (i8 addrspace(3)* getelementptr inbounds (%""union._shared_openmp_static_memory_type_$_"", %""union._shared_openmp_static_memory_type_$_"" addrspace(3)* @""_openmp_shared_static_glob_rd_$_"", i32 0, i32 0, i32 0) to i8*), i64 [[TMP7]], i16 [[TMP6]], i8** addrspacecast (i8* addrspace(3)* @""_openmp_kernel_static_glob_rd$ptr"" to i8**)) // CHECK1-NEXT: [[TMP8:%.*]] = load i8*, i8* addrspace(3)* @""_openmp_kernel_static_glob_rd$ptr"", align 8 // CHECK1-NEXT: [[TMP9:%.*]] = getelementptr inbounds i8, i8* [[TMP8]], i64 0 // CHECK1-NEXT: [[TMP10:%.*]] = bitcast i8* [[TMP9]] to %struct._globalized_locals_ty* // CHECK1-NEXT: [[D:%.*]] = getelementptr inbounds [[STRUCT__GLOBALIZED_LOCALS_TY:%.*]], %struct._globalized_locals_ty* [[TMP10]], i32 0, i32 0 // CHECK1-NEXT: [[TMP11:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB2]]) // CHECK1-NEXT: [[TMP12:%.*]] = load i32, i32* [[CONV]], align 8 // CHECK1-NEXT: store i32 [[TMP12]], i32* [[D]], align 4 // CHECK1-NEXT: [[TMP13:%.*]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[CAPTURED_VARS_ADDRS]], i64 0, i64 0 // CHECK1-NEXT: [[TMP14:%.*]] = bitcast [10 x i32]* [[TMP0]] to i8* // CHECK1-NEXT: store i8* [[TMP14]], i8** [[TMP13]], align 8 // CHECK1-NEXT: [[TMP15:%.*]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[CAPTURED_VARS_ADDRS]], i64 0, i64 1 // CHECK1-NEXT: [[TMP16:%.*]] = bitcast i32* [[D]] to i8* // CHECK1-NEXT: store i8* [[TMP16]], i8** [[TMP15]], align 8 // CHECK1-NEXT: [[TMP17:%.*]] = bitcast [2 x i8*]* [[CAPTURED_VARS_ADDRS]] to i8** // CHECK1-NEXT: call void @__kmpc_parallel_51(%struct.ident_t* @[[GLOB2]], i32 [[TMP11]], i32 1, i32 -1, i32 -1, i8* bitcast (void (i32*, i32*, [10 x i32]*, i32*)* @__omp_outlined__ to i8*), i8* bitcast (void (i16, i32)* @__omp_outlined___wrapper to i8*), i8** [[TMP17]], i64 2) // CHECK1-NEXT: [[ARRAYIDX:%.*]] = getelementptr inbounds [10 x i32], [10 x i32]* [[TMP0]], i64 0, i64 3 // CHECK1-NEXT: [[TMP18:%.*]] = load i32, i32* [[ARRAYIDX]], align 4 // CHECK1-NEXT: [[ADD:%.*]] = add nsw i32 [[TMP18]], 1 // CHECK1-NEXT: store i32 [[ADD]], i32* [[ARRAYIDX]], align 4 // CHECK1-NEXT: [[TMP19:%.*]] = load i16, i16* @""_openmp_static_kernel$is_shared"", align 2 // CHECK1-NEXT: call void @__kmpc_restore_team_static_memory(i16 0, i16 [[TMP19]]) // CHECK1-NEXT: br label [[DOTTERMINATION_NOTIFIER:%.*]] // CHECK1: .termination.notifier: // CHECK1-NEXT: call void @__kmpc_kernel_deinit(i16 1) // CHECK1-NEXT: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0) // CHECK1-NEXT: br label [[DOTEXIT]] // CHECK1: .exit: // CHECK1-NEXT: ret void // CHECK1-LABEL: define {{[^@]+}}@__omp_outlined__ // CHECK1-SAME: (i32* noalias [[DOTGLOBAL_TID_:%.*]], i32* noalias [[DOTBOUND_TID_:%.*]], [10 x i32]* nonnull align 4 dereferenceable(40) [[B:%.*]], i32* nonnull align 4 dereferenceable(4) [[D:%.*]]) #[[ATTR1]] { // CHECK1-NEXT: entry: // CHECK1-NEXT: [[DOTGLOBAL_TID__ADDR:%.*]] = alloca i32*, align 8 // CHECK1-NEXT: [[DOTBOUND_TID__ADDR:%.*]] = alloca i32*, align 8 // CHECK1-NEXT: [[B_ADDR:%.*]] = alloca [10 x i32]*, align 8 // CHECK1-NEXT: [[D_ADDR:%.*]] = alloca i32*, align 8 // CHECK1-NEXT: [[DOTOMP_IV:%.*]] = alloca i32, align 4 // CHECK1-NEXT: [[TMP:%.*]] = alloca i32, align 4 // CHECK1-NEXT: [[DOTOMP_LB:%.*]] = alloca i32, align 4 // CHECK1-NEXT: [[DOTOMP_UB:%.*]] = alloca i32, align 4 // CHECK1-NEXT: [[DOTOMP_STRIDE:%.*]] = alloca i32, align 4 // CHECK1-NEXT: [[DOTOMP_IS_LAST:%.*]] = alloca i32, align 4 // CHECK1-NEXT: [[I:%.*]] = alloca i32, align 4 // CHECK1-NEXT: store i32* [[DOTGLOBAL_TID_]], i32** [[DOTGLOBAL_TID__ADDR]], align 8 // CHECK1-NEXT: store i32* [[DOTBOUND_TID_]], i32** [[DOTBOUND_TID__ADDR]], align 8 // CHECK1-NEXT: store [10 x i32]* [[B]], [10 x i32]** [[B_ADDR]], align 8 // CHECK1-NEXT: store i32* [[D]], i32** [[D_ADDR]], align 8 // CHECK1-NEXT: [[TMP0:%.*]] = load [10 x i32]*, [10 x i32]** [[B_ADDR]], align 8 // CHECK1-NEXT: [[TMP1:%.*]] = load i32*, i32** [[D_ADDR]], align 8 // CHECK1-NEXT: store i32 0, i32* [[DOTOMP_LB]], align 4 // CHECK1-NEXT: store i32 9, i32* [[DOTOMP_UB]], align 4 // CHECK1-NEXT: store i32 1, i32* [[DOTOMP_STRIDE]], align 4 // CHECK1-NEXT: store i32 0, i32* [[DOTOMP_IS_LAST]], align 4 // CHECK1-NEXT: [[TMP2:%.*]] = load i32*, i32** [[DOTGLOBAL_TID__ADDR]], align 8 // CHECK1-NEXT: [[TMP3:%.*]] = load i32, i32* [[TMP2]], align 4 // CHECK1-NEXT: call void @__kmpc_for_static_init_4(%struct.ident_t* @[[GLOB1:[0-9]+]], i32 [[TMP3]], i32 33, i32* [[DOTOMP_IS_LAST]], i32* [[DOTOMP_LB]], i32* [[DOTOMP_UB]], i32* [[DOTOMP_STRIDE]], i32 1, i32 1) // CHECK1-NEXT: br label [[OMP_DISPATCH_COND:%.*]] // CHECK1: omp.dispatch.cond: // CHECK1-NEXT: [[TMP4:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK1-NEXT: [[CMP:%.*]] = icmp sgt i32 [[TMP4]], 9 // CHECK1-NEXT: br i1 [[CMP]], label [[COND_TRUE:%.*]], label [[COND_FALSE:%.*]] // CHECK1: cond.true: // CHECK1-NEXT: br label [[COND_END:%.*]] // CHECK1: cond.false: // CHECK1-NEXT: [[TMP5:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK1-NEXT: br label [[COND_END]] // CHECK1: cond.end: // CHECK1-NEXT: [[COND:%.*]] = phi i32 [ 9, [[COND_TRUE]] ], [ [[TMP5]], [[COND_FALSE]] ] // CHECK1-NEXT: store i32 [[COND]], i32* [[DOTOMP_UB]], align 4 // CHECK1-NEXT: [[TMP6:%.*]] = load i32, i32* [[DOTOMP_LB]], align 4 // CHECK1-NEXT: store i32 [[TMP6]], i32* [[DOTOMP_IV]], align 4 // CHECK1-NEXT: [[TMP7:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK1-NEXT: [[TMP8:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK1-NEXT: [[CMP1:%.*]] = icmp sle i32 [[TMP7]], [[TMP8]] // CHECK1-NEXT: br i1 [[CMP1]], label [[OMP_DISPATCH_BODY:%.*]], label [[OMP_DISPATCH_END:%.*]] // CHECK1: omp.dispatch.body: // CHECK1-NEXT: br label [[OMP_INNER_FOR_COND:%.*]] // CHECK1: omp.inner.for.cond: // CHECK1-NEXT: [[TMP9:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK1-NEXT: [[TMP10:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK1-NEXT: [[CMP2:%.*]] = icmp sle i32 [[TMP9]], [[TMP10]] // CHECK1-NEXT: br i1 [[CMP2]], label [[OMP_INNER_FOR_BODY:%.*]], label [[OMP_INNER_FOR_END:%.*]] // CHECK1: omp.inner.for.body: // CHECK1-NEXT: [[TMP11:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK1-NEXT: [[MUL:%.*]] = mul nsw i32 [[TMP11]], 1 // CHECK1-NEXT: [[ADD:%.*]] = add nsw i32 0, [[MUL]] // CHECK1-NEXT: store i32 [[ADD]], i32* [[I]], align 4 // CHECK1-NEXT: [[TMP12:%.*]] = load i32, i32* [[TMP1]], align 4 // CHECK1-NEXT: [[TMP13:%.*]] = load i32, i32* [[I]], align 4 // CHECK1-NEXT: [[IDXPROM:%.*]] = sext i32 [[TMP13]] to i64 // CHECK1-NEXT: [[ARRAYIDX:%.*]] = getelementptr inbounds [10 x i32], [10 x i32]* [[TMP0]], i64 0, i64 [[IDXPROM]] // CHECK1-NEXT: [[TMP14:%.*]] = load i32, i32* [[ARRAYIDX]], align 4 // CHECK1-NEXT: [[ADD3:%.*]] = add nsw i32 [[TMP14]], [[TMP12]] // CHECK1-NEXT: store i32 [[ADD3]], i32* [[ARRAYIDX]], align 4 // CHECK1-NEXT: br label [[OMP_BODY_CONTINUE:%.*]] // CHECK1: omp.body.continue: // CHECK1-NEXT: br label [[OMP_INNER_FOR_INC:%.*]] // CHECK1: omp.inner.for.inc: // CHECK1-NEXT: [[TMP15:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK1-NEXT: [[ADD4:%.*]] = add nsw i32 [[TMP15]], 1 // CHECK1-NEXT: store i32 [[ADD4]], i32* [[DOTOMP_IV]], align 4 // CHECK1-NEXT: br label [[OMP_INNER_FOR_COND]] // CHECK1: omp.inner.for.end: // CHECK1-NEXT: br label [[OMP_DISPATCH_INC:%.*]] // CHECK1: omp.dispatch.inc: // CHECK1-NEXT: [[TMP16:%.*]] = load i32, i32* [[DOTOMP_LB]], align 4 // CHECK1-NEXT: [[TMP17:%.*]] = load i32, i32* [[DOTOMP_STRIDE]], align 4 // CHECK1-NEXT: [[ADD5:%.*]] = add nsw i32 [[TMP16]], [[TMP17]] // CHECK1-NEXT: store i32 [[ADD5]], i32* [[DOTOMP_LB]], align 4 // CHECK1-NEXT: [[TMP18:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK1-NEXT: [[TMP19:%.*]] = load i32, i32* [[DOTOMP_STRIDE]], align 4 // CHECK1-NEXT: [[ADD6:%.*]] = add nsw i32 [[TMP18]], [[TMP19]] // CHECK1-NEXT: store i32 [[ADD6]], i32* [[DOTOMP_UB]], align 4 // CHECK1-NEXT: br label [[OMP_DISPATCH_COND]] // CHECK1: omp.dispatch.end: // CHECK1-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @[[GLOB1]], i32 [[TMP3]]) // CHECK1-NEXT: ret void // CHECK1-LABEL: define {{[^@]+}}@__omp_outlined___wrapper // CHECK1-SAME: (i16 zeroext [[TMP0:%.*]], i32 [[TMP1:%.*]]) #[[ATTR0]] { // CHECK1-NEXT: entry: // CHECK1-NEXT: [[DOTADDR:%.*]] = alloca i16, align 2 // CHECK1-NEXT: [[DOTADDR1:%.*]] = alloca i32, align 4 // CHECK1-NEXT: [[DOTZERO_ADDR:%.*]] = alloca i32, align 4 // CHECK1-NEXT: [[GLOBAL_ARGS:%.*]] = alloca i8**, align 8 // CHECK1-NEXT: store i32 0, i32* [[DOTZERO_ADDR]], align 4 // CHECK1-NEXT: store i16 [[TMP0]], i16* [[DOTADDR]], align 2 // CHECK1-NEXT: store i32 [[TMP1]], i32* [[DOTADDR1]], align 4 // CHECK1-NEXT: call void @__kmpc_get_shared_variables(i8*** [[GLOBAL_ARGS]]) // CHECK1-NEXT: [[TMP2:%.*]] = load i8**, i8*** [[GLOBAL_ARGS]], align 8 // CHECK1-NEXT: [[TMP3:%.*]] = getelementptr inbounds i8*, i8** [[TMP2]], i64 0 // CHECK1-NEXT: [[TMP4:%.*]] = bitcast i8** [[TMP3]] to [10 x i32]** // CHECK1-NEXT: [[TMP5:%.*]] = load [10 x i32]*, [10 x i32]** [[TMP4]], align 8 // CHECK1-NEXT: [[TMP6:%.*]] = getelementptr inbounds i8*, i8** [[TMP2]], i64 1 // CHECK1-NEXT: [[TMP7:%.*]] = bitcast i8** [[TMP6]] to i32** // CHECK1-NEXT: [[TMP8:%.*]] = load i32*, i32** [[TMP7]], align 8 // CHECK1-NEXT: call void @__omp_outlined__(i32* [[DOTADDR1]], i32* [[DOTZERO_ADDR]], [10 x i32]* [[TMP5]], i32* [[TMP8]]) #[[ATTR3]] // CHECK1-NEXT: ret void // CHECK2-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__Z9ftemplateIiET_i_l14_worker // CHECK2-SAME: () #[[ATTR0:[0-9]+]] { // CHECK2-NEXT: entry: // CHECK2-NEXT: [[WORK_FN:%.*]] = alloca i8*, align 8 // CHECK2-NEXT: [[EXEC_STATUS:%.*]] = alloca i8, align 1 // CHECK2-NEXT: store i8* null, i8** [[WORK_FN]], align 8 // CHECK2-NEXT: store i8 0, i8* [[EXEC_STATUS]], align 1 // CHECK2-NEXT: br label [[DOTAWAIT_WORK:%.*]] // CHECK2: .await.work: // CHECK2-NEXT: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0) // CHECK2-NEXT: [[TMP0:%.*]] = call i1 @__kmpc_kernel_parallel(i8** [[WORK_FN]]) // CHECK2-NEXT: [[TMP1:%.*]] = zext i1 [[TMP0]] to i8 // CHECK2-NEXT: store i8 [[TMP1]], i8* [[EXEC_STATUS]], align 1 // CHECK2-NEXT: [[TMP2:%.*]] = load i8*, i8** [[WORK_FN]], align 8 // CHECK2-NEXT: [[SHOULD_TERMINATE:%.*]] = icmp eq i8* [[TMP2]], null // CHECK2-NEXT: br i1 [[SHOULD_TERMINATE]], label [[DOTEXIT:%.*]], label [[DOTSELECT_WORKERS:%.*]] // CHECK2: .select.workers: // CHECK2-NEXT: [[TMP3:%.*]] = load i8, i8* [[EXEC_STATUS]], align 1 // CHECK2-NEXT: [[IS_ACTIVE:%.*]] = icmp ne i8 [[TMP3]], 0 // CHECK2-NEXT: br i1 [[IS_ACTIVE]], label [[DOTEXECUTE_PARALLEL:%.*]], label [[DOTBARRIER_PARALLEL:%.*]] // CHECK2: .execute.parallel: // CHECK2-NEXT: [[TMP4:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB2:[0-9]+]]) // CHECK2-NEXT: [[TMP5:%.*]] = load i8*, i8** [[WORK_FN]], align 8 // CHECK2-NEXT: [[WORK_MATCH:%.*]] = icmp eq i8* [[TMP5]], bitcast (void (i16, i32)* @__omp_outlined___wrapper to i8*) // CHECK2-NEXT: br i1 [[WORK_MATCH]], label [[DOTEXECUTE_FN:%.*]], label [[DOTCHECK_NEXT:%.*]] // CHECK2: .execute.fn: // CHECK2-NEXT: call void @__omp_outlined___wrapper(i16 0, i32 [[TMP4]]) #[[ATTR3:[0-9]+]] // CHECK2-NEXT: br label [[DOTTERMINATE_PARALLEL:%.*]] // CHECK2: .check.next: // CHECK2-NEXT: [[TMP6:%.*]] = bitcast i8* [[TMP2]] to void (i16, i32)* // CHECK2-NEXT: call void [[TMP6]](i16 0, i32 [[TMP4]]) // CHECK2-NEXT: br label [[DOTTERMINATE_PARALLEL]] // CHECK2: .terminate.parallel: // CHECK2-NEXT: call void @__kmpc_kernel_end_parallel() // CHECK2-NEXT: br label [[DOTBARRIER_PARALLEL]] // CHECK2: .barrier.parallel: // CHECK2-NEXT: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0) // CHECK2-NEXT: br label [[DOTAWAIT_WORK]] // CHECK2: .exit: // CHECK2-NEXT: ret void // CHECK2-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__Z9ftemplateIiET_i_l14 // CHECK2-SAME: (i64 [[N:%.*]], [10 x i32]* nonnull align 4 dereferenceable(40) [[B:%.*]]) #[[ATTR1:[0-9]+]] { // CHECK2-NEXT: entry: // CHECK2-NEXT: [[N_ADDR:%.*]] = alloca i64, align 8 // CHECK2-NEXT: [[B_ADDR:%.*]] = alloca [10 x i32]*, align 8 // CHECK2-NEXT: [[CAPTURED_VARS_ADDRS:%.*]] = alloca [2 x i8*], align 8 // CHECK2-NEXT: store i64 [[N]], i64* [[N_ADDR]], align 8 // CHECK2-NEXT: store [10 x i32]* [[B]], [10 x i32]** [[B_ADDR]], align 8 // CHECK2-NEXT: [[CONV:%.*]] = bitcast i64* [[N_ADDR]] to i32* // CHECK2-NEXT: [[TMP0:%.*]] = load [10 x i32]*, [10 x i32]** [[B_ADDR]], align 8 // CHECK2-NEXT: [[NVPTX_TID:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK2-NEXT: [[NVPTX_NUM_THREADS:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK2-NEXT: [[NVPTX_WARP_SIZE:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK2-NEXT: [[THREAD_LIMIT:%.*]] = sub nuw i32 [[NVPTX_NUM_THREADS]], [[NVPTX_WARP_SIZE]] // CHECK2-NEXT: [[TMP1:%.*]] = icmp ult i32 [[NVPTX_TID]], [[THREAD_LIMIT]] // CHECK2-NEXT: br i1 [[TMP1]], label [[DOTWORKER:%.*]], label [[DOTMASTERCHECK:%.*]] // CHECK2: .worker: // CHECK2-NEXT: call void @{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__Z9ftemplateIiET_i_l14_worker() #[[ATTR3]] // CHECK2-NEXT: br label [[DOTEXIT:%.*]] // CHECK2: .mastercheck: // CHECK2-NEXT: [[NVPTX_TID1:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK2-NEXT: [[NVPTX_NUM_THREADS2:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK2-NEXT: [[NVPTX_WARP_SIZE3:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK2-NEXT: [[TMP2:%.*]] = sub nuw i32 [[NVPTX_WARP_SIZE3]], 1 // CHECK2-NEXT: [[TMP3:%.*]] = sub nuw i32 [[NVPTX_NUM_THREADS2]], 1 // CHECK2-NEXT: [[TMP4:%.*]] = xor i32 [[TMP2]], -1 // CHECK2-NEXT: [[MASTER_TID:%.*]] = and i32 [[TMP3]], [[TMP4]] // CHECK2-NEXT: [[TMP5:%.*]] = icmp eq i32 [[NVPTX_TID1]], [[MASTER_TID]] // CHECK2-NEXT: br i1 [[TMP5]], label [[DOTMASTER:%.*]], label [[DOTEXIT]] // CHECK2: .master: // CHECK2-NEXT: [[NVPTX_NUM_THREADS4:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK2-NEXT: [[NVPTX_WARP_SIZE5:%.*]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK2-NEXT: [[THREAD_LIMIT6:%.*]] = sub nuw i32 [[NVPTX_NUM_THREADS4]], [[NVPTX_WARP_SIZE5]] // CHECK2-NEXT: call void @__kmpc_kernel_init(i32 [[THREAD_LIMIT6]], i16 1) // CHECK2-NEXT: call void @__kmpc_data_sharing_init_stack() // CHECK2-NEXT: [[TMP6:%.*]] = call i8* @__kmpc_data_sharing_push_stack(i64 4, i16 1) // CHECK2-NEXT: [[TMP7:%.*]] = bitcast i8* [[TMP6]] to %struct._globalized_locals_ty* // CHECK2-NEXT: [[D:%.*]] = getelementptr inbounds [[STRUCT__GLOBALIZED_LOCALS_TY:%.*]], %struct._globalized_locals_ty* [[TMP7]], i32 0, i32 0 // CHECK2-NEXT: [[TMP8:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB2]]) // CHECK2-NEXT: [[TMP9:%.*]] = load i32, i32* [[CONV]], align 8 // CHECK2-NEXT: store i32 [[TMP9]], i32* [[D]], align 4 // CHECK2-NEXT: [[TMP10:%.*]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[CAPTURED_VARS_ADDRS]], i64 0, i64 0 // CHECK2-NEXT: [[TMP11:%.*]] = bitcast [10 x i32]* [[TMP0]] to i8* // CHECK2-NEXT: store i8* [[TMP11]], i8** [[TMP10]], align 8 // CHECK2-NEXT: [[TMP12:%.*]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[CAPTURED_VARS_ADDRS]], i64 0, i64 1 // CHECK2-NEXT: [[TMP13:%.*]] = bitcast i32* [[D]] to i8* // CHECK2-NEXT: store i8* [[TMP13]], i8** [[TMP12]], align 8 // CHECK2-NEXT: [[TMP14:%.*]] = bitcast [2 x i8*]* [[CAPTURED_VARS_ADDRS]] to i8** // CHECK2-NEXT: call void @__kmpc_parallel_51(%struct.ident_t* @[[GLOB2]], i32 [[TMP8]], i32 1, i32 -1, i32 -1, i8* bitcast (void (i32*, i32*, [10 x i32]*, i32*)* @__omp_outlined__ to i8*), i8* bitcast (void (i16, i32)* @__omp_outlined___wrapper to i8*), i8** [[TMP14]], i64 2) // CHECK2-NEXT: [[ARRAYIDX:%.*]] = getelementptr inbounds [10 x i32], [10 x i32]* [[TMP0]], i64 0, i64 3 // CHECK2-NEXT: [[TMP15:%.*]] = load i32, i32* [[ARRAYIDX]], align 4 // CHECK2-NEXT: [[ADD:%.*]] = add nsw i32 [[TMP15]], 1 // CHECK2-NEXT: store i32 [[ADD]], i32* [[ARRAYIDX]], align 4 // CHECK2-NEXT: call void @__kmpc_data_sharing_pop_stack(i8* [[TMP6]]) // CHECK2-NEXT: br label [[DOTTERMINATION_NOTIFIER:%.*]] // CHECK2: .termination.notifier: // CHECK2-NEXT: call void @__kmpc_kernel_deinit(i16 1) // CHECK2-NEXT: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0) // CHECK2-NEXT: br label [[DOTEXIT]] // CHECK2: .exit: // CHECK2-NEXT: ret void // CHECK2-LABEL: define {{[^@]+}}@__omp_outlined__ // CHECK2-SAME: (i32* noalias [[DOTGLOBAL_TID_:%.*]], i32* noalias [[DOTBOUND_TID_:%.*]], [10 x i32]* nonnull align 4 dereferenceable(40) [[B:%.*]], i32* nonnull align 4 dereferenceable(4) [[D:%.*]]) #[[ATTR1]] { // CHECK2-NEXT: entry: // CHECK2-NEXT: [[DOTGLOBAL_TID__ADDR:%.*]] = alloca i32*, align 8 // CHECK2-NEXT: [[DOTBOUND_TID__ADDR:%.*]] = alloca i32*, align 8 // CHECK2-NEXT: [[B_ADDR:%.*]] = alloca [10 x i32]*, align 8 // CHECK2-NEXT: [[D_ADDR:%.*]] = alloca i32*, align 8 // CHECK2-NEXT: [[DOTOMP_IV:%.*]] = alloca i32, align 4 // CHECK2-NEXT: [[TMP:%.*]] = alloca i32, align 4 // CHECK2-NEXT: [[DOTOMP_LB:%.*]] = alloca i32, align 4 // CHECK2-NEXT: [[DOTOMP_UB:%.*]] = alloca i32, align 4 // CHECK2-NEXT: [[DOTOMP_STRIDE:%.*]] = alloca i32, align 4 // CHECK2-NEXT: [[DOTOMP_IS_LAST:%.*]] = alloca i32, align 4 // CHECK2-NEXT: [[I:%.*]] = alloca i32, align 4 // CHECK2-NEXT: store i32* [[DOTGLOBAL_TID_]], i32** [[DOTGLOBAL_TID__ADDR]], align 8 // CHECK2-NEXT: store i32* [[DOTBOUND_TID_]], i32** [[DOTBOUND_TID__ADDR]], align 8 // CHECK2-NEXT: store [10 x i32]* [[B]], [10 x i32]** [[B_ADDR]], align 8 // CHECK2-NEXT: store i32* [[D]], i32** [[D_ADDR]], align 8 // CHECK2-NEXT: [[TMP0:%.*]] = load [10 x i32]*, [10 x i32]** [[B_ADDR]], align 8 // CHECK2-NEXT: [[TMP1:%.*]] = load i32*, i32** [[D_ADDR]], align 8 // CHECK2-NEXT: store i32 0, i32* [[DOTOMP_LB]], align 4 // CHECK2-NEXT: store i32 9, i32* [[DOTOMP_UB]], align 4 // CHECK2-NEXT: store i32 1, i32* [[DOTOMP_STRIDE]], align 4 // CHECK2-NEXT: store i32 0, i32* [[DOTOMP_IS_LAST]], align 4 // CHECK2-NEXT: [[TMP2:%.*]] = load i32*, i32** [[DOTGLOBAL_TID__ADDR]], align 8 // CHECK2-NEXT: [[TMP3:%.*]] = load i32, i32* [[TMP2]], align 4 // CHECK2-NEXT: call void @__kmpc_for_static_init_4(%struct.ident_t* @[[GLOB1:[0-9]+]], i32 [[TMP3]], i32 33, i32* [[DOTOMP_IS_LAST]], i32* [[DOTOMP_LB]], i32* [[DOTOMP_UB]], i32* [[DOTOMP_STRIDE]], i32 1, i32 1) // CHECK2-NEXT: br label [[OMP_DISPATCH_COND:%.*]] // CHECK2: omp.dispatch.cond: // CHECK2-NEXT: [[TMP4:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK2-NEXT: [[CMP:%.*]] = icmp sgt i32 [[TMP4]], 9 // CHECK2-NEXT: br i1 [[CMP]], label [[COND_TRUE:%.*]], label [[COND_FALSE:%.*]] // CHECK2: cond.true: // CHECK2-NEXT: br label [[COND_END:%.*]] // CHECK2: cond.false: // CHECK2-NEXT: [[TMP5:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK2-NEXT: br label [[COND_END]] // CHECK2: cond.end: // CHECK2-NEXT: [[COND:%.*]] = phi i32 [ 9, [[COND_TRUE]] ], [ [[TMP5]], [[COND_FALSE]] ] // CHECK2-NEXT: store i32 [[COND]], i32* [[DOTOMP_UB]], align 4 // CHECK2-NEXT: [[TMP6:%.*]] = load i32, i32* [[DOTOMP_LB]], align 4 // CHECK2-NEXT: store i32 [[TMP6]], i32* [[DOTOMP_IV]], align 4 // CHECK2-NEXT: [[TMP7:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK2-NEXT: [[TMP8:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK2-NEXT: [[CMP1:%.*]] = icmp sle i32 [[TMP7]], [[TMP8]] // CHECK2-NEXT: br i1 [[CMP1]], label [[OMP_DISPATCH_BODY:%.*]], label [[OMP_DISPATCH_END:%.*]] // CHECK2: omp.dispatch.body: // CHECK2-NEXT: br label [[OMP_INNER_FOR_COND:%.*]] // CHECK2: omp.inner.for.cond: // CHECK2-NEXT: [[TMP9:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK2-NEXT: [[TMP10:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK2-NEXT: [[CMP2:%.*]] = icmp sle i32 [[TMP9]], [[TMP10]] // CHECK2-NEXT: br i1 [[CMP2]], label [[OMP_INNER_FOR_BODY:%.*]], label [[OMP_INNER_FOR_END:%.*]] // CHECK2: omp.inner.for.body: // CHECK2-NEXT: [[TMP11:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK2-NEXT: [[MUL:%.*]] = mul nsw i32 [[TMP11]], 1 // CHECK2-NEXT: [[ADD:%.*]] = add nsw i32 0, [[MUL]] // CHECK2-NEXT: store i32 [[ADD]], i32* [[I]], align 4 // CHECK2-NEXT: [[TMP12:%.*]] = load i32, i32* [[TMP1]], align 4 // CHECK2-NEXT: [[TMP13:%.*]] = load i32, i32* [[I]], align 4 // CHECK2-NEXT: [[IDXPROM:%.*]] = sext i32 [[TMP13]] to i64 // CHECK2-NEXT: [[ARRAYIDX:%.*]] = getelementptr inbounds [10 x i32], [10 x i32]* [[TMP0]], i64 0, i64 [[IDXPROM]] // CHECK2-NEXT: [[TMP14:%.*]] = load i32, i32* [[ARRAYIDX]], align 4 // CHECK2-NEXT: [[ADD3:%.*]] = add nsw i32 [[TMP14]], [[TMP12]] // CHECK2-NEXT: store i32 [[ADD3]], i32* [[ARRAYIDX]], align 4 // CHECK2-NEXT: br label [[OMP_BODY_CONTINUE:%.*]] // CHECK2: omp.body.continue: // CHECK2-NEXT: br label [[OMP_INNER_FOR_INC:%.*]] // CHECK2: omp.inner.for.inc: // CHECK2-NEXT: [[TMP15:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK2-NEXT: [[ADD4:%.*]] = add nsw i32 [[TMP15]], 1 // CHECK2-NEXT: store i32 [[ADD4]], i32* [[DOTOMP_IV]], align 4 // CHECK2-NEXT: br label [[OMP_INNER_FOR_COND]] // CHECK2: omp.inner.for.end: // CHECK2-NEXT: br label [[OMP_DISPATCH_INC:%.*]] // CHECK2: omp.dispatch.inc: // CHECK2-NEXT: [[TMP16:%.*]] = load i32, i32* [[DOTOMP_LB]], align 4 // CHECK2-NEXT: [[TMP17:%.*]] = load i32, i32* [[DOTOMP_STRIDE]], align 4 // CHECK2-NEXT: [[ADD5:%.*]] = add nsw i32 [[TMP16]], [[TMP17]] // CHECK2-NEXT: store i32 [[ADD5]], i32* [[DOTOMP_LB]], align 4 // CHECK2-NEXT: [[TMP18:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK2-NEXT: [[TMP19:%.*]] = load i32, i32* [[DOTOMP_STRIDE]], align 4 // CHECK2-NEXT: [[ADD6:%.*]] = add nsw i32 [[TMP18]], [[TMP19]] // CHECK2-NEXT: store i32 [[ADD6]], i32* [[DOTOMP_UB]], align 4 // CHECK2-NEXT: br label [[OMP_DISPATCH_COND]] // CHECK2: omp.dispatch.end: // CHECK2-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @[[GLOB1]], i32 [[TMP3]]) // CHECK2-NEXT: ret void // CHECK2-LABEL: define {{[^@]+}}@__omp_outlined___wrapper // CHECK2-SAME: (i16 zeroext [[TMP0:%.*]], i32 [[TMP1:%.*]]) #[[ATTR0]] { // CHECK2-NEXT: entry: // CHECK2-NEXT: [[DOTADDR:%.*]] = alloca i16, align 2 // CHECK2-NEXT: [[DOTADDR1:%.*]] = alloca i32, align 4 // CHECK2-NEXT: [[DOTZERO_ADDR:%.*]] = alloca i32, align 4 // CHECK2-NEXT: [[GLOBAL_ARGS:%.*]] = alloca i8**, align 8 // CHECK2-NEXT: store i32 0, i32* [[DOTZERO_ADDR]], align 4 // CHECK2-NEXT: store i16 [[TMP0]], i16* [[DOTADDR]], align 2 // CHECK2-NEXT: store i32 [[TMP1]], i32* [[DOTADDR1]], align 4 // CHECK2-NEXT: call void @__kmpc_get_shared_variables(i8*** [[GLOBAL_ARGS]]) // CHECK2-NEXT: [[TMP2:%.*]] = load i8**, i8*** [[GLOBAL_ARGS]], align 8 // CHECK2-NEXT: [[TMP3:%.*]] = getelementptr inbounds i8*, i8** [[TMP2]], i64 0 // CHECK2-NEXT: [[TMP4:%.*]] = bitcast i8** [[TMP3]] to [10 x i32]** // CHECK2-NEXT: [[TMP5:%.*]] = load [10 x i32]*, [10 x i32]** [[TMP4]], align 8 // CHECK2-NEXT: [[TMP6:%.*]] = getelementptr inbounds i8*, i8** [[TMP2]], i64 1 // CHECK2-NEXT: [[TMP7:%.*]] = bitcast i8** [[TMP6]] to i32** // CHECK2-NEXT: [[TMP8:%.*]] = load i32*, i32** [[TMP7]], align 8 // CHECK2-NEXT: call void @__omp_outlined__(i32* [[DOTADDR1]], i32* [[DOTZERO_ADDR]], [10 x i32]* [[TMP5]], i32* [[TMP8]]) #[[ATTR3]] // CHECK2-NEXT: ret void // CHECK-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}__Z9ftemplateIiET_i_l13 // CHECK-SAME: (i64 [[N:%.*]], [10 x i32]* nonnull align 4 dereferenceable(40) [[B:%.*]]) #[[ATTR0:[0-9]+]] { // CHECK-NEXT: entry: // CHECK-NEXT: [[N_ADDR:%.*]] = alloca i64, align 8 // CHECK-NEXT: [[B_ADDR:%.*]] = alloca [10 x i32]*, align 8 // CHECK-NEXT: [[CAPTURED_VARS_ADDRS:%.*]] = alloca [2 x i8*], align 8 // CHECK-NEXT: store i64 [[N]], i64* [[N_ADDR]], align 8 // CHECK-NEXT: store [10 x i32]* [[B]], [10 x i32]** [[B_ADDR]], align 8 // CHECK-NEXT: [[CONV:%.*]] = bitcast i64* [[N_ADDR]] to i32* // CHECK-NEXT: [[TMP0:%.*]] = load [10 x i32]*, [10 x i32]** [[B_ADDR]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1:[0-9]+]], i8 1, i1 true, i1 true) // CHECK-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP1]], -1 // CHECK-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK: user_code.entry: // CHECK-NEXT: [[D:%.*]] = call align 8 i8* @__kmpc_alloc_shared(i64 4) // CHECK-NEXT: [[D_ON_STACK:%.*]] = bitcast i8* [[D]] to i32* // CHECK-NEXT: [[TMP2:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // CHECK-NEXT: [[TMP3:%.*]] = load i32, i32* [[CONV]], align 4 // CHECK-NEXT: store i32 [[TMP3]], i32* [[D_ON_STACK]], align 4 // CHECK-NEXT: [[TMP4:%.*]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[CAPTURED_VARS_ADDRS]], i64 0, i64 0 // CHECK-NEXT: [[TMP5:%.*]] = bitcast [10 x i32]* [[TMP0]] to i8* // CHECK-NEXT: store i8* [[TMP5]], i8** [[TMP4]], align 8 // CHECK-NEXT: [[TMP6:%.*]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[CAPTURED_VARS_ADDRS]], i64 0, i64 1 // CHECK-NEXT: [[TMP7:%.*]] = bitcast i32* [[D_ON_STACK]] to i8* // CHECK-NEXT: store i8* [[TMP7]], i8** [[TMP6]], align 8 // CHECK-NEXT: [[TMP8:%.*]] = bitcast [2 x i8*]* [[CAPTURED_VARS_ADDRS]] to i8** // CHECK-NEXT: call void @__kmpc_parallel_51(%struct.ident_t* @[[GLOB1]], i32 [[TMP2]], i32 1, i32 -1, i32 -1, i8* bitcast (void (i32*, i32*, [10 x i32]*, i32*)* @__omp_outlined__ to i8*), i8* bitcast (void (i16, i32)* @__omp_outlined___wrapper to i8*), i8** [[TMP8]], i64 2) // CHECK-NEXT: [[ARRAYIDX:%.*]] = getelementptr inbounds [10 x i32], [10 x i32]* [[TMP0]], i64 0, i64 3 // CHECK-NEXT: [[TMP9:%.*]] = load i32, i32* [[ARRAYIDX]], align 4 // CHECK-NEXT: [[ADD:%.*]] = add nsw i32 [[TMP9]], 1 // CHECK-NEXT: store i32 [[ADD]], i32* [[ARRAYIDX]], align 4 // CHECK-NEXT: call void @__kmpc_free_shared(i8* [[D]], i64 4) // CHECK-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-NEXT: ret void // CHECK: worker.exit: // CHECK-NEXT: ret void // // // CHECK-LABEL: define {{[^@]+}}@__omp_outlined__ // CHECK-SAME: (i32* noalias [[DOTGLOBAL_TID_:%.*]], i32* noalias [[DOTBOUND_TID_:%.*]], [10 x i32]* nonnull align 4 dereferenceable(40) [[B:%.*]], i32* nonnull align 4 dereferenceable(4) [[D:%.*]]) #[[ATTR0]] { // CHECK-NEXT: entry: // CHECK-NEXT: [[DOTGLOBAL_TID__ADDR:%.*]] = alloca i32*, align 8 // CHECK-NEXT: [[DOTBOUND_TID__ADDR:%.*]] = alloca i32*, align 8 // CHECK-NEXT: [[B_ADDR:%.*]] = alloca [10 x i32]*, align 8 // CHECK-NEXT: [[D_ADDR:%.*]] = alloca i32*, align 8 // CHECK-NEXT: [[DOTOMP_IV:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[TMP:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[DOTOMP_LB:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[DOTOMP_UB:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[DOTOMP_STRIDE:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[DOTOMP_IS_LAST:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[I:%.*]] = alloca i32, align 4 // CHECK-NEXT: store i32* [[DOTGLOBAL_TID_]], i32** [[DOTGLOBAL_TID__ADDR]], align 8 // CHECK-NEXT: store i32* [[DOTBOUND_TID_]], i32** [[DOTBOUND_TID__ADDR]], align 8 // CHECK-NEXT: store [10 x i32]* [[B]], [10 x i32]** [[B_ADDR]], align 8 // CHECK-NEXT: store i32* [[D]], i32** [[D_ADDR]], align 8 // CHECK-NEXT: [[TMP0:%.*]] = load [10 x i32]*, [10 x i32]** [[B_ADDR]], align 8 // CHECK-NEXT: [[TMP1:%.*]] = load i32*, i32** [[D_ADDR]], align 8 // CHECK-NEXT: store i32 0, i32* [[DOTOMP_LB]], align 4 // CHECK-NEXT: store i32 9, i32* [[DOTOMP_UB]], align 4 // CHECK-NEXT: store i32 1, i32* [[DOTOMP_STRIDE]], align 4 // CHECK-NEXT: store i32 0, i32* [[DOTOMP_IS_LAST]], align 4 // CHECK-NEXT: [[TMP2:%.*]] = load i32*, i32** [[DOTGLOBAL_TID__ADDR]], align 8 // CHECK-NEXT: [[TMP3:%.*]] = load i32, i32* [[TMP2]], align 4 // CHECK-NEXT: call void @__kmpc_for_static_init_4(%struct.ident_t* @[[GLOB2:[0-9]+]], i32 [[TMP3]], i32 33, i32* [[DOTOMP_IS_LAST]], i32* [[DOTOMP_LB]], i32* [[DOTOMP_UB]], i32* [[DOTOMP_STRIDE]], i32 1, i32 1) // CHECK-NEXT: br label [[OMP_DISPATCH_COND:%.*]] // CHECK: omp.dispatch.cond: // CHECK-NEXT: [[TMP4:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[TMP4]], 9 // CHECK-NEXT: br i1 [[CMP]], label [[COND_TRUE:%.*]], label [[COND_FALSE:%.*]] // CHECK: cond.true: // CHECK-NEXT: br label [[COND_END:%.*]] // CHECK: cond.false: // CHECK-NEXT: [[TMP5:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK-NEXT: br label [[COND_END]] // CHECK: cond.end: // CHECK-NEXT: [[COND:%.*]] = phi i32 [ 9, [[COND_TRUE]] ], [ [[TMP5]], [[COND_FALSE]] ] // CHECK-NEXT: store i32 [[COND]], i32* [[DOTOMP_UB]], align 4 // CHECK-NEXT: [[TMP6:%.*]] = load i32, i32* [[DOTOMP_LB]], align 4 // CHECK-NEXT: store i32 [[TMP6]], i32* [[DOTOMP_IV]], align 4 // CHECK-NEXT: [[TMP7:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK-NEXT: [[TMP8:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK-NEXT: [[CMP1:%.*]] = icmp sle i32 [[TMP7]], [[TMP8]] // CHECK-NEXT: br i1 [[CMP1]], label [[OMP_DISPATCH_BODY:%.*]], label [[OMP_DISPATCH_END:%.*]] // CHECK: omp.dispatch.body: // CHECK-NEXT: br label [[OMP_INNER_FOR_COND:%.*]] // CHECK: omp.inner.for.cond: // CHECK-NEXT: [[TMP9:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK-NEXT: [[TMP10:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK-NEXT: [[CMP2:%.*]] = icmp sle i32 [[TMP9]], [[TMP10]] // CHECK-NEXT: br i1 [[CMP2]], label [[OMP_INNER_FOR_BODY:%.*]], label [[OMP_INNER_FOR_END:%.*]] // CHECK: omp.inner.for.body: // CHECK-NEXT: [[TMP11:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK-NEXT: [[MUL:%.*]] = mul nsw i32 [[TMP11]], 1 // CHECK-NEXT: [[ADD:%.*]] = add nsw i32 0, [[MUL]] // CHECK-NEXT: store i32 [[ADD]], i32* [[I]], align 4 // CHECK-NEXT: [[TMP12:%.*]] = load i32, i32* [[TMP1]], align 4 // CHECK-NEXT: [[TMP13:%.*]] = load i32, i32* [[I]], align 4 // CHECK-NEXT: [[IDXPROM:%.*]] = sext i32 [[TMP13]] to i64 // CHECK-NEXT: [[ARRAYIDX:%.*]] = getelementptr inbounds [10 x i32], [10 x i32]* [[TMP0]], i64 0, i64 [[IDXPROM]] // CHECK-NEXT: [[TMP14:%.*]] = load i32, i32* [[ARRAYIDX]], align 4 // CHECK-NEXT: [[ADD3:%.*]] = add nsw i32 [[TMP14]], [[TMP12]] // CHECK-NEXT: store i32 [[ADD3]], i32* [[ARRAYIDX]], align 4 // CHECK-NEXT: br label [[OMP_BODY_CONTINUE:%.*]] // CHECK: omp.body.continue: // CHECK-NEXT: br label [[OMP_INNER_FOR_INC:%.*]] // CHECK: omp.inner.for.inc: // CHECK-NEXT: [[TMP15:%.*]] = load i32, i32* [[DOTOMP_IV]], align 4 // CHECK-NEXT: [[ADD4:%.*]] = add nsw i32 [[TMP15]], 1 // CHECK-NEXT: store i32 [[ADD4]], i32* [[DOTOMP_IV]], align 4 // CHECK-NEXT: br label [[OMP_INNER_FOR_COND]] // CHECK: omp.inner.for.end: // CHECK-NEXT: br label [[OMP_DISPATCH_INC:%.*]] // CHECK: omp.dispatch.inc: // CHECK-NEXT: [[TMP16:%.*]] = load i32, i32* [[DOTOMP_LB]], align 4 // CHECK-NEXT: [[TMP17:%.*]] = load i32, i32* [[DOTOMP_STRIDE]], align 4 // CHECK-NEXT: [[ADD5:%.*]] = add nsw i32 [[TMP16]], [[TMP17]] // CHECK-NEXT: store i32 [[ADD5]], i32* [[DOTOMP_LB]], align 4 // CHECK-NEXT: [[TMP18:%.*]] = load i32, i32* [[DOTOMP_UB]], align 4 // CHECK-NEXT: [[TMP19:%.*]] = load i32, i32* [[DOTOMP_STRIDE]], align 4 // CHECK-NEXT: [[ADD6:%.*]] = add nsw i32 [[TMP18]], [[TMP19]] // CHECK-NEXT: store i32 [[ADD6]], i32* [[DOTOMP_UB]], align 4 // CHECK-NEXT: br label [[OMP_DISPATCH_COND]] // CHECK: omp.dispatch.end: // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @[[GLOB2]], i32 [[TMP3]]) // CHECK-NEXT: ret void // // // CHECK-LABEL: define {{[^@]+}}@__omp_outlined___wrapper // CHECK-SAME: (i16 zeroext [[TMP0:%.*]], i32 [[TMP1:%.*]]) #[[ATTR3:[0-9]+]] { // CHECK-NEXT: entry: // CHECK-NEXT: [[DOTADDR:%.*]] = alloca i16, align 2 // CHECK-NEXT: [[DOTADDR1:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[DOTZERO_ADDR:%.*]] = alloca i32, align 4 // CHECK-NEXT: [[GLOBAL_ARGS:%.*]] = alloca i8**, align 8 // CHECK-NEXT: store i16 [[TMP0]], i16* [[DOTADDR]], align 2 // CHECK-NEXT: store i32 [[TMP1]], i32* [[DOTADDR1]], align 4 // CHECK-NEXT: store i32 0, i32* [[DOTZERO_ADDR]], align 4 // CHECK-NEXT: call void @__kmpc_get_shared_variables(i8*** [[GLOBAL_ARGS]]) // CHECK-NEXT: [[TMP2:%.*]] = load i8**, i8*** [[GLOBAL_ARGS]], align 8 // CHECK-NEXT: [[TMP3:%.*]] = getelementptr inbounds i8*, i8** [[TMP2]], i64 0 // CHECK-NEXT: [[TMP4:%.*]] = bitcast i8** [[TMP3]] to [10 x i32]** // CHECK-NEXT: [[TMP5:%.*]] = load [10 x i32]*, [10 x i32]** [[TMP4]], align 8 // CHECK-NEXT: [[TMP6:%.*]] = getelementptr inbounds i8*, i8** [[TMP2]], i64 1 // CHECK-NEXT: [[TMP7:%.*]] = bitcast i8** [[TMP6]] to i32** // CHECK-NEXT: [[TMP8:%.*]] = load i32*, i32** [[TMP7]], align 8 // CHECK-NEXT: call void @__omp_outlined__(i32* [[DOTADDR1]], i32* [[DOTZERO_ADDR]], [10 x i32]* [[TMP5]], i32* [[TMP8]]) #[[ATTR2:[0-9]+]] // CHECK-NEXT: ret void // ",16278,True,5163.135270315656,median "/*************************************************************************** Copyright (c) 2016, Xilinx, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************/ #ifndef __XF_DENSE_NONPYR_OPTICAL_FLOW__ #define __XF_DENSE_NONPYR_OPTICAL_FLOW__ #include #include #include #include #include #include #include #include ""assert.h"" #include ""imgproc/xf_dense_npyr_optical_flow_types.h"" #include ""common/xf_common.h"" namespace xf{ // enable to run c-sim //#define HLS_SIM // Custom low cost colorizer. Uses RGB to show 4 directions. For // simple demo purposes only. Real applications would take flow values and do // other useful analysis on them. static void getPseudoColorInt (pix_t pix, float fx, float fy, rgba_t& rgba) { // normalization factor is key for good visualization. Make this auto-ranging // or controllable from the host TODO // const int normFac = 127/2; const int normFac = 10; int y = 127 + (int) (fy * normFac); int x = 127 + (int) (fx * normFac); if (y>255) y=255; if (y<0) y=0; if (x>255) x=255; if (x<0) x=0; rgb_t rgb; if (x > 127) { if (y < 128) { // 1 quad rgb.r = x - 127 + (127-y)/2; rgb.g = (127 - y)/2; rgb.b = 0; } else { // 4 quad rgb.r = x - 127; rgb.g = 0; rgb.b = y - 127; } } else { if (y < 128) { // 2 quad rgb.r = (127 - y)/2; rgb.g = 127 - x + (127-y)/2; rgb.b = 0; } else { // 3 quad rgb.r = 0; rgb.g = 128 - x; rgb.b = y - 127; } } rgba.r = pix/4 + 3*rgb.r/4; rgba.g = pix/4 + 3*rgb.g/4; rgba.b = pix/4 + 3*rgb.b/4; rgba.a = 255; // rgba.r = rgb.r; // rgba.g = rgb.g; // rgba.b = rgb.b ; } // read external array matB and stream. // Can be simplified to a single loop with II=1 TODO //void readMatRows ( mywide_t< XF_NPIXPERCYCLE(NPC) > *matB, hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > >& pixStream) template static void readMatRows16 (ap_uint<16> *src, hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > >& pixStream, int rows, int cols, int size) { unsigned int count = 0; for (int i=0; i < size; i++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS*ROWS/NPC #pragma HLS PIPELINE unsigned short t; t = *(src + i); mywide_t< XF_NPIXPERCYCLE(NPC) > tmpData; tmpData. data [0] = t & 0x00FF; tmpData. data [1] = t >> 8; pixStream. write (tmpData); } } template static void writeMatRowsRGBA16 (hls::stream & pixStream0, hls::stream & pixStream1, ap_uint<64>* dst, int rows, int cols, int size) { for (int i=0; i < size; ++i) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS*COLS/NPC #pragma HLS PIPELINE rgba_t d0 = pixStream0. read (); rgba_t d1 = pixStream1. read (); //unsigned int t1 = (unsigned int)d1.a << 24 | (unsigned int)d1.b << 16 | (unsigned int)d1.g << 8 | (unsigned int)d1.r; //unsigned int t0 = (unsigned int)d0.a << 24 | (unsigned int)d0.b << 16 | (unsigned int)d0.g << 8 | (unsigned int)d0.r; // who is at MSB? t0 or t1 TODO //unsigned long long l = (unsigned long long) t1 << 32 | (unsigned long long) t0; unsigned long long l = (unsigned long long)d1.a << 56 | (unsigned long long)d1.b << 48 | (unsigned long long)d1.g << 40 | (unsigned long long)d1.r << 32 | (unsigned long long)d0.a << 24 | (unsigned long long)d0.b << 16 | (unsigned long long)d0.g << 8 | (unsigned long long)d0.r; *(dst + i) = l; } } // write rgba stream to external array dst. The ""a"" is just padding and is // unused template static void pack2Vectors (hls::stream & flow0, hls::stream & flow1, ap_uint<64>* out_flow, int rows, int cols, int size) { for (int i=0; i < size; i++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS*COLS/NPC #pragma HLS PIPELINE float d0 = flow0.read(); float d1 = flow1.read(); ap_uint<32> *d0_int; d0_int = (ap_uint<32> *)&d0; ap_uint<32> *d1_int; d1_int = (ap_uint<32> *)&d1; //as 0th word will have d0_int and 1st word will have d1_int ap_uint<64> l = ((unsigned long long)( *d1_int)<<32) | (unsigned long long)( *d0_int); *(out_flow + i) = l; } } // Compute sums for bottom-right and top-right pixel and update the column sums. // Use column sums to update the integrals. Implements O(1) sliding window. // // TODO: // 1. Dont need the entire column for img1Win and img2Win. Need only the kernel // 2. Full line buffer is not needed template static void computeSums16 (hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > > img1Col [(WINDOW_SIZE+1)], hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > > img2Col [(WINDOW_SIZE+1)], hls::stream & ixix_out0, hls::stream & ixiy_out0, hls::stream & iyiy_out0, hls::stream & dix_out0, hls::stream & diy_out0, hls::stream & ixix_out1, hls::stream & ixiy_out1, hls::stream & iyiy_out1, hls::stream & dix_out1, hls::stream & diy_out1, int rows, int cols, int size) { pix_t img1Col0 [(WINDOW_SIZE+1)], img2Col0 [(WINDOW_SIZE+1)]; pix_t img1Col1 [(WINDOW_SIZE+1)], img2Col1 [(WINDOW_SIZE+1)]; #pragma HLS ARRAY_PARTITION variable=img1Col0 complete dim=0 #pragma HLS ARRAY_PARTITION variable=img2Col0 complete dim=0 #pragma HLS ARRAY_PARTITION variable=img1Col1 complete dim=0 #pragma HLS ARRAY_PARTITION variable=img2Col1 complete dim=0 static pix_t img1Win [2 * (WINDOW_SIZE+1)], img2Win [1 * (WINDOW_SIZE+1)]; #pragma HLS ARRAY_PARTITION variable=img1Win complete dim=0 #pragma HLS ARRAY_PARTITION variable=img2Win complete dim=0 //static pix_t img1Win1 [2 * (WINDOW_SIZE+1)], img2Win1 [1 * (WINDOW_SIZE+1)]; //#pragma HLS ARRAY_PARTITION variable=img1Win1 complete dim=0 //#pragma HLS ARRAY_PARTITION variable=img2Win1 complete dim=0 static int ixix=0, ixiy=0, iyiy=0, dix=0, diy=0; // column sums: // need left-shift. Array-Part leads to FF with big Muxes. Try to do with // classic array and pointer. Need current and current-WINDOW_SIZE ptrs // For II=1 pipelining, need two read and 1 write ports. Simulating it with // two arrays that have their write ports tied together. // TODO need only MAX_WODTH/2. Have to adjust zIdx and nIdx as well static int csIxixO [COLS/2], csIxiyO [COLS/2], csIyiyO [COLS/2], csDixO [COLS/2], csDiyO [COLS/2]; static int csIxixE [COLS/2], csIxiyE [COLS/2], csIyiyE [COLS/2], csDixE [COLS/2], csDiyE [COLS/2]; static int cbIxixO [COLS/2], cbIxiyO [COLS/2], cbIyiyO [COLS/2], cbDixO [COLS/2], cbDiyO [COLS/2]; static int cbIxixE [COLS/2], cbIxiyE [COLS/2], cbIyiyE [COLS/2], cbDixE [COLS/2], cbDiyE [COLS/2]; int zIdx= - (WINDOW_SIZE/2-1); int nIdx = zIdx + WINDOW_SIZE/2-1; #pragma HLS ARRAY_MAP variable=csIxixO instance=csO vertical #pragma HLS ARRAY_MAP variable=csIxiyO instance=csO vertical #pragma HLS ARRAY_MAP variable=csIyiyO instance=csO vertical #pragma HLS ARRAY_MAP variable=csDixO instance=csO vertical #pragma HLS ARRAY_MAP variable=csDiyO instance=csO vertical #pragma HLS ARRAY_MAP variable=csIxixE instance=csE vertical #pragma HLS ARRAY_MAP variable=csIxiyE instance=csE vertical #pragma HLS ARRAY_MAP variable=csIyiyE instance=csE vertical #pragma HLS ARRAY_MAP variable=csDixE instance=csE vertical #pragma HLS ARRAY_MAP variable=csDiyE instance=csE vertical #pragma HLS ARRAY_MAP variable=cbIxixO instance=cb vertical #pragma HLS ARRAY_MAP variable=cbIxiyO instance=cb vertical #pragma HLS ARRAY_MAP variable=cbIyiyO instance=cb vertical #pragma HLS ARRAY_MAP variable=cbDixO instance=cb vertical #pragma HLS ARRAY_MAP variable=cbDiyO instance=cb vertical #pragma HLS ARRAY_MAP variable=cbIxixE instance=cb vertical #pragma HLS ARRAY_MAP variable=cbIxiyE instance=cb vertical #pragma HLS ARRAY_MAP variable=cbIyiyE instance=cb vertical #pragma HLS ARRAY_MAP variable=cbDixE instance=cb vertical #pragma HLS ARRAY_MAP variable=cbDiyE instance=cb vertical if (USE_URAM) { #pragma HLS RESOURCE variable=csIxixO core=XPM_MEMORY uram #pragma HLS RESOURCE variable=csIxixE core=XPM_MEMORY uram #pragma HLS RESOURCE variable=cbIxixO core=XPM_MEMORY uram } else { #pragma HLS RESOURCE variable=csIxixO core=RAM_2P_BRAM #pragma HLS RESOURCE variable=csIxixE core=RAM_2P_BRAM #pragma HLS RESOURCE variable=cbIxixO core=RAM_2P_BRAM } #pragma HLS DEPENDENCE variable=csIxixO inter WAR false #pragma HLS DEPENDENCE variable=csIxiyO inter WAR false #pragma HLS DEPENDENCE variable=csIyiyO inter WAR false #pragma HLS DEPENDENCE variable=csDixO inter WAR false #pragma HLS DEPENDENCE variable=csDiyO inter WAR false #pragma HLS DEPENDENCE variable=csIxixE inter WAR false #pragma HLS DEPENDENCE variable=csIxiyE inter WAR false #pragma HLS DEPENDENCE variable=csIyiyE inter WAR false #pragma HLS DEPENDENCE variable=csDixE inter WAR false #pragma HLS DEPENDENCE variable=csDiyE inter WAR false #pragma HLS DEPENDENCE variable=cbIxixO inter WAR false #pragma HLS DEPENDENCE variable=cbIxiyO inter WAR false #pragma HLS DEPENDENCE variable=cbIyiyO inter WAR false #pragma HLS DEPENDENCE variable=cbDixO inter WAR false #pragma HLS DEPENDENCE variable=cbDiyO inter WAR false #pragma HLS DEPENDENCE variable=cbIxixE inter WAR false #pragma HLS DEPENDENCE variable=cbIxiyE inter WAR false #pragma HLS DEPENDENCE variable=cbIyiyE inter WAR false #pragma HLS DEPENDENCE variable=cbDixE inter WAR false #pragma HLS DEPENDENCE variable=cbDiyE inter WAR false int csIxixR0, csIxiyR0, csIyiyR0, csDixR0, csDiyR0; int csIxixR1, csIxiyR1, csIyiyR1, csDixR1, csDiyR1; for (int r = 0; r < rows; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS for (int c = 0; c < cols/2; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS/2 #pragma HLS PIPELINE int csIxixL0 = 0, csIxiyL0 = 0, csIyiyL0 = 0, csDixL0 = 0, csDiyL0 = 0; int csIxixL1 = 0, csIxiyL1 = 0, csIyiyL1 = 0, csDixL1 = 0, csDiyL1 = 0; if (zIdx >= 0) { int const zIdxPrev = zIdx==0 ? cols/2-1 : zIdx-1; csIxixL0 = csIxixO [zIdxPrev]; csIxiyL0 = csIxiyO [zIdxPrev]; csIyiyL0 = csIyiyO [zIdxPrev]; csDixL0 = csDixO [zIdxPrev]; csDiyL0 = csDiyO [zIdxPrev]; csIxixL1 = csIxixE [zIdx]; csIxiyL1 = csIxiyE [zIdx]; csIyiyL1 = csIyiyE [zIdx]; csDixL1 = csDixE [zIdx]; csDiyL1 = csDiyE [zIdx]; } for (int wr=0; wr<(WINDOW_SIZE+1); ++wr) { #pragma HLS LOOP_TRIPCOUNT min=1 max=WINDOW_SIZE+1 mywide_t< XF_NPIXPERCYCLE(NPC) > tmp1 = img1Col [wr]. read (); img1Col0[wr] = tmp1. data [0]; img1Col1[wr] = tmp1. data [1]; mywide_t< XF_NPIXPERCYCLE(NPC) > tmp2 = img2Col [wr]. read (); img2Col0[wr] = tmp2. data [0]; img2Col1[wr] = tmp2. data [1]; } // p(x+1,y) and p(x-1,y) int wrt=1; int cIxTopR0 = (img1Col0 [wrt] - img1Win [wrt*2 + 2-2]) /2 ; // p(x,y+1) and p(x,y-1) int cIyTopR0 = (img1Win [ (wrt+1)*2 + 2-1] - img1Win [ (wrt-1)*2 + 2-1]) /2; // p1(x,y) and p2(x,y) int delTopR0 = img1Win [wrt*2 + 2-1] - img2Win [wrt*1 + 1-1]; int wrb = WINDOW_SIZE-1; int cIxBotR0 = (img1Col0 [wrb] - img1Win [wrb*2 + 2-2]) /2 ; int cIyBotR0 = (img1Win [ (wrb+1)*2 + 2-1] - img1Win [ (wrb-1)*2 + 2-1]) /2; int delBotR0 = img1Win [wrb*2 + 2-1] - img2Win [wrb*1 + 1-1]; if (0 && r < WINDOW_SIZE) { cIxTopR0 = 0; cIyTopR0 = 0; delTopR0 = 0; } // p(x+1,y) and p(x-1,y) wrt=1; int cIxTopR1 = (img1Col1 [wrt] - img1Win [wrt*2 + 2-1]) /2 ; // p(x,y+1) and p(x,y-1) int cIyTopR1 = (img1Col0 [wrt + 1] - img1Col0 [wrt - 1]) /2; // p1(x,y) and p2(x,y) int delTopR1 = (img1Col0 [wrt] - img2Col0 [wrt]); wrb = WINDOW_SIZE-1; int cIxBotR1 = (img1Col1 [wrb] - img1Win [wrb*2 + 2-1]) /2 ; int cIyBotR1 = (img1Col0 [wrb + 1] - img1Col0 [wrb - 1]) /2; int delBotR1 = (img1Col0 [wrb] - img2Col0 [wrb]); csIxixR0 = cbIxixE [nIdx] + cIxBotR0 * cIxBotR0 - cIxTopR0 * cIxTopR0; csIxiyR0 = cbIxiyE [nIdx] + cIxBotR0 * cIyBotR0 - cIxTopR0 * cIyTopR0; csIyiyR0 = cbIyiyE [nIdx] + cIyBotR0 * cIyBotR0 - cIyTopR0 * cIyTopR0; csDixR0 = cbDixE [nIdx] + delBotR0 * cIxBotR0 - delTopR0 * cIxTopR0; csDiyR0 = cbDiyE [nIdx] + delBotR0 * cIyBotR0 - delTopR0 * cIyTopR0; csIxixR1 = cbIxixO [nIdx] + cIxBotR1 * cIxBotR1 - cIxTopR1 * cIxTopR1; csIxiyR1 = cbIxiyO [nIdx] + cIxBotR1 * cIyBotR1 - cIxTopR1 * cIyTopR1; csIyiyR1 = cbIyiyO [nIdx] + cIyBotR1 * cIyBotR1 - cIyTopR1 * cIyTopR1; csDixR1 = cbDixO [nIdx] + delBotR1 * cIxBotR1 - delTopR1 * cIxTopR1; csDiyR1 = cbDiyO [nIdx] + delBotR1 * cIyBotR1 - delTopR1 * cIyTopR1; int tmpixix0 = (csIxixR0 - csIxixL0); int tmpixix1 = (csIxixR0 - csIxixL0) + (csIxixR1 - csIxixL1); int tmpixiy0 = (csIxiyR0 - csIxiyL0); int tmpixiy1 = (csIxiyR0 - csIxiyL0) + (csIxiyR1 - csIxiyL1); int tmpiyiy0 = (csIyiyR0 - csIyiyL0); int tmpiyiy1 = (csIyiyR0 - csIyiyL0) + (csIyiyR1 - csIyiyL1); int tmpdix0 = (csDixR0 - csDixL0); int tmpdix1 = (csDixR0 - csDixL0) + (csDixR1 - csDixL1); int tmpdiy0 = (csDiyR0 - csDiyL0); int tmpdiy1 = (csDiyR0 - csDiyL0) + (csDiyR1 - csDiyL1); //ixix += (csIxixR0 - csIxixL0); //ixiy += (csIxiyR0 - csIxiyL0); //iyiy += (csIyiyR0 - csIyiyL0); //dix += (csDixR0 - csDixL0); //diy += (csDiyR0 - csDiyL0); //ixix_out0. write (ixix); //ixiy_out0. write (ixiy); //iyiy_out0. write (iyiy); //dix_out0. write (dix); //diy_out0. write (diy); ixix_out0. write (ixix + tmpixix0); ixiy_out0. write (ixiy + tmpixiy0); iyiy_out0. write (iyiy + tmpiyiy0); dix_out0. write (dix + tmpdix0); diy_out0. write (diy + tmpdiy0); // now compute the second pixel //ixix += (csIxixR1 - csIxixL1); //ixiy += (csIxiyR1 - csIxiyL1); //iyiy += (csIyiyR1 - csIyiyL1); //dix += (csDixR1 - csDixL1); //diy += (csDiyR1 - csDiyL1); ixix += tmpixix1; ixiy += tmpixiy1; iyiy += tmpiyiy1; dix += tmpdix1; diy += tmpdiy1; ixix_out1. write (ixix); ixiy_out1. write (ixiy); iyiy_out1. write (iyiy); dix_out1. write (dix); diy_out1. write (diy); for (int i = 0; i < (WINDOW_SIZE+1); i++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=WINDOW_SIZE+1 img1Win [i * 2] = img1Col0 [i]; img1Win [i * 2 + 1] = img1Col1 [i]; img2Win [i] = img2Col1 [i]; } cbIxixE [nIdx] = csIxixR0; cbIxiyE [nIdx] = csIxiyR0; cbIyiyE [nIdx] = csIyiyR0; cbDixE [nIdx] = csDixR0; cbDiyE [nIdx] = csDiyR0; csIxixE [nIdx] = csIxixR0; csIxiyE [nIdx] = csIxiyR0; csIyiyE [nIdx] = csIyiyR0; csDixE [nIdx] = csDixR0; csDiyE [nIdx] = csDiyR0; cbIxixO [nIdx] = csIxixR1; cbIxiyO [nIdx] = csIxiyR1; cbIyiyO [nIdx] = csIyiyR1; cbDixO [nIdx] = csDixR1; cbDiyO [nIdx] = csDiyR1; csIxixO [nIdx] = csIxixR1; csIxiyO [nIdx] = csIxiyR1; csIyiyO [nIdx] = csIyiyR1; csDixO [nIdx] = csDixR1; csDiyO [nIdx] = csDiyR1; zIdx ++; if (zIdx == cols/2) zIdx = 0; nIdx ++; if (nIdx == cols/2) nIdx = 0; } } // Cleanup. If kernel is called multiple times with different inputs, not // cleaning these vars would pollute the subsequent frames. // TODO zero in the line buffer instead, for r < WINDOW_SIZE for (int r = 0; r < (WINDOW_SIZE+1); r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=WINDOW_SIZE+1 #pragma HLS UNROLL img1Win [r] = 0; img1Win [r+(WINDOW_SIZE+1)] = 0; img2Win [r] = 0; img1Col0 [r] =0; img2Col0 [r] =0; img1Col1 [r] =0; img2Col1 [r] =0; } for (int r=0; r < cols/2; ++r) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS #pragma HLS PIPELINE csIxixO [r] = 0; csIxiyO [r] = 0; csIyiyO [r] = 0; csDixO [r] = 0; csDiyO [r] = 0; cbIxixO [r] = 0; cbIxiyO [r] = 0; cbIyiyO [r] = 0; cbDixO [r] = 0; cbDiyO [r] = 0; csIxixE [r] = 0; csIxiyE [r] = 0; csIyiyE [r] = 0; csDixE [r] = 0; csDiyE [r] = 0; cbIxixE [r] = 0; cbIxiyE [r] = 0; cbIyiyE [r] = 0; cbDixE [r] = 0; cbDiyE [r] = 0; } ixix=0; ixiy=0; iyiy=0; dix=0; diy=0; } // consume the integrals and compute flow vectors template static void computeFlow16 (hls::stream & ixix, hls::stream & ixiy, hls::stream & iyiy, hls::stream & dix, hls::stream & diy, hls::stream & fx_out, hls::stream & fy_out, int rows, int cols, int size) { for (int r = 0; r < rows; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS for (int c = 0; c < cols/2; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS/2 #pragma HLS PIPELINE int ixix_ = ixix. read (); int ixiy_ = ixiy. read (); int iyiy_ = iyiy. read (); int dix_ = dix. read (); int diy_ = diy. read (); float fx_=0, fy_=0; // matrix inv float det = (float)ixix_ * iyiy_ - (float)ixiy_ * ixiy_; if (det <= 1.0f || r<(WINDOW_SIZE) || c<((WINDOW_SIZE+1)/2)) { fx_ = 0.0; fy_ = 0.0; } else { // res est: (dsp,ff,lut) // fdiv (0,748,800), fmul (3,143,139), fadd (2,306,246), fsub (2,306,246) // sitofp (0,229,365), fcmp (0,66,72), imul(1,0,0) (in cs) //float detInv = 1.0/det; float i00 = (float)iyiy_ / det; float i01 = (float) (-ixiy_) / det; float i10 = (float) (-ixiy_) / det; float i11 = (float)ixix_ / det; fx_ = i00 * dix_ + i01 * diy_; fy_ = i10 * dix_ + i11 * diy_; } fx_out. write (fx_); fy_out. write (fy_); } } } // convert flow values to visualizable pixel. For simple demo purposes only template static void getOutPix16 (hls::stream & fx, hls::stream & fy, hls::stream & out_pix, int rows, int cols, int size) { for (int r = 0; r < rows; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS for (int c = 0; c < cols/2; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS/2 #pragma HLS PIPELINE float fx_ = fx. read (); float fy_ = fy. read (); pix_t p_ = 0; rgba_t out_pix_; getPseudoColorInt (p_, fx_, fy_, out_pix_); out_pix. write (out_pix_); } } } // line buffer for both input images. Can be split to a fn that models a single // linebuffer template static void lbWrapper16 (hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > >& f0Stream, hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > >& f1Stream, hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > > img1Col[(WINDOW_SIZE+1)], hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > > img2Col[(WINDOW_SIZE+1)], int rows, int cols, int size) { static pix_t lb1 [(WINDOW_SIZE+1)][COLS/XF_NPIXPERCYCLE(NPC)][XF_NPIXPERCYCLE(NPC)], lb2 [(WINDOW_SIZE+1)][COLS/XF_NPIXPERCYCLE(NPC)][XF_NPIXPERCYCLE(NPC)]; #pragma HLS ARRAY_MAP variable=lb1 instance=lbMap vertical #pragma HLS ARRAY_MAP variable=lb2 instance=lbMap vertical #pragma HLS ARRAY_RESHAPE variable=lb1 complete dim=1 #pragma HLS ARRAY_RESHAPE variable=lb2 complete dim=1 #pragma HLS ARRAY_RESHAPE variable=lb1 complete dim=3 #pragma HLS ARRAY_RESHAPE variable=lb2 complete dim=3 if (USE_URAM) { #pragma HLS RESOURCE variable=lb1 core=XPM_MEMORY uram #pragma HLS RESOURCE variable=lb2 core=XPM_MEMORY uram } for (int r = 0; r < rows; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS #pragma HLS LOOP_FLATTEN OFF for (int c = 0; c < cols/2; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS/2 #pragma HLS pipeline // shift up both linebuffers at col=c for (int i = 0; i < ((WINDOW_SIZE+1) - 1); i++) { mywide_t< XF_NPIXPERCYCLE(NPC) > lb; for (int k = 0; k pix0 = f0Stream. read (); img1Col [(WINDOW_SIZE+1) - 1]. write (pix0); mywide_t< XF_NPIXPERCYCLE(NPC) > pix1 = f1Stream. read (); img2Col [(WINDOW_SIZE+1) - 1]. write (pix1); for (int k = 0; k static void flowWrap16 (ap_uint<16> *frame0, ap_uint<16> *frame1, ap_uint<64> *flowx, ap_uint<64> *flowy, int rows, int cols, int size) { //#pragma HLS data_pack variable=frame0 //#pragma HLS data_pack variable=frame1 //#pragma HLS data_pack variable=framef #pragma HLS DATAFLOW // ddr <-> kernel streams. Stream depths are probably too large and can be // trimmed hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > > f0Stream, f1Stream; #pragma HLS data_pack variable=f0Stream #pragma HLS data_pack variable=f1Stream #pragma HLS STREAM variable=f0Stream depth=16 #pragma HLS STREAM variable=f1Stream depth=16 // hls::stream ff0Stream, ff1Stream; // #pragma HLS data_pack variable=ff0Stream // #pragma HLS data_pack variable=ff1Stream // #pragma HLS STREAM variable=ff0Stream depth=16 // #pragma HLS STREAM variable=ff1Stream depth=16 hls::stream < mywide_t< XF_NPIXPERCYCLE(NPC) > > img1Col [(WINDOW_SIZE+1)], img2Col [(WINDOW_SIZE+1)]; #pragma HLS data_pack variable=img1Col #pragma HLS data_pack variable=img2Col #pragma HLS STREAM variable=img1Col depth=16 #pragma HLS STREAM variable=img2Col depth=16 #pragma HLS ARRAY_PARTITION variable=img1Col complete dim=0 #pragma HLS ARRAY_PARTITION variable=img2Col complete dim=0 hls::stream ixix0, ixiy0, iyiy0, dix0, diy0; hls::stream fx0(""fx0""), fy0(""fy0""); #pragma HLS STREAM variable=ixix0 depth=16 #pragma HLS STREAM variable=ixiy0 depth=16 #pragma HLS STREAM variable=iyiy0 depth=16 #pragma HLS STREAM variable=dix0 depth=16 #pragma HLS STREAM variable=diy0 depth=16 #pragma HLS STREAM variable=fx0 depth=16 #pragma HLS STREAM variable=fy0 depth=16 hls::stream ixix1, ixiy1, iyiy1, dix1, diy1; hls::stream fx1(""fx1""), fy1(""fy1""); #pragma HLS STREAM variable=ixix1 depth=16 #pragma HLS STREAM variable=ixiy1 depth=16 #pragma HLS STREAM variable=iyiy1 depth=16 #pragma HLS STREAM variable=dix1 depth=16 #pragma HLS STREAM variable=diy1 depth=16 #pragma HLS STREAM variable=fx1 depth=16 #pragma HLS STREAM variable=fy1 depth=16 readMatRows16 (frame0, f0Stream, rows, cols, size); readMatRows16 (frame1, f1Stream, rows, cols, size); lbWrapper16 (f0Stream, f1Stream, img1Col, img2Col, rows, cols, size); computeSums16 (img1Col, img2Col, ixix0, ixiy0, iyiy0, dix0, diy0, ixix1, ixiy1, iyiy1, dix1, diy1, rows, cols, size); computeFlow16 (ixix0, ixiy0, iyiy0, dix0, diy0, fx0, fy0, rows, cols, size); computeFlow16 (ixix1, ixiy1, iyiy1, dix1, diy1, fx1, fy1, rows, cols, size); pack2Vectors (fx0, fx1, flowx, rows, cols, size); pack2Vectors (fy0, fy1, flowy, rows, cols, size); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // external interface to the kernel. // frame0 - First input frame (grayscale 1 byte per pixel) // frame1 - Second input frame (grayscale 1 byte per pixel) // framef - Output frame with flows visualized. 3 bytes per pixel + 1 byte padding //void fpga_optflow ( mywide_t< XF_NPIXPERCYCLE(NPC) > *frame0, mywide_t< XF_NPIXPERCYCLE(NPC) > *frame1, rgba2_t *framef); // ushort = 16bits, 8 bits per grayscale pix, so two pix // ulonglong = 64 bits, 32 bits per color pixel (rgba), so two color pix //void fpga_optflow (unsigned short *frame0, unsigned short *frame1, unsigned long long *framef) //void fpga_optflow (unsigned short frame0[NUM_WORDS], unsigned short frame1[NUM_WORDS], unsigned long long framef[NUM_WORDS]) template static void fpga_optflow16 (ap_uint<16> *frame0, ap_uint<16> *frame1, ap_uint<64> *flowx, ap_uint<64> *flowy, int rows, int cols, int size) { #pragma HLS inline off flowWrap16 (frame0, frame1, flowx, flowy, rows, cols, size); return; } // read external array matB and stream. // Can be simplified to a single loop with II=1 TODO, hls::stream< mywide_t< XF_NPIXPERCYCLE(NPC) > > &frame1, hls::stream &framef template static void readMatRows (ap_uint<8> *matB, hls::stream & pixStream, int rows, int cols, int size) { const int WORD_SIZE = (NPC == XF_NPPC1)? 1 : 2; for (int i=0; i < size; i++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS*ROWS/NPC #pragma HLS PIPELINE mywide_t< XF_NPIXPERCYCLE(NPC) > tmpData; tmpData.data[0] = *(matB + i); for (int k=0; k < WORD_SIZE; ++k) { pixStream. write (tmpData. data [k]); } } } // write rgba stream to external array dst. The ""a"" is just padding and is // unused template static void writeMatRowsRGBA (hls::stream & pixStream, unsigned int *dst, int rows, int cols, int size) { for (int i=0; i < size; i++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS*COLS/NPC #pragma HLS PIPELINE rgba_t tmpData = pixStream. read (); *(dst + i) = (unsigned int)tmpData.a << 24 | (unsigned int)tmpData.b << 16 | (unsigned int)tmpData.g << 8 | (unsigned int)tmpData.r; } } // Compute sums for bottom-right and top-right pixel and update the column sums. // Use column sums to update the integrals. Implements O(1) sliding window. // // TODO: // 1. Dont need the entire column for img1Win and img2Win. Need only the kernel // 2. Full line buffer is not needed template static void computeSums (hls::stream img1Col [(WINDOW_SIZE+1)], hls::stream img2Col [(WINDOW_SIZE+1)], hls::stream & ixix_out, hls::stream & ixiy_out, hls::stream & iyiy_out, hls::stream & dix_out, hls::stream & diy_out, int rows, int cols, int size) { pix_t img1Col_ [(WINDOW_SIZE+1)], img2Col_ [(WINDOW_SIZE+1)]; #pragma HLS ARRAY_PARTITION variable=img1Col_ complete dim=0 #pragma HLS ARRAY_PARTITION variable=img2Col_ complete dim=0 static pix_t img1Win [2 * (WINDOW_SIZE+1)], img2Win [1 * (WINDOW_SIZE+1)]; static int ixix=0, ixiy=0, iyiy=0, dix=0, diy=0; #pragma HLS ARRAY_PARTITION variable=img1Win complete dim=0 #pragma HLS ARRAY_PARTITION variable=img2Win complete dim=0 // column sums: // need left-shift. Array-Part leads to FF with big Muxes. Try to do with // classic array and pointer. Need current and current-WINDOW_SIZE ptrs // For II=1 pipelining, need two read and 1 write ports. Simulating it with // two arrays that have their write ports tied together. static int csIxix [COLS], csIxiy [COLS], csIyiy [COLS], csDix [COLS], csDiy [COLS]; static int cbIxix [COLS], cbIxiy [COLS], cbIyiy [COLS], cbDix [COLS], cbDiy [COLS]; int zIdx= - (WINDOW_SIZE-2); int nIdx = zIdx + WINDOW_SIZE-2; #pragma HLS ARRAY_MAP variable=csIxix instance=cs vertical #pragma HLS ARRAY_MAP variable=csIxiy instance=cs vertical #pragma HLS ARRAY_MAP variable=csIyiy instance=cs vertical #pragma HLS ARRAY_MAP variable=csDix instance=cs vertical #pragma HLS ARRAY_MAP variable=csDiy instance=cs vertical if (USE_URAM) { #pragma HLS RESOURCE variable=csIxix core=XPM_MEMORY uram } else { #pragma HLS RESOURCE variable=csIxix core=RAM_2P_BRAM } #pragma HLS DEPENDENCE variable=csIxix inter WAR false #pragma HLS DEPENDENCE variable=csIxiy inter WAR false #pragma HLS DEPENDENCE variable=csIyiy inter WAR false #pragma HLS DEPENDENCE variable=csDix inter WAR false #pragma HLS DEPENDENCE variable=csDiy inter WAR false #pragma HLS ARRAY_MAP variable=cbIxix instance=cb vertical #pragma HLS ARRAY_MAP variable=cbIxiy instance=cb vertical #pragma HLS ARRAY_MAP variable=cbIyiy instance=cb vertical #pragma HLS ARRAY_MAP variable=cbDix instance=cb vertical #pragma HLS ARRAY_MAP variable=cbDiy instance=cb vertical if (USE_URAM) { #pragma HLS RESOURCE variable=cbIxix core=XPM_MEMORY uram } else { #pragma HLS RESOURCE variable=cbIxix core=RAM_2P_BRAM } #pragma HLS DEPENDENCE variable=cbIxix inter WAR false #pragma HLS DEPENDENCE variable=cbIxiy inter WAR false #pragma HLS DEPENDENCE variable=cbIyiy inter WAR false #pragma HLS DEPENDENCE variable=cbDix inter WAR false #pragma HLS DEPENDENCE variable=cbDiy inter WAR false int csIxixR, csIxiyR, csIyiyR, csDixR, csDiyR; for (int r = 0; r < rows; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS for (int c = 0; c < cols; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS #pragma HLS PIPELINE int csIxixL = 0; int csIxiyL = 0; int csIyiyL = 0; int csDixL = 0; int csDiyL = 0; if (zIdx >= 0) { csIxixL = csIxix [zIdx]; csIxiyL = csIxiy [zIdx]; csIyiyL = csIyiy [zIdx]; csDixL = csDix [zIdx]; csDiyL = csDiy [zIdx]; } for (int wr=0; wr<(WINDOW_SIZE+1); ++wr) { #pragma HLS LOOP_TRIPCOUNT min=1 max=WINDOW_SIZE+1 img1Col_[wr] = img1Col [wr]. read (); img2Col_[wr] = img2Col [wr]. read (); } // p(x+1,y) and p(x-1,y) int wrt=1; int cIxTopR = (img1Col_ [wrt] - img1Win [wrt*2 + 2-2]) /2 ; // p(x,y+1) and p(x,y-1) int cIyTopR = (img1Win [ (wrt+1)*2 + 2-1] - img1Win [ (wrt-1)*2 + 2-1]) /2; // p1(x,y) and p2(x,y) int delTopR = img1Win [wrt*2 + 2-1] - img2Win [wrt*1 + 1-1]; int wrb = WINDOW_SIZE-1; int cIxBotR = (img1Col_ [wrb] - img1Win [wrb*2 + 2-2]) /2 ; int cIyBotR = (img1Win [ (wrb+1)*2 + 2-1] - img1Win [ (wrb-1)*2 + 2-1]) /2; int delBotR = img1Win [wrb*2 + 2-1] - img2Win [wrb*1 + 1-1]; if (0 && r < WINDOW_SIZE) { cIxTopR = 0; cIyTopR = 0; delTopR = 0; } csIxixR = cbIxix [nIdx] + cIxBotR * cIxBotR - cIxTopR * cIxTopR; csIxiyR = cbIxiy [nIdx] + cIxBotR * cIyBotR - cIxTopR * cIyTopR; csIyiyR = cbIyiy [nIdx] + cIyBotR * cIyBotR - cIyTopR * cIyTopR; csDixR = cbDix [nIdx] + delBotR * cIxBotR - delTopR * cIxTopR; csDiyR = cbDiy [nIdx] + delBotR * cIyBotR - delTopR * cIyTopR; ixix += (csIxixR - csIxixL); ixiy += (csIxiyR - csIxiyL); iyiy += (csIyiyR - csIyiyL); dix += (csDixR - csDixL); diy += (csDiyR - csDiyL); ixix_out. write (ixix); ixiy_out. write (ixiy); iyiy_out. write (iyiy); dix_out. write (dix); diy_out. write (diy); // we dont have the shifted pixel anymore to do overlay TODO // img1Delayed. write (0); for (int i = 0; i < (WINDOW_SIZE+1); i++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=WINDOW_SIZE+1 img1Win [i * 2] = img1Win [i * 2 + 1]; } for (int i=0; i < (WINDOW_SIZE+1); ++i) { #pragma HLS LOOP_TRIPCOUNT min=1 max=WINDOW_SIZE+1 img1Win [i*2 + 1] = img1Col_ [i]; img2Win [i] = img2Col_ [i]; } cbIxix [nIdx] = csIxixR; cbIxiy [nIdx] = csIxiyR; cbIyiy [nIdx] = csIyiyR; cbDix [nIdx] = csDixR; cbDiy [nIdx] = csDiyR; csIxix [nIdx] = csIxixR; csIxiy [nIdx] = csIxiyR; csIyiy [nIdx] = csIyiyR; csDix [nIdx] = csDixR; csDiy [nIdx] = csDiyR; zIdx++; if (zIdx == cols) zIdx = 0; nIdx++; if (nIdx == cols) nIdx = 0; } } // Cleanup. If kernel is called multiple times with different inputs, not // cleaning these vars would pollute the subsequent frames. // TODO zero in the line buffer instead, for r < WINDOW_SIZE for (int r = 0; r < (WINDOW_SIZE+1); r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=WINDOW_SIZE+1 #pragma HLS UNROLL img1Win [r] = 0; img1Win [r+(WINDOW_SIZE+1)] = 0; img2Win [r] = 0; img1Col_ [r] =0; img2Col_ [r] =0; } for (int r=0; r < cols; ++r) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS #pragma HLS PIPELINE csIxix [r] = 0; csIxiy [r] = 0; csIyiy [r] = 0; csDix [r] = 0; csDiy [r] = 0; cbIxix [r] = 0; cbIxiy [r] = 0; cbIyiy [r] = 0; cbDix [r] = 0; cbDiy [r] = 0; } ixix=0; ixiy=0; iyiy=0; dix=0; diy=0; } // consume the integrals and compute flow vectors template static void computeFlow (hls::stream & ixix, hls::stream & ixiy, hls::stream & iyiy, hls::stream & dix, hls::stream & diy, hls::stream &fx_out, hls::stream &fy_out, int rows, int cols, int size) { for (int r = 0; r < rows; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS for (int c = 0; c < cols; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS #pragma HLS PIPELINE int ixix_ = ixix. read (); int ixiy_ = ixiy. read (); int iyiy_ = iyiy. read (); int dix_ = dix. read (); int diy_ = diy. read (); float fx_=0, fy_=0; // matrix inv float det = (float)ixix_ * iyiy_ - (float)ixiy_ * ixiy_; if (det <= 1.0f || r<(WINDOW_SIZE) || c<(WINDOW_SIZE+1)) { fx_ = 0.0; fy_ = 0.0; } else { // res est: (dsp,ff,lut) // fdiv (0,748,800), fmul (3,143,139), fadd (2,306,246), fsub (2,306,246) // sitofp (0,229,365), fcmp (0,66,72), imul(1,0,0) (in cs) //float detInv = 1.0/det; float i00 = (float)iyiy_ / det; float i01 = (float) (-ixiy_) / det; float i10 = (float) (-ixiy_) / det; float i11 = (float)ixix_ / det; fx_ = i00 * dix_ + i01 * diy_; fy_ = i10 * dix_ + i11 * diy_; } fx_out.write(fx_); fy_out.write(fy_); } } } template static void writeOutput8 (hls::stream &fx_in, hls::stream &fy_in, float *fx_out, float *fy_out, int size) { for (int r = 0; r < size; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS*COLS #pragma HLS PIPELINE *(fx_out + r) = fx_in.read(); *(fy_out + r) = fy_in.read(); } } // convert flow values to visualizable pixel. For simple demo purposes only template static void getOutPix ( float *fx, float *fy, pix_t *p, hls::stream & out_pix, int rows, int cols, int size) { for (int r = 0; r < rows; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS for (int c = 0; c < cols; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS #pragma HLS PIPELINE float fx_ = *(fx + r*cols + c); float fy_ = *(fy + r*cols + c); pix_t p_ = *(p + r*cols + c); rgba_t out_pix_; getPseudoColorInt (p_, fx_, fy_, out_pix_); out_pix. write (out_pix_); } } } // line buffer for both input images. Can be split to a fn that models a single // linebuffer template static void lbWrapper (hls::stream & f0Stream, hls::stream & f1Stream, hls::stream img1Col[(WINDOW_SIZE+1)], hls::stream img2Col[(WINDOW_SIZE+1)], int rows, int cols, int size) { static pix_t lb1 [(WINDOW_SIZE+1)][COLS], lb2 [(WINDOW_SIZE+1)][COLS]; #pragma HLS ARRAY_MAP variable=lb1 instance=lbMap vertical #pragma HLS ARRAY_MAP variable=lb2 instance=lbMap vertical #pragma HLS ARRAY_RESHAPE variable=lb1 complete dim=1 #pragma HLS ARRAY_RESHAPE variable=lb2 complete dim=1 if (USE_URAM) { #pragma HLS RESOURCE variable=lb1 core=XPM_MEMORY uram #pragma HLS RESOURCE variable=lb2 core=XPM_MEMORY uram } for (int r = 0; r < rows; r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=ROWS #pragma HLS LOOP_FLATTEN OFF for (int c = 0; c < cols; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS #pragma HLS pipeline // shift up both linebuffers at col=c for (int i = 0; i < (WINDOW_SIZE+1) - 1; i++) { lb1 [i][c] = lb1 [i + 1][c]; img1Col [i]. write (lb1 [i][c]); lb2 [i][c] = lb2 [i+1][c]; img2Col [i]. write (lb2 [i][c]); } // read in the new pixels at col=c and row=bottom_of_lb pix_t pix0 = f0Stream. read (); lb1 [(WINDOW_SIZE+1) - 1][c] = pix0; img1Col [(WINDOW_SIZE+1) - 1]. write (pix0); pix_t pix1 = f1Stream. read (); lb2 [(WINDOW_SIZE+1) -1][c] = pix1; img2Col [(WINDOW_SIZE+1) - 1]. write (pix1); } } // cleanup for (int c = 0; c < cols; c++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=COLS #pragma HLS PIPELINE for (int r = 0; r < (WINDOW_SIZE+1); r++) { #pragma HLS LOOP_TRIPCOUNT min=1 max=WINDOW_SIZE+1 lb1 [r][c] = 0; lb2 [r][c] = 0; } } } // top level wrapper to avoid dataflow problems template static void flowWrap (ap_uint<8> *frame0, ap_uint<8> *frame1, float *flowx, float *flowy, int rows, int cols, int size) { #pragma HLS inline off #pragma HLS DATAFLOW // ddr <-> kernel streams. Stream depths are probably too large and can be // trimmed hls::stream f0Stream (""f0Stream""), f1Stream (""f1Stream""); hls::stream f0Delayed (""f0Delayed""); #pragma HLS STREAM variable=f0Stream depth=16 #pragma HLS STREAM variable=f1Stream depth=16 // #pragma HLS STREAM variable=f0Delayed depth=128 // hls::stream ffStream (""ffStream""); // #pragma HLS data_pack variable=ffStream // #pragma HLS STREAM variable=ffStream depth=16 hls::stream img1Col [(WINDOW_SIZE+1)], img2Col [(WINDOW_SIZE+1)]; hls::stream ixix, ixiy, iyiy, dix, diy; hls::stream fx, fy; #pragma HLS STREAM variable=ixix depth=16 #pragma HLS STREAM variable=ixiy depth=16 #pragma HLS STREAM variable=iyiy depth=16 #pragma HLS STREAM variable=dix depth=16 #pragma HLS STREAM variable=diy depth=16 // #pragma HLS STREAM variable=fx depth=16 // #pragma HLS STREAM variable=fy depth=16 #pragma HLS STREAM variable=img1Col depth=16 #pragma HLS STREAM variable=img2Col depth=16 #pragma HLS ARRAY_PARTITION variable=img1Col complete dim=0 #pragma HLS ARRAY_PARTITION variable=img2Col complete dim=0 readMatRows (frame0, f0Stream, rows, cols, size); readMatRows (frame1, f1Stream, rows, cols, size); lbWrapper (f0Stream, f1Stream, img1Col, img2Col, rows, cols, size); computeSums (img1Col, img2Col, ixix, ixiy, iyiy, dix, diy, rows, cols, size); computeFlow (ixix, ixiy, iyiy, dix, diy, fx, fy, rows, cols, size); writeOutput8 (fx, fy, flowx, flowy, size); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // external interface to the kernel. // frame0 - First input frame (grayscale 1 byte per pixel) // frame1 - Second input frame (grayscale 1 byte per pixel) // framef - Output frame with flows visualized. 3 bytes per pixel + 1 byte padding template static void fpga_optflow8 (ap_uint<8> *frame0, ap_uint<8> *frame1, float *flowx, float *flowy, int rows, int cols, int size) { #pragma HLS inline off flowWrap(frame0, frame1, flowx, flowy, rows, cols, size); return; } // #pragma SDS data data_mover(""frame0.data"":AXIDMA_SIMPLE) // #pragma SDS data data_mover(""frame1.data"":AXIDMA_SIMPLE) // #pragma SDS data data_mover(""framef.data"":AXIDMA_SG) #pragma SDS data mem_attribute(""frame0.data"":NON_CACHEABLE|PHYSICAL_CONTIGUOUS) #pragma SDS data mem_attribute(""frame1.data"":NON_CACHEABLE|PHYSICAL_CONTIGUOUS) #pragma SDS data mem_attribute(""flowx.data"":NON_CACHEABLE|PHYSICAL_CONTIGUOUS) #pragma SDS data mem_attribute(""flowy.data"":NON_CACHEABLE|PHYSICAL_CONTIGUOUS) #pragma SDS data access_pattern(""frame0.data"":SEQUENTIAL) #pragma SDS data access_pattern(""frame1.data"":SEQUENTIAL) #pragma SDS data access_pattern(""flowx.data"":SEQUENTIAL) #pragma SDS data access_pattern(""flowy.data"":SEQUENTIAL) #pragma SDS data copy(""frame0.data""[0:""frame0.size""]) #pragma SDS data copy(""frame1.data""[0:""frame1.size""]) #pragma SDS data copy(""flowx.data""[0:""flowx.size""]) #pragma SDS data copy(""flowy.data""[0:""flowy.size""]) template void DenseNonPyrLKOpticalFlow (xf::Mat & frame0, xf::Mat & frame1, xf::Mat & flowx, xf::Mat & flowy) { if(NPC==XF_NPPC1) { fpga_optflow8 ( (ap_uint<8> *) frame0.data, (ap_uint<8> *)frame1.data, (float *)flowx.data, (float *)flowy.data, frame0.rows, frame0.cols, frame0.size); } else { fpga_optflow16 ( (ap_uint<16> *) frame0.data, (ap_uint<16> *) frame1.data, (ap_uint<64> *)flowx.data, (ap_uint<64> *)flowy.data, frame0.rows, frame0.cols, frame0.size); } } } #endif ",16189,True,3456.1887410683953,median "= v1.EgressNetworkPolicy {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] EgressNetworkPolicy describes the current egress network policy for a Namespace. When using the 'redhat/openshift-ovs-multitenant' network plugin, traffic from a pod to an IP address outside the cluster will be checked against each EgressNetworkPolicyRule in the pod's namespace's EgressNetworkPolicy, in order. If no rule matches (or no EgressNetworkPolicy is present) then the traffic will be allowed by default. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
spec:
egress:
- to:
- cidrSelector:
dnsName:
type:
++++ == Operations [[Post-apis-network.openshift.io-v1-namespaces-namespace-egressnetworkpolicies]] === Create a EgressNetworkPolicy in a namespace Create an EgressNetworkPolicy ==== HTTP request ---- POST /apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""network.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies <<'EOF' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""network.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.EgressNetworkPolicy |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicy |201 Created|v1.EgressNetworkPolicy |202 Accepted|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-network.openshift.io-v1-namespaces-namespace-egressnetworkpolicies-name]] === Get a EgressNetworkPolicy in a namespace Read the specified EgressNetworkPolicy ==== HTTP request ---- GET /apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-network.openshift.io-v1-egressnetworkpolicies]] === Get all EgressNetworkPolicies List or watch objects of kind EgressNetworkPolicy ==== HTTP request ---- GET /apis/network.openshift.io/v1/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/egressnetworkpolicies ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicyList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-network.openshift.io-v1-namespaces-namespace-egressnetworkpolicies]] === Get all EgressNetworkPolicies in a namespace List or watch objects of kind EgressNetworkPolicy ==== HTTP request ---- GET /apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicyList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-network.openshift.io-v1-watch-namespaces-namespace-egressnetworkpolicies-name]] === Watch a EgressNetworkPolicy in a namespace Watch changes to an object of kind EgressNetworkPolicy ==== HTTP request ---- GET /apis/network.openshift.io/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-network.openshift.io-v1-watch-egressnetworkpolicies]] === Watch all EgressNetworkPolicies Watch individual changes to a list of EgressNetworkPolicy ==== HTTP request ---- GET /apis/network.openshift.io/v1/watch/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/watch/egressnetworkpolicies ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-network.openshift.io-v1-watch-namespaces-namespace-egressnetworkpolicies]] === Watch all EgressNetworkPolicies in a namespace Watch individual changes to a list of EgressNetworkPolicy ==== HTTP request ---- GET /apis/network.openshift.io/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-network.openshift.io-v1-namespaces-namespace-egressnetworkpolicies-name]] === Update a EgressNetworkPolicy in a namespace Replace the specified EgressNetworkPolicy ==== HTTP request ---- PUT /apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""network.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME <<'EOF' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""network.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.EgressNetworkPolicy |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicy |201 Created|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-network.openshift.io-v1-namespaces-namespace-egressnetworkpolicies-name]] === Patch a EgressNetworkPolicy in a namespace Partially update the specified EgressNetworkPolicy ==== HTTP request ---- PATCH /apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-network.openshift.io-v1-namespaces-namespace-egressnetworkpolicies-name]] === Delete a EgressNetworkPolicy in a namespace Delete an EgressNetworkPolicy ==== HTTP request ---- DELETE /apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-network.openshift.io-v1-namespaces-namespace-egressnetworkpolicies]] === Delete all EgressNetworkPolicies in a namespace Delete collection of EgressNetworkPolicy ==== HTTP request ---- DELETE /apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/network.openshift.io/v1/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",12205,False,2446.783387396256,median "= Microsoft Dynamics CRM Connector Reference :page-aliases: connectors::ms-dynamics/ms-dynamics-crm-connector-reference.adoc Support Category: https://www.mulesoft.com/legal/versioning-back-support-policy#anypoint-connectors[Select] Microsoft Dynamics CRM Connector Version 3.2 Release Notes: xref:release-notes::connector/ms-dynamics-crm-connector-release-notes-mule-4.adoc[Microsoft Dynamics CRM Connector Release Notes] [[dynamics-crm-config]] == Dynamics CRM Configurations ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required |Name | String | The name for this configuration. Connectors reference the configuration with this name. | | x | Connection a| * <> * <> * <> * <> | The connection types to provide to this configuration. | | x | Expiration Policy a| <> | Configures the minimum amount of time that a dynamic configuration instance can remain idle before Mule considers it eligible for expiration. This does not mean that the instance expires at the exact moment that it becomes eligible. Mule purges the instances as appropriate. | | |=== == Connection Types [[dynamics-crm-config_claims]] === Claims This authentication method includes directory sources that contain additional information (claims) about users to verify their identity. [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Username a| String | Username to connect to Dynamics CRM. | | x | Password a| String | Microsoft Windows password to connect to Dynamics NAV. | | x | Organization Service Url a| String | Base URL where the SOAP services are exposed in the form `+https://://WS+`, for example: `+https://hostname:7047/DynamicsNAV90/WS+` | | x | Disable Cn Check a| Boolean | Disable SSL certificate validation. | false | | Read Timeout a| Number | Specifies the amount of time in milliseconds that the consumer waits for a response before it times out. Default value is 0, which means infinite. | 0 | | Connection Timeout a| Number | Specifies the amount of time in milliseconds that the consumer attempts to establish a connection before it times out. Default value is 0, which means infinite. | 0 | | Enable Logging a| Boolean | If this is `true`, requests and responses display in console log. | `false` | | Host a| String | Hostname of the proxy. If this property is not set, then no proxy is used, otherwise a proxy is used, but a proxy host must be specified. | | | Port a| Number | Port of the proxy. If host is set, then this property must be set and cannot be a negative number. | | | Username a| String | Username used to authenticate against the proxy. If this property is not set, then no authentication is going to be uses for the proxy, otherwise this value must be specified. | | | Password a| String | Password used to authenticate against the proxy. | | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | | Pooling Profile a| <> | Characteristics of the connection pool. | | |=== [[dynamics-crm-config_kerberos]] === Kerberos Clients obtain tickets from the Kerberos Key Distribution Center (KDC) and present the tickets to the server when the connection is established. [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Username a| String | Username that you want to login with. Domain should not be included. | | x | Password a| String | Password for the user that you are going to login. | | x | Organization Service Url a| String | URL for the SharePoint instance that the connector is going to interact with. | | x | SPN a| String | Service Principal Names (SPN) for the SharePoint web service. | | | Realm a| String | The case-sensitive default realm (domain name) that the user belongs to. | | | KDC a| String | The Key Distribution Center (KDC), usually the domain controller name, to authenticate the user. | | | Login Properties File Path a| String | Path to a customized login properties file. When not specified, default values which usually work for most cases are set up. | | | Kerberos Properties File Path a| String | Path to a customized Kerberos properties file. | | | Disable SSL certificate validation a| Boolean | When dealing with HTTPS certificates, if the certificate is not signed by a trusted partner, the server might respond with an exception. To prevent this, you can disable the Common Name (CN) check. *Note:* This is not recommended for production environments. | `false` | | Host a| String | Hostname of the proxy. If this property is not set, then no proxy is used, otherwise a proxy is used, but a proxy host must be specified. | | | Port a| Number | Port of the proxy. If a *Host* value is set, then this property must be set and cannot be a negative number. | | | Username a| String | Username used to authenticate against the proxy. If this property is not set, then no authentication is used with the proxy, otherwise this value must be specified. | | | Password a| String | Password used to authenticate against the proxy. | | | Read Timeout a| Number | Specifies the amount of time in milliseconds that the consumer waits for a response before it times out. Default value is 0, which means infinite. | 0 | | Connection Timeout a| Number | Specifies the amount of time in milliseconds that the consumer attempts to establish a connection before it times out. Default value is 0, which means infinite. | 0 | | Enable Logging a| Boolean | If this is `true`, requests and responses display in the console log. | `false` | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | | Pooling Profile a| <> | Characteristics of the connection pool | | |=== [[dynamics-crm-config_ntlm]] === NTLM This authentication type is used on networks that include systems running on both Windows and stand-alone systems and uses an encrypted challenge-response protocol to authenticate the user. [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Username a| String | Username to connect to Dynamics CRM. | | x | Password a| String | The Windows password to connect to Dynamics NAV. | | x | Organization Service Url a| String | Base URL where the SOAP services are exposed in the form `+https://://WS+`. Example: `+https://hostname:7047/DynamicsNAV90/WS+` | | x | Disable Cn Check a| Boolean | Disable SSL certificate validation. | `false` | | Gateway Router Service Address a| String | Gateway router service address. | | | Read Timeout a| Number | Specifies the amount of time in milliseconds that the consumer waits for a response before it times out. Default value is 0, which means infinite. | 0 | | Connection Timeout a| Number | Specifies the amount of time in milliseconds that the consumer attempts to establish a connection before it times out. Default value is 0, which means infinite. | 0 | | Enable Logging a| Boolean | If this is true, requests and responses display in the console log. | false | | Host a| String | Hostname of the proxy. If this property is not set, then no proxy is used, otherwise a proxy is used, but a proxy host must be specified. | | | Port a| Number | Port of the proxy. If a *Host* value is set, then this property must be set and cannot be a negative number. | | | Username a| String | Username used to authenticate against the proxy. If this property is not set, then no authentication is going to use against the proxy, otherwise this value must be specified. | | | Password a| String | Password used to authenticate against the proxy. | | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | | Pooling Profile a| <> | Characteristics of the connection pool. | | |=== [[dynamics-crm-config_online]] === Online [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Username a| String | Username to connect to Dynamics CRM | | x | Password a| String | Windows password to connect to Dynamics NAV | | x | Organization Service Url a| String | Base URL where the SOAP services are exposed in the form `+https://://WS+`. Example: `+https://hostname:7047/DynamicsNAV90/WS+` | | x | Disable Cn Check a| Boolean | Disable SSL certificate validation. | `false` | | Authentication Retries a| Number | If the authentication process to Microsoft fails the first time, the connector attempts to re-authenticate this many times. | | x | Read Timeout a| Number | Specifies the amount of time in milliseconds that the consumer waits for a response before it times out. Default value is 0, which means infinite. | 0 | | Connection Timeout a| Number | Specifies the amount of time in milliseconds that the consumer attempts to establish a connection before it times out. Default value is 0, which means infinite. | 0 | | Enable Logging a| Boolean | If this is `true`, requests and responses display in the console log. | false | | Host a| String | Hostname of the proxy. If this property is not set, then no proxy is used, otherwise a proxy is used, but a proxy host must be specified. | | | Port a| Number | Port of the proxy. If a *Host* value is set, this property must be set and cannot be a negative number. | | | Username a| String | Username used to authenticate against the proxy. If this property is not set, then no authentication is going to use against the proxy, otherwise this value must be specified. | | | Password a| String | Password used to authenticate against the proxy. | | | Sts Metadata Url a| String | The security token service's metadata exchange URL. For Active Directory federation services (ADFS), this is usually `+https://mycompany-sts.com/adfs/services/trust/mex+`. | | | Sts Username Port Qname a| String | The name of port that accepts username and password credentials as described in the STS's metadata exchange URL. This value has to be specified as a QName in the format `+{http://schemas.microsoft.com/ws/2008/06/identity/securitytokenservice}UserNameWSTrustBinding_IWSTrust13Async+`. | | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | | Pooling Profile a| <> | Characteristics of the connection pool | | |=== == Sources * <> * <> * <> [NOTE] Microsoft Dynamics CRM Connector sources (listeners) use Object Store to save watermarks. You might experience limitations that are specific to the Object Store implementation you are using (Object Store for CloudHub deployments or Object Store for on-premises deployments), so configure Object Store to suit your needs. + For more information, see https://help.mulesoft.com/s/article/The-Different-Types-of-Object-Stores-Explained[The Different Types of Object Stores Explained]. [[deleted-object]] === Deleted Object `` ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Since a| String | Required date format is `'yyyy-MM-dd'T'HH:mm:ss'Z'` | | | Field Type a| String | | | x | Primary Node Only a| Boolean | Whether this source should only be executed on the primary node when running in a cluster. | | | Scheduling Strategy a| scheduling-strategy | Configures the scheduler that triggers the polling | | x | Redelivery Policy a| <> | Defines a policy for processing the redelivery of the same message | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Object | Attributes Type a| Any |=== === For Configurations * <> [[modified-object]] === Modified Object `` ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Since a| String | Required date format is `'yyyy-MM-dd'T'HH:mm:ss'Z'` | | | Field Type a| String | | | x | Primary Node Only a| Boolean | Whether this source should only be executed on the primary node when running in a cluster. | | | Scheduling Strategy a| scheduling-strategy | Configures the scheduler that triggers the polling | | x | Redelivery Policy a| <> | Defines a policy for processing the redelivery of the same message | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Object | Attributes Type a| Any |=== === For Configurations * <> [[new-object]] === New Object `` ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Since a| String | Required date format is `'yyyy-MM-dd'T'HH:mm:ss'Z'` | | | Field Type a| String | | | x | Primary Node Only a| Boolean | Whether this source should only be executed on the primary node when running in a cluster. | | | Scheduling Strategy a| scheduling-strategy | Configures the scheduler that triggers the polling. | | x | Redelivery Policy a| <> | Defines a policy for processing the redelivery of the same message. | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Object | Attributes Type a| Any |=== === For Configurations * <> == Operations Supported operations: * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> [[associate]] === Associate `` Create links between records. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of the entity. | | x | Id a| String | The ID of the record to which the related records are associated. | | x | Relationship Entity Role Is Referenced a| Boolean | * `false`: When the primary entity record is referencing the record to associate. * `true`: When the primary entity record is referenced by the record to associate. | false | | Relationship Schema Name a| String | The name of the relationship to create the link. | | x | Related Entities IDs a| Array of String | A List with the related entity records IDs to associate. | | x | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[create]] === Create `` Create a new record. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of the entity. | | x | Attributes a| Object | The attributes of the record as a `Map`. | `#[payload]` | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |String |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[createMultiple]] === Create Multiple `` Create multiple new records. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of the entity. | | x | List Of Attributes a| Array of Object | The list of attributes of the record as a `List>`. | `#[payload]` | | Use Single Transaction a| Boolean | If supported (CRM 2016 and above), use a single transaction to create all items, if anyone fails then rollback all. | false | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[delete]] === Delete `` Delete a record. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of the entity. | | x | Id a| String | The ID of the record to delete. | | x | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[deleteMultiple]] === Delete Multiple `` Delete multiple records. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of the entity. | | x | IDs a| Array of String | The IDs of the records to delete. | | x | Use Single Transaction a| Boolean | If supported (CRM 2016 and above) use a single transaction to delete all items, if anyone fails then rollback all. | false | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[disassociate]] === Disassociate `` Delete a link between records. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of entity. | | x | Id a| String | The ID of the record from which the related records are disassociated. | | x | Relationship Entity Role Is Referenced a| Boolean | false: when the primary entity record is Referencing the record to associate; true: when the primary entity record is Referenced by the record to associate. | false | | Relationship Schema Name a| String | The name of the relationship to delete the link. | | x | Related Entities IDs a| Array of String | A List with the related entity records IDs to disassociate. | | x | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[execute]] === Execute `` Executes a message in the form of a request, and returns a response. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Request Name a| String | The logical name of request make. | | x | Request Parameters a| Any | [DEPRECATED] This parameter will be removed from the configuration in the near future. Set the `#[payload]` correctly before calling the connector. | `#[payload]` | | Request Id a| String | The ID of the request to make. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Any |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[executeMultiple]] === Execute Multiple `` Executes multiple messages in the form of a request, and returns their respective responses. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Requests a| Array of Any | This parameter is a list of the requests (`OrganizationRequest` or `Map`). Set the `#[payload]` correctly before calling the connector. | `#[payload]` | | Use Single Transaction a| Boolean | If supported (CRM 2016 and above) use a single transaction to execute all requests, if anyone fails then rollback all. | false | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[retrieve]] === Retrieve `` Retrieve a record. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of the entity. | | x | Id a| String | The ID of the record to retrieve. | | x | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Object |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[retrieveMultipleByQuery]] === Retrieve Multiple By Query `` Use a query to retrieve multiple records. You can find the definition of the Microsoft XML query language in the schema definition in `+http://msdn.microsoft.com/en-us/library/gg328332.aspx+`. You can find the aggregation examples here `+http://msdn.microsoft.com/en-us/library/gg328122.aspx+`. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Query a| String | For DataSense Query Language, the DSQL query. For native query language, the Fetch XML query. | `#[payload]` | | Items Per Page a| Number | The number of items returned per page. | 50 | | Single Page Number a| Number | If greater than 0, returns only that specific page. | -1 | | Streaming Strategy a| * <> * <> * non-repeatable-iterable | Configure to use repeatable streams. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Array of Object |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[update]] === Update `` Update a record's attributes. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of the entity. | | x | Id a| String | The ID of the record to update. | | x | Attributes a| Object | The attributes to update as a `Map`. | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[updateMultiple]] === Update Multiple `` Update a record's attributes. ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Logical Name a| String | The logical name of the entity. | | x | List Of Attributes a| Array of Object | The list of attributes of the record as a `List>`. | `#[payload]` | | Use Single Transaction a| Boolean | If supported (CRM 2016 and above) use a single transaction to update all items, if anyone fails then rollback all. | false | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable | `#[payload]` | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> ==== Throws * MICROSOFT-DYNAMICS-CRM:CONNECTIVITY * MICROSOFT-DYNAMICS-CRM:INCOMPLETE_WSDL * MICROSOFT-DYNAMICS-CRM:INVALID_CERTIFICATE * MICROSOFT-DYNAMICS-CRM:INVALID_CREDENTIALS * MICROSOFT-DYNAMICS-CRM:INVALID_CRYPTOGRAPHIC_ALGORITHM * MICROSOFT-DYNAMICS-CRM:INVALID_JDK_VERSION * MICROSOFT-DYNAMICS-CRM:INVALID_SESSION * MICROSOFT-DYNAMICS-CRM:INVALID_URL * MICROSOFT-DYNAMICS-CRM:RETRY_EXHAUSTED * MICROSOFT-DYNAMICS-CRM:TRANSACTION * MICROSOFT-DYNAMICS-CRM:TRANSFORMATION * MICROSOFT-DYNAMICS-CRM:UNKNOWN * MICROSOFT-DYNAMICS-CRM:VALIDATION [[deleted-object]] === Deleted Object `` ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Since a| String | Required date format is `'yyyy-MM-dd'T'HH:mm:ss'Z'` | | | Field Type a| String | | | x | Primary Node Only a| Boolean | Whether this source should only be executed on the primary node when running in a cluster. | | | Scheduling Strategy a| scheduling-strategy | Configures the scheduler that triggers the polling | | x | Redelivery Policy a| <> | Defines a policy for processing the redelivery of the same message | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Object | Attributes Type a| Any |=== === For Configurations * <> [[modified-object]] === Modified Object `` ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Since a| String | Required date format is `'yyyy-MM-dd'T'HH:mm:ss'Z'` | | | Field Type a| String | | | x | Primary Node Only a| Boolean | Whether this source should only be executed on the primary node when running in a cluster. | | | Scheduling Strategy a| scheduling-strategy | Configures the scheduler that triggers the polling | | x | Redelivery Policy a| <> | Defines a policy for processing the redelivery of the same message | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Object | Attributes Type a| Any |=== === For Configurations * <> [[new-object]] === New Object `` ==== Parameters [%header,cols=""20s,25a,30a,15a,10a""] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Since a| String | Required date format is `'yyyy-MM-dd'T'HH:mm:ss'Z'` | | | Field Type a| String | | | x | Primary Node Only a| Boolean | Whether this source should only be executed on the primary node when running in a cluster. | | | Scheduling Strategy a| scheduling-strategy | Configures the scheduler that triggers the polling. | | x | Redelivery Policy a| <> | Defines a policy for processing the redelivery of the same message. | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== ==== Output [%autowidth.spread] |=== |Type |Object | Attributes Type a| Any |=== === For Configurations * <> == Types [[Reconnection]] === Reconnection [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Fails Deployment a| Boolean | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | | Reconnection Strategy a| * <> * <> | The reconnection strategy to use. | | |=== [[reconnect]] === Reconnect [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Frequency a| Number | How often to reconnect (in milliseconds). | | | Count a| Number | The number of reconnection attempts to make. | | | blocking |Boolean |If false, the reconnection strategy runs in a separate, non-blocking thread. |true | |=== [[reconnect-forever]] === Reconnect Forever [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Frequency a| Number | How often in milliseconds to reconnect. | | | blocking |Boolean |If false, the reconnection strategy runs in a separate, non-blocking thread. |true | |=== [[PoolingProfile]] === Pooling Profile [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Max Active a| Number | Controls the maximum number of Mule components that can be borrowed from a session at one time. When set to a negative value, there is no limit to the number of components that may be active at one time. When maxActive is exceeded, the pool is said to be exhausted. | | | Max Idle a| Number | Controls the maximum number of Mule components that can sit idle in the pool at any time. When set to a negative value, there is no limit to the number of Mule components that may be idle at one time. | | | Max Wait a| Number | Specifies the number of milliseconds to wait for a pooled component to become available when the pool is exhausted and the exhaustedAction is set to WHEN_EXHAUSTED_WAIT. | | | Min Eviction Millis a| Number | Determines the minimum amount of time an object may sit idle in the pool before it is eligible for eviction. When non-positive, no objects will be evicted from the pool due to idle time alone. | | | Eviction Check Interval Millis a| Number | Specifies the number of milliseconds between runs of the object evictor. When non-positive, no object evictor is executed. | | | Exhausted Action a| Enumeration, one of: ** WHEN_EXHAUSTED_GROW ** WHEN_EXHAUSTED_WAIT ** WHEN_EXHAUSTED_FAIL | Specifies the behavior of the Mule component pool when the pool is exhausted. Possible values are: * WHEN_EXHAUSTED_FAIL - Throws a NoSuchElementException. * WHEN_EXHAUSTED_WAIT - Blocks by invoking `Object.wait(long)` until a new or idle object is available. * WHEN_EXHAUSTED_GROW - Creates a new Mule instance and returns it, essentially making the *Max Active* value meaningless. If a positive *Max Wait* value is supplied, it blocks for at most that many milliseconds, after which a NoSuchElementException is thrown. If `maxThreadWait` is a negative value, it blocks indefinitely. | | | Initialisation Policy a| Enumeration, one of: ** INITIALISE_NONE ** INITIALISE_ONE ** INITIALISE_ALL | Determines how components in a pool should be initialized. The possible values are: * INITIALISE_NONE - Does not load any components into the pool on startup. * INITIALISE_ONE - Loads one initial component into the pool on startup. * INITIALISE_ALL - Loads all components in the pool on startup. | | | Disabled a| Boolean | Whether pooling should be disabled. | | |=== [[ExpirationPolicy]] === Expiration Policy [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Max Idle Time a| Number | A scalar time value for the maximum amount of time a dynamic configuration instance should be allowed to be idle before it's considered eligible for expiration | | | Time Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | A time unit that qualifies the maxIdleTime attribute | | |=== [[RedeliveryPolicy]] === Redelivery Policy [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Max Redelivery Count a| Number | The maximum number of times a message can be redelivered and processed unsuccessfully before triggering process-failed-message | | | Use Secure Hash a| Boolean | Whether to use a secure hash algorithm to identify a redelivered message. | | | Message Digest Algorithm a| String | The secure hashing algorithm to use. If not set, the default is SHA-256. | | | Id Expression a| String | Defines one or more expressions to use to determine when a message has been redelivered. This property may only be set if *Use Secure Hash* is `false`. | | | Object Store a| Object Store | The object store where the redelivery counter for each message is stored. | | |=== [[BulkOperationResult]] === Bulk Operation Result [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Id a| Any | | | | Items a| Array of <> | | | | Successful a| Boolean | | | |=== [[BulkItem]] === Bulk Item [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Exception a| Any | | | | Id a| Any | | | | Message a| String | | | | Payload a| Object | | | | Status Code a| String | | | | Successful a| Boolean | | | |=== [[repeatable-in-memory-iterable]] === Repeatable In Memory Iterable [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | Initial Buffer Size a| Number | The amount of instances to initially keep in memory to consume the stream and provide random access to it. If the stream contains more data than can fit into this buffer, then the buffer expands according to the *Buffer Size Increment* attribute, with an upper limit of *Max Buffer Size*. Default value is 100 instances. | | | Buffer Size Increment a| Number | This is by how much the buffer size expands if it exceeds its initial size. Setting a value of zero or lower means that the buffer should not expand, meaning that a STREAM_MAXIMUM_SIZE_EXCEEDED error is raised when the buffer gets full. Default value is 100 instances. | | | Max Buffer Size a| Number | The maximum amount of memory to use. If more than that is used then a STREAM_MAXIMUM_SIZE_EXCEEDED error is raised. A value lower than or equal to zero means no limit. | | |=== [[repeatable-file-store-iterable]] === Repeatable File Store Iterable [%header,cols=""20s,25a,30a,15a,10a""] |=== | Field | Type | Description | Default Value | Required | In Memory Objects a| Number | The maximum amount of instances to keep in memory. If more than that is required, then it starts to buffer the content on disk. | | | Buffer Unit a| Enumeration, one of: ** BYTE ** KB ** MB ** GB | The unit in which maxInMemorySize is expressed. | | |=== == See Also https://help.mulesoft.com[MuleSoft Help Center] ",12063,True,2794.384224170353,median "// Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include