text,length,is_long_context,metric_val,label_metric "/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include ""math-precomp.h"" // Precompiled headers #include #include #include #include using namespace mrpt; using namespace std; using namespace mrpt::math; // Next we declare some auxiliary functions: namespace mrpt::math { // Replaces data[1..2*nn] by its discrete Fourier transform, if isign is input // as 1; or replaces // data[1..2*nn] by nn times its inverse discrete Fourier transform, if isign is // input as -1. // data is a complex array of length nn or, equivalently, a real array of length // 2*nn. nn MUST // be an integer power of 2 (this is not checked for!). static void four1(float data[], unsigned long nn, int isign) { unsigned long n, mmax, m, j, i; double wtemp, wr, wpr, wpi, wi, theta; // Double precision for the trigonometric recurrences. float tempr, tempi; n = nn << 1; j = 1; for (i = 1; i < n; i += 2) // This is the bit-reversal section of the routine. { if (j > i) { std::swap(data[j], data[i]); // Exchange the two complex numbers. std::swap(data[j + 1], data[i + 1]); } m = nn; while (m >= 2 && j > m) { j -= m; m >>= 1; } j += m; } // Here begins the Danielson-Lanczos section of the routine. mmax = 2; while (n > mmax) // Outer loop executed log2 nn times. { unsigned long istep = mmax << 1; theta = isign * (6.28318530717959 / mmax); // Initialize the trigonometric recurrence. wtemp = sin(0.5 * theta); wpr = -2.0 * wtemp * wtemp; wpi = sin(theta); wr = 1.0; wi = 0.0; for (m = 1; m < mmax; m += 2) // Here are the two nested inner loops. { for (i = m; i <= n; i += istep) { j = i + mmax; // This is the Danielson-Lanczos formula: tempr = (float)(wr * data[j] - wi * data[j + 1]); tempi = (float)(wr * data[j + 1] + wi * data[j]); data[j] = data[i] - tempr; data[j + 1] = data[i + 1] - tempi; data[i] += tempr; data[i + 1] += tempi; } wr = (wtemp = wr) * wpr - wi * wpi + wr; // Trigonometric recurrence. wi = wi * wpr + wtemp * wpi + wi; } mmax = istep; } } // Calculates the Fourier transform of a set of n real-valued data points. // Replaces this data (which // is stored in array data[1..n]) by the positive frequency half of its complex // Fourier transform. // The real-valued first and last components of the complex transform are // returned as elements // data[1] and data[2], respectively. n must be a power of 2. This routine also // calculates the // inverse transform of a complex data array if it is the transform of real // data. (Result in this case // must be multiplied by 2/n.) static void realft(float data[], unsigned long n) { unsigned long i, i1, i2, i3, i4, np3; float c1 = 0.5, c2, h1r, h1i, h2r, h2i; double wr, wi, wpr, wpi, wtemp, theta; // Double precision for the trigonometric recurrences. theta = 3.141592653589793 / (double)(n >> 1); // Initialize the recurrence. c2 = -0.5; four1(data, n >> 1, 1); // The forward transform is here. wtemp = sin(0.5 * theta); wpr = -2.0 * wtemp * wtemp; wpi = sin(theta); wr = 1.0 + wpr; wi = wpi; np3 = n + 3; for (i = 2; i <= (n >> 2); i++) // Case i=1 done separately below. { i4 = 1 + (i3 = np3 - (i2 = 1 + (i1 = i + i - 1))); h1r = c1 * (data[i1] + data[i3]); // The two separate transforms are // separated out of data. h1i = c1 * (data[i2] - data[i4]); h2r = -c2 * (data[i2] + data[i4]); h2i = c2 * (data[i1] - data[i3]); data[i1] = (float)(h1r + wr * h2r - wi * h2i); // Here they are recombined to // form the true transform of // the original real data. data[i2] = (float)(h1i + wr * h2i + wi * h2r); data[i3] = (float)(h1r - wr * h2r + wi * h2i); data[i4] = (float)(-h1i + wr * h2i + wi * h2r); wr = (wtemp = wr) * wpr - wi * wpi + wr; // The recurrence. wi = wi * wpr + wtemp * wpi + wi; } data[1] = (h1r = data[1]) + data[2]; // Squeeze the first and last data together to get them all within the // original array. data[2] = h1r - data[2]; } /** Copyright(C) 1997 Takuya OOURA (email: ooura@mmm.t.u-tokyo.ac.jp). You may use, copy, modify this code for any purpose and without fee. You may distribute this ORIGINAL package. */ using FFT_TYPE = float; static void makewt(int nw, int* ip, FFT_TYPE* w); static void bitrv2(int n, int* ip, FFT_TYPE* a); static void cftbsub(int n, FFT_TYPE* a, FFT_TYPE* w); static void cftfsub(int n, FFT_TYPE* a, FFT_TYPE* w); static void rftfsub(int n, FFT_TYPE* a, int nc, FFT_TYPE* c); static void rftbsub(int n, FFT_TYPE* a, int nc, FFT_TYPE* c); static void cftbsub(int n, FFT_TYPE* a, FFT_TYPE* w) { int j, j1, j2, j3, k, k1, ks, l, m; FFT_TYPE wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; FFT_TYPE x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; l = 2; while ((l << 1) < n) { m = l << 2; for (j = 0; j <= l - 2; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = a[j] + a[j1]; x0i = a[j + 1] + a[j1 + 1]; x1r = a[j] - a[j1]; x1i = a[j + 1] - a[j1 + 1]; x2r = a[j2] + a[j3]; x2i = a[j2 + 1] + a[j3 + 1]; x3r = a[j2] - a[j3]; x3i = a[j2 + 1] - a[j3 + 1]; a[j] = x0r + x2r; a[j + 1] = x0i + x2i; a[j2] = x0r - x2r; a[j2 + 1] = x0i - x2i; a[j1] = x1r - x3i; a[j1 + 1] = x1i + x3r; a[j3] = x1r + x3i; a[j3 + 1] = x1i - x3r; } if (m < n) { wk1r = w[2]; for (j = m; j <= l + m - 2; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = a[j] + a[j1]; x0i = a[j + 1] + a[j1 + 1]; x1r = a[j] - a[j1]; x1i = a[j + 1] - a[j1 + 1]; x2r = a[j2] + a[j3]; x2i = a[j2 + 1] + a[j3 + 1]; x3r = a[j2] - a[j3]; x3i = a[j2 + 1] - a[j3 + 1]; a[j] = x0r + x2r; a[j + 1] = x0i + x2i; a[j2] = x2i - x0i; a[j2 + 1] = x0r - x2r; x0r = x1r - x3i; x0i = x1i + x3r; a[j1] = wk1r * (x0r - x0i); a[j1 + 1] = wk1r * (x0r + x0i); x0r = x3i + x1r; x0i = x3r - x1i; a[j3] = wk1r * (x0i - x0r); a[j3 + 1] = wk1r * (x0i + x0r); } k1 = 1; ks = -1; for (k = (m << 1); k <= n - m; k += m) { k1++; ks = -ks; wk1r = w[k1 << 1]; wk1i = w[(k1 << 1) + 1]; wk2r = ks * w[k1]; wk2i = w[k1 + ks]; wk3r = wk1r - 2 * wk2i * wk1i; wk3i = 2 * wk2i * wk1r - wk1i; for (j = k; j <= l + k - 2; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = a[j] + a[j1]; x0i = a[j + 1] + a[j1 + 1]; x1r = a[j] - a[j1]; x1i = a[j + 1] - a[j1 + 1]; x2r = a[j2] + a[j3]; x2i = a[j2 + 1] + a[j3 + 1]; x3r = a[j2] - a[j3]; x3i = a[j2 + 1] - a[j3 + 1]; a[j] = x0r + x2r; a[j + 1] = x0i + x2i; x0r -= x2r; x0i -= x2i; a[j2] = wk2r * x0r - wk2i * x0i; a[j2 + 1] = wk2r * x0i + wk2i * x0r; x0r = x1r - x3i; x0i = x1i + x3r; a[j1] = wk1r * x0r - wk1i * x0i; a[j1 + 1] = wk1r * x0i + wk1i * x0r; x0r = x1r + x3i; x0i = x1i - x3r; a[j3] = wk3r * x0r - wk3i * x0i; a[j3 + 1] = wk3r * x0i + wk3i * x0r; } } } l = m; } if (l < n) { for (j = 0; j <= l - 2; j += 2) { j1 = j + l; x0r = a[j] - a[j1]; x0i = a[j + 1] - a[j1 + 1]; a[j] += a[j1]; a[j + 1] += a[j1 + 1]; a[j1] = x0r; a[j1 + 1] = x0i; } } } static void cftfsub(int n, FFT_TYPE* a, FFT_TYPE* w) { int j, j1, j2, j3, k, k1, ks, l, m; FFT_TYPE wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; FFT_TYPE x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; l = 2; while ((l << 1) < n) { m = l << 2; for (j = 0; j <= l - 2; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = a[j] + a[j1]; x0i = a[j + 1] + a[j1 + 1]; x1r = a[j] - a[j1]; x1i = a[j + 1] - a[j1 + 1]; x2r = a[j2] + a[j3]; x2i = a[j2 + 1] + a[j3 + 1]; x3r = a[j2] - a[j3]; x3i = a[j2 + 1] - a[j3 + 1]; a[j] = x0r + x2r; a[j + 1] = x0i + x2i; a[j2] = x0r - x2r; a[j2 + 1] = x0i - x2i; a[j1] = x1r + x3i; a[j1 + 1] = x1i - x3r; a[j3] = x1r - x3i; a[j3 + 1] = x1i + x3r; } if (m < n) { wk1r = w[2]; for (j = m; j <= l + m - 2; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = a[j] + a[j1]; x0i = a[j + 1] + a[j1 + 1]; x1r = a[j] - a[j1]; x1i = a[j + 1] - a[j1 + 1]; x2r = a[j2] + a[j3]; x2i = a[j2 + 1] + a[j3 + 1]; x3r = a[j2] - a[j3]; x3i = a[j2 + 1] - a[j3 + 1]; a[j] = x0r + x2r; a[j + 1] = x0i + x2i; a[j2] = x0i - x2i; a[j2 + 1] = x2r - x0r; x0r = x1r + x3i; x0i = x1i - x3r; a[j1] = wk1r * (x0i + x0r); a[j1 + 1] = wk1r * (x0i - x0r); x0r = x3i - x1r; x0i = x3r + x1i; a[j3] = wk1r * (x0r + x0i); a[j3 + 1] = wk1r * (x0r - x0i); } k1 = 1; ks = -1; for (k = (m << 1); k <= n - m; k += m) { k1++; ks = -ks; wk1r = w[k1 << 1]; wk1i = w[(k1 << 1) + 1]; wk2r = ks * w[k1]; wk2i = w[k1 + ks]; wk3r = wk1r - 2 * wk2i * wk1i; wk3i = 2 * wk2i * wk1r - wk1i; for (j = k; j <= l + k - 2; j += 2) { j1 = j + l; j2 = j1 + l; j3 = j2 + l; x0r = a[j] + a[j1]; x0i = a[j + 1] + a[j1 + 1]; x1r = a[j] - a[j1]; x1i = a[j + 1] - a[j1 + 1]; x2r = a[j2] + a[j3]; x2i = a[j2 + 1] + a[j3 + 1]; x3r = a[j2] - a[j3]; x3i = a[j2 + 1] - a[j3 + 1]; a[j] = x0r + x2r; a[j + 1] = x0i + x2i; x0r -= x2r; x0i -= x2i; a[j2] = wk2r * x0r + wk2i * x0i; a[j2 + 1] = wk2r * x0i - wk2i * x0r; x0r = x1r + x3i; x0i = x1i - x3r; a[j1] = wk1r * x0r + wk1i * x0i; a[j1 + 1] = wk1r * x0i - wk1i * x0r; x0r = x1r - x3i; x0i = x1i + x3r; a[j3] = wk3r * x0r + wk3i * x0i; a[j3 + 1] = wk3r * x0i - wk3i * x0r; } } } l = m; } if (l < n) { for (j = 0; j <= l - 2; j += 2) { j1 = j + l; x0r = a[j] - a[j1]; x0i = a[j + 1] - a[j1 + 1]; a[j] += a[j1]; a[j + 1] += a[j1 + 1]; a[j1] = x0r; a[j1 + 1] = x0i; } } } static void makewt(int nw, int* ip, FFT_TYPE* w) { void bitrv2(int n, int* ip, FFT_TYPE* a); int nwh, j; FFT_TYPE delta, x, y; ip[0] = nw; ip[1] = 1; if (nw > 2) { nwh = nw >> 1; delta = atan(1.0f) / nwh; w[0] = 1; w[1] = 0; w[nwh] = cos(delta * nwh); w[nwh + 1] = w[nwh]; for (j = 2; j <= nwh - 2; j += 2) { x = cos(delta * j); y = sin(delta * j); w[j] = x; w[j + 1] = y; w[nw - j] = y; w[nw - j + 1] = x; } bitrv2(nw, ip + 2, w); } } /** Copyright(C) 1997 Takuya OOURA (email: ooura@mmm.t.u-tokyo.ac.jp). You may use, copy, modify this code for any purpose and without fee. You may distribute this ORIGINAL package. */ static void makect(int nc, int* ip, FFT_TYPE* c) { int nch, j; FFT_TYPE delta; ip[1] = nc; if (nc > 1) { nch = nc >> 1; delta = atan(1.0f) / nch; c[0] = 0.5f; c[nch] = 0.5f * cos(delta * nch); for (j = 1; j <= nch - 1; j++) { c[j] = 0.5f * cos(delta * j); c[nc - j] = 0.5f * sin(delta * j); } } } /** Copyright(C) 1997 Takuya OOURA (email: ooura@mmm.t.u-tokyo.ac.jp). You may use, copy, modify this code for any purpose and without fee. You may distribute this ORIGINAL package. */ static void bitrv2(int n, int* ip, FFT_TYPE* a) { int j, j1, k, k1, l, m, m2; FFT_TYPE xr, xi; ip[0] = 0; l = n; m = 1; while ((m << 2) < l) { l >>= 1; for (j = 0; j <= m - 1; j++) { ip[m + j] = ip[j] + l; } m <<= 1; } if ((m << 2) > l) { for (k = 1; k <= m - 1; k++) { for (j = 0; j <= k - 1; j++) { j1 = (j << 1) + ip[k]; k1 = (k << 1) + ip[j]; xr = a[j1]; xi = a[j1 + 1]; a[j1] = a[k1]; a[j1 + 1] = a[k1 + 1]; a[k1] = xr; a[k1 + 1] = xi; } } } else { m2 = m << 1; for (k = 1; k <= m - 1; k++) { for (j = 0; j <= k - 1; j++) { j1 = (j << 1) + ip[k]; k1 = (k << 1) + ip[j]; xr = a[j1]; xi = a[j1 + 1]; a[j1] = a[k1]; a[j1 + 1] = a[k1 + 1]; a[k1] = xr; a[k1 + 1] = xi; j1 += m2; k1 += m2; xr = a[j1]; xi = a[j1 + 1]; a[j1] = a[k1]; a[j1 + 1] = a[k1 + 1]; a[k1] = xr; a[k1 + 1] = xi; } } } } /** Copyright(C) 1997 Takuya OOURA (email: ooura@mmm.t.u-tokyo.ac.jp). You may use, copy, modify this code for any purpose and without fee. You may distribute this ORIGINAL package. */ static void cdft(int n, int isgn, FFT_TYPE* a, int* ip, FFT_TYPE* w) { if (n > (ip[0] << 2)) { makewt(n >> 2, ip, w); } if (n > 4) { bitrv2(n, ip + 2, a); } if (isgn < 0) { cftfsub(n, a, w); } else { cftbsub(n, a, w); } } static void rftfsub(int n, FFT_TYPE* a, int nc, FFT_TYPE* c) { int j, k, kk, ks; FFT_TYPE wkr, wki, xr, xi, yr, yi; ks = (nc << 2) / n; kk = 0; for (k = (n >> 1) - 2; k >= 2; k -= 2) { j = n - k; kk += ks; wkr = 0.5f - c[kk]; wki = c[nc - kk]; xr = a[k] - a[j]; xi = a[k + 1] + a[j + 1]; yr = wkr * xr + wki * xi; yi = wkr * xi - wki * xr; a[k] -= yr; a[k + 1] -= yi; a[j] += yr; a[j + 1] -= yi; } } static void rdft(int n, int isgn, FFT_TYPE* a, int* ip, FFT_TYPE* w) { int nw, nc; FFT_TYPE xi; nw = ip[0]; if (n > (nw << 2)) { nw = n >> 2; makewt(nw, ip, w); } nc = ip[1]; if (n > (nc << 2)) { nc = n >> 2; makect(nc, ip, w + nw); } if (isgn < 0) { a[1] = 0.5f * (a[0] - a[1]); a[0] -= a[1]; if (n > 4) { rftfsub(n, a, nc, w + nw); bitrv2(n, ip + 2, a); } cftfsub(n, a, w); } else { if (n > 4) { bitrv2(n, ip + 2, a); } cftbsub(n, a, w); if (n > 4) { rftbsub(n, a, nc, w + nw); } xi = a[0] - a[1]; a[0] += a[1]; a[1] = xi; } } static void rftbsub(int n, FFT_TYPE* a, int nc, FFT_TYPE* c) { int j, k, kk, ks; FFT_TYPE wkr, wki, xr, xi, yr, yi; ks = (nc << 2) / n; kk = 0; for (k = (n >> 1) - 2; k >= 2; k -= 2) { j = n - k; kk += ks; wkr = 0.5f - c[kk]; wki = c[nc - kk]; xr = a[k] - a[j]; xi = a[k + 1] + a[j + 1]; yr = wkr * xr - wki * xi; yi = wkr * xi + wki * xr; a[k] -= yr; a[k + 1] -= yi; a[j] += yr; a[j + 1] -= yi; } } /** Copyright(C) 1997 Takuya OOURA (email: ooura@mmm.t.u-tokyo.ac.jp). You may use, copy, modify this code for any purpose and without fee. You may distribute this ORIGINAL package. -------- Real DFT / Inverse of Real DFT -------- [definition] RDFT R[k1][k2] = sum_j1=0^n1-1 sum_j2=0^n2-1 a[j1][j2] * cos(2*pi*j1*k1/n1 + 2*pi*j2*k2/n2), 0<=k1 IRDFT (excluding scale) a[k1][k2] = (1/2) * sum_j1=0^n1-1 sum_j2=0^n2-1 (R[j1][j2] * cos(2*pi*j1*k1/n1 + 2*pi*j2*k2/n2) + I[j1][j2] * sin(2*pi*j1*k1/n1 + 2*pi*j2*k2/n2)), 0<=k1 ip[0] = 0; // first time only rdft2d(n1, n2, 1, a, t, ip, w); ip[0] = 0; // first time only rdft2d(n1, n2, -1, a, t, ip, w); [parameters] n1 :data length (int) n1 >= 2, n1 = power of 2 n2 :data length (int) n2 >= 2, n2 = power of 2 a[0...n1-1][0...n2-1] :input/output data (FFT_TYPE **) output data a[k1][2*k2] = R[k1][k2] = R[n1-k1][n2-k2], a[k1][2*k2+1] = I[k1][k2] = -I[n1-k1][n2-k2], 0 input data a[j1][2*j2] = R[j1][j2] = R[n1-j1][n2-j2], a[j1][2*j2+1] = I[j1][j2] = -I[n1-j1][n2-j2], 0= 2+sqrt(n) ; if n % 4 == 0 2+sqrt(n/2); otherwise (n = max(n1, n2/2)) ip[0],ip[1] are pointers of the cos/sin table. w[0...*] :cos/sin table (FFT_TYPE *) length of w >= max(n1/2, n2/4) + n2/4 w[],ip[] are initialized if ip[0] == 0. [remark] Inverse of rdft2d(n1, n2, 1, a, t, ip, w); is rdft2d(n1, n2, -1, a, t, ip, w); for (j1 = 0; j1 <= n1 - 1; j1++) { for (j2 = 0; j2 <= n2 - 1; j2++) { a[j1][j2] *= 2.0 / (n1 * n2); } } */ static void rdft2d( int n1, int n2, int isgn, FFT_TYPE** a, FFT_TYPE* t, int* ip, FFT_TYPE* w) { int n, nw, nc, n1h, i, j, i2; FFT_TYPE xi; n = n1 << 1; if (n < n2) { n = n2; } nw = ip[0]; if (n > (nw << 2)) { nw = n >> 2; makewt(nw, ip, w); } nc = ip[1]; if (n2 > (nc << 2)) { nc = n2 >> 2; makect(nc, ip, w + nw); } n1h = n1 >> 1; if (isgn < 0) { for (i = 1; i <= n1h - 1; i++) { j = n1 - i; xi = a[i][0] - a[j][0]; a[i][0] += a[j][0]; a[j][0] = xi; xi = a[j][1] - a[i][1]; a[i][1] += a[j][1]; a[j][1] = xi; } for (j = 0; j <= n2 - 2; j += 2) { for (i = 0; i <= n1 - 1; i++) { i2 = i << 1; t[i2] = a[i][j]; t[i2 + 1] = a[i][j + 1]; } cdft(n1 << 1, isgn, t, ip, w); for (i = 0; i <= n1 - 1; i++) { i2 = i << 1; a[i][j] = t[i2]; a[i][j + 1] = t[i2 + 1]; } } for (i = 0; i <= n1 - 1; i++) { rdft(n2, isgn, a[i], ip, w); } } else { for (i = 0; i <= n1 - 1; i++) { rdft(n2, isgn, a[i], ip, w); } for (j = 0; j <= n2 - 2; j += 2) { for (i = 0; i <= n1 - 1; i++) { i2 = i << 1; t[i2] = a[i][j]; t[i2 + 1] = a[i][j + 1]; } cdft(n1 << 1, isgn, t, ip, w); for (i = 0; i <= n1 - 1; i++) { i2 = i << 1; a[i][j] = t[i2]; a[i][j + 1] = t[i2 + 1]; } } for (i = 1; i <= n1h - 1; i++) { j = n1 - i; a[j][0] = 0.5f * (a[i][0] - a[j][0]); a[i][0] -= a[j][0]; a[j][1] = 0.5f * (a[i][1] + a[j][1]); a[i][1] -= a[j][1]; } } } /** Copyright(C) 1997 Takuya OOURA (email: ooura@mmm.t.u-tokyo.ac.jp). You may use, copy, modify this code for any purpose and without fee. You may distribute this ORIGINAL package. -------- Complex DFT (Discrete Fourier Transform) -------- [definition] X[k1][k2] = sum_j1=0^n1-1 sum_j2=0^n2-1 x[j1][j2] * exp(2*pi*i*j1*k1/n1) * exp(2*pi*i*j2*k2/n2), 0<=k1 X[k1][k2] = sum_j1=0^n1-1 sum_j2=0^n2-1 x[j1][j2] * exp(-2*pi*i*j1*k1/n1) * exp(-2*pi*i*j2*k2/n2), 0<=k1 ip[0] = 0; // first time only cdft2d(n1, 2*n2, 1, a, t, ip, w); ip[0] = 0; // first time only cdft2d(n1, 2*n2, -1, a, t, ip, w); [parameters] n1 :data length (int) n1 >= 1, n1 = power of 2 2*n2 :data length (int) n2 >= 1, n2 = power of 2 a[0...n1-1][0...2*n2-1] :input/output data (double **) input data a[j1][2*j2] = Re(x[j1][j2]), a[j1][2*j2+1] = Im(x[j1][j2]), 0<=j1= 2+sqrt(n) ; if n % 4 == 0 2+sqrt(n/2); otherwise (n = max(n1, n2)) ip[0],ip[1] are pointers of the cos/sin table. w[0...*] :cos/sin table (double *) length of w >= max(n1/2, n2/2) w[],ip[] are initialized if ip[0] == 0. [remark] Inverse of cdft2d(n1, 2*n2, -1, a, t, ip, w); is cdft2d(n1, 2*n2, 1, a, t, ip, w); for (j1 = 0; j1 <= n1 - 1; j1++) { for (j2 = 0; j2 <= 2 * n2 - 1; j2++) { a[j1][j2] *= 1.0 / (n1 * n2); } } */ static void cdft2d( int n1, int n2, int isgn, FFT_TYPE** a, FFT_TYPE* t, int* ip, FFT_TYPE* w) { void makewt(int nw, int* ip, FFT_TYPE* w); void cdft(int n, int isgn, FFT_TYPE* a, int* ip, FFT_TYPE* w); int n, i, j, i2; n = n1 << 1; if (n < n2) { n = n2; } if (n > (ip[0] << 2)) { makewt(n >> 2, ip, w); } for (i = 0; i <= n1 - 1; i++) { cdft(n2, isgn, a[i], ip, w); } for (j = 0; j <= n2 - 2; j += 2) { for (i = 0; i <= n1 - 1; i++) { i2 = i << 1; t[i2] = a[i][j]; t[i2 + 1] = a[i][j + 1]; } cdft(n1 << 1, isgn, t, ip, w); for (i = 0; i <= n1 - 1; i++) { i2 = i << 1; a[i][j] = t[i2]; a[i][j + 1] = t[i2 + 1]; } } } } // namespace mrpt::math void mrpt::math::fft_real( CVectorFloat& in_realData, CVectorFloat& out_FFT_Re, CVectorFloat& out_FFT_Im, CVectorFloat& out_FFT_Mag) { MRPT_START unsigned long n = (unsigned long)in_realData.size(); // TODO: Test data lenght is 2^N... CVectorFloat auxVect(n + 1); memcpy(&auxVect[1], &in_realData[0], n * sizeof(auxVect[0])); realft(&auxVect[0], n); unsigned int n_2 = 1 + (n / 2); out_FFT_Re.resize(n_2); out_FFT_Im.resize(n_2); out_FFT_Mag.resize(n_2); for (unsigned int i = 0; i < n_2; i++) { if (i == (n_2 - 1)) out_FFT_Re[i] = auxVect[2]; else out_FFT_Re[i] = auxVect[1 + i * 2]; if (i == 0 || i == (n_2 - 1)) out_FFT_Im[i] = 0; else out_FFT_Im[i] = auxVect[1 + i * 2 + 1]; out_FFT_Mag[i] = std::sqrt(square(out_FFT_Re[i]) + square(out_FFT_Im[i])); } MRPT_END } void math::dft2_real( const CMatrixFloat& in_data, CMatrixFloat& out_real, CMatrixFloat& out_imag) { MRPT_START size_t i, j; using float_ptr = FFT_TYPE*; // The dimensions: size_t dim1 = in_data.rows(); size_t dim2 = in_data.cols(); // Transform to format compatible with C routines: // ------------------------------------------------------------ FFT_TYPE** a; FFT_TYPE* t; int* ip; FFT_TYPE* w; // Reserve memory and copy data: // -------------------------------------- a = new float_ptr[dim1]; for (i = 0; i < dim1; i++) { a[i] = new FFT_TYPE[dim2]; for (j = 0; j < dim2; j++) a[i][j] = in_data.get_unsafe(i, j); } t = new FFT_TYPE[2 * dim1 + 20]; ip = new int[(int)ceil(20 + 2 + sqrt((FFT_TYPE)max(dim1, dim2 / 2)))]; ip[0] = 0; w = new FFT_TYPE[max(dim1 / 2, dim2 / 4) + dim2 / 4 + 20]; // Do the job! // -------------------------------------- rdft2d((int)dim1, (int)dim2, 1, a, t, ip, w); // Transform back to MRPT matrix format: // -------------------------------------- out_real.setSize(dim1, dim2); out_imag.setSize(dim1, dim2); // a[k1][2*k2] = R[k1][k2] = R[n1-k1][n2-k2], // a[k1][2*k2+1] = I[k1][k2] = -I[n1-k1][n2-k2], // 0 -1: DFT, 1:IDFT ---------------------------------------------------------------*/ static void myGeneralDFT( int sign, const CMatrixFloat& in_real, const CMatrixFloat& in_imag, CMatrixFloat& out_real, CMatrixFloat& out_imag) { ASSERT_(in_real.rows() == in_imag.rows()); ASSERT_(in_real.cols() == in_imag.cols()); // The dimensions: size_t dim1 = in_real.rows(); size_t dim2 = in_real.cols(); size_t k1, k2, n1, n2; float w_r, w_i; float ang1 = (float)(sign * M_2PI / dim1); float ang2 = (float)(sign * M_2PI / dim2); float phase; float R, I; float scale = sign == 1 ? (1.0f / (dim1 * dim2)) : 1; out_real.setSize(dim1, dim2); out_imag.setSize(dim1, dim2); for (k1 = 0; k1 < dim1; k1++) { for (k2 = 0; k2 < dim2; k2++) { R = I = 0; // Accum: for (n1 = 0; n1 < dim1; n1++) { phase = ang1 * n1 * k1; for (n2 = 0; n2 < dim2; n2++) { w_r = cos(phase); w_i = sin(phase); R += w_r * in_real.get_unsafe(n1, n2) - w_i * in_imag.get_unsafe(n1, n2); I += w_i * in_real.get_unsafe(n1, n2) + w_r * in_imag.get_unsafe(n1, n2); phase += ang2 * k2; } // end for k2 } // end for k1 // Save result: out_real.set_unsafe(k1, k2, R * scale); out_imag.set_unsafe(k1, k2, I * scale); } // end for k2 } // end for k1 } /*--------------------------------------------------------------- dft2_complex ---------------------------------------------------------------*/ void math::dft2_complex( const CMatrixFloat& in_real, const CMatrixFloat& in_imag, CMatrixFloat& out_real, CMatrixFloat& out_imag) { MRPT_START ASSERT_(in_real.rows() == in_imag.rows()); ASSERT_(in_real.cols() == in_imag.cols()); // The dimensions: size_t dim1 = in_real.rows(); size_t dim2 = in_real.cols(); size_t i, j; bool dim1IsPower2 = (mrpt::round2up(dim1) == dim1); bool dim2IsPower2 = (mrpt::round2up(dim2) == dim2); // FFT or DFT?? if (dim1IsPower2 && dim2IsPower2) { // ---------------------------------------- // Optimized FFT: // ---------------------------------------- using float_ptr = FFT_TYPE*; // Transform to format compatible with C routines: // ------------------------------------------------------------ static FFT_TYPE** a = nullptr; static FFT_TYPE* t = nullptr; static int* ip = nullptr; static FFT_TYPE* w = nullptr; // Reserve memory // -------------------------------------- static int alreadyInitSize1 = -1, alreadyInitSize2 = -1; if (alreadyInitSize1 != (int)dim1 || alreadyInitSize2 != (int)dim2) { // Create/realloc buffers: if (a) { for (i = 0; i < dim1; i++) delete[] a[i]; delete[] a; } if (ip) delete[] ip; if (t) delete[] t; if (w) delete[] w; alreadyInitSize1 = (int)dim1; alreadyInitSize2 = (int)dim2; a = new float_ptr[dim1]; for (i = 0; i < dim1; i++) a[i] = new FFT_TYPE[2 * dim2]; t = new FFT_TYPE[2 * dim1 + 20]; ip = new int[(int)ceil( 20 + 2 + sqrt((FFT_TYPE)max(dim1, dim2 / 2)))]; ip[0] = 0; w = new FFT_TYPE[max(dim1 / 2, dim2 / 4) + dim2 / 4 + 20]; } // and copy data: // -------------------------------------- for (i = 0; i < dim1; i++) for (j = 0; j < dim2; j++) { a[i][2 * j + 0] = in_real.get_unsafe(i, j); a[i][2 * j + 1] = in_imag.get_unsafe(i, j); } // Do the job! // -------------------------------------- cdft2d((int)dim1, (int)(2 * dim2), 1, a, t, ip, w); // Transform back to MRPT matrix format: // -------------------------------------- out_real.setSize(dim1, dim2); out_imag.setSize(dim1, dim2); // a[k1][2*k2] = Re(X[k1][k2]), // a[k1][2*k2+1] = Im(X[k1][k2]), // 0<=k1 #include #include struct coeffGroupRDStats { int iNNZbeforePos0; double d64CodedLevelandDist; // distortion and level cost only double d64UncodedDist; // all zero coded block distortion double d64SigCost; double d64SigCost_0; }; //! \\ingroup CommonLib //! \\{ // ==================================================================================================================== // Constants // ==================================================================================================================== // ==================================================================================================================== // Static functions // ==================================================================================================================== // ==================================================================================================================== // QuantRDOQ class member functions // ==================================================================================================================== QuantRDOQ::QuantRDOQ( const Quant* other ) : Quant( other ) { const QuantRDOQ *rdoq = dynamic_cast( other ); CHECK( other && !rdoq, ""The RDOQ cast must be successfull!"" ); #if HEVC_USE_SCALING_LISTS xInitScalingList( rdoq ); #endif } QuantRDOQ::~QuantRDOQ() { #if HEVC_USE_SCALING_LISTS xDestroyScalingList(); #endif } /** Get the best level in RD sense * * \\returns best quantized transform level for given scan position * * This method calculates the best quantized transform level for a given scan position. */ #if JVET_K0072 inline uint32_t QuantRDOQ::xGetCodedLevel( double& rd64CodedCost, double& rd64CodedCost0, double& rd64CodedCostSig, Intermediate_Int lLevelDouble, uint32_t uiMaxAbsLevel, const BinFracBits* fracBitsSig, const BinFracBits& fracBitsPar, const BinFracBits& fracBitsGt1, const BinFracBits& fracBitsGt2, uint16_t ui16AbsGoRice, int iQBits, double errorScale, bool bLast, bool useLimitedPrefixLength, const int maxLog2TrDynamicRange ) const { double dCurrCostSig = 0; uint32_t uiBestAbsLevel = 0; if( !bLast && uiMaxAbsLevel < 3 ) { rd64CodedCostSig = xGetRateSigCoef( *fracBitsSig, 0 ); rd64CodedCost = rd64CodedCost0 + rd64CodedCostSig; if( uiMaxAbsLevel == 0 ) { return uiBestAbsLevel; } } else { rd64CodedCost = MAX_DOUBLE; } if( !bLast ) { dCurrCostSig = xGetRateSigCoef( *fracBitsSig, 1 ); } uint32_t uiMinAbsLevel = ( uiMaxAbsLevel > 1 ? uiMaxAbsLevel - 1 : 1 ); for( int uiAbsLevel = uiMaxAbsLevel; uiAbsLevel >= uiMinAbsLevel ; uiAbsLevel-- ) { double dErr = double( lLevelDouble - ( Intermediate_Int(uiAbsLevel) << iQBits ) ); double dCurrCost = dErr * dErr * errorScale + xGetICost( xGetICRate( uiAbsLevel, fracBitsPar, fracBitsGt1, fracBitsGt2, ui16AbsGoRice, useLimitedPrefixLength, maxLog2TrDynamicRange ) ); dCurrCost += dCurrCostSig; if( dCurrCost < rd64CodedCost ) { uiBestAbsLevel = uiAbsLevel; rd64CodedCost = dCurrCost; rd64CodedCostSig = dCurrCostSig; } } return uiBestAbsLevel; } #else inline uint32_t QuantRDOQ::xGetCodedLevel ( double& rd64CodedCost, double& rd64CodedCost0, double& rd64CodedCostSig, Intermediate_Int lLevelDouble, uint32_t uiMaxAbsLevel, const BinFracBits* fracBitsSig, const BinFracBits& fracBitsOne, const BinFracBits& fracBitsAbs, #if JEM_TOOLS const bool useAltRC, #endif uint16_t ui16AbsGoRice, uint32_t c1Idx, uint32_t c2Idx, int iQBits, double errorScale, bool bLast, bool useLimitedPrefixLength, const int maxLog2TrDynamicRange ) const { double dCurrCostSig = 0; uint32_t uiBestAbsLevel = 0; if( !bLast && uiMaxAbsLevel < 3 ) { rd64CodedCostSig = xGetRateSigCoef( *fracBitsSig, 0 ); rd64CodedCost = rd64CodedCost0 + rd64CodedCostSig; if( uiMaxAbsLevel == 0 ) { return uiBestAbsLevel; } } else { rd64CodedCost = MAX_DOUBLE; } if( !bLast ) { dCurrCostSig = xGetRateSigCoef( *fracBitsSig, 1 ); } uint32_t uiMinAbsLevel = ( uiMaxAbsLevel > 1 ? uiMaxAbsLevel - 1 : 1 ); for( int uiAbsLevel = uiMaxAbsLevel; uiAbsLevel >= uiMinAbsLevel ; uiAbsLevel-- ) { double dErr = double( lLevelDouble - ( Intermediate_Int(uiAbsLevel) << iQBits ) ); #if JEM_TOOLS double dCurrCost = dErr * dErr * errorScale + xGetICost( xGetICRate( uiAbsLevel, fracBitsOne, fracBitsAbs, useAltRC, ui16AbsGoRice, c1Idx, c2Idx, useLimitedPrefixLength, maxLog2TrDynamicRange ) ); #else double dCurrCost = dErr * dErr * errorScale + xGetICost( xGetICRate( uiAbsLevel, fracBitsOne, fracBitsAbs, ui16AbsGoRice, c1Idx, c2Idx, useLimitedPrefixLength, maxLog2TrDynamicRange ) ); #endif dCurrCost += dCurrCostSig; if( dCurrCost < rd64CodedCost ) { uiBestAbsLevel = uiAbsLevel; rd64CodedCost = dCurrCost; rd64CodedCostSig = dCurrCostSig; } } return uiBestAbsLevel; } #endif /** Calculates the cost for specific absolute transform level * \\param uiAbsLevel scaled quantized level * \\param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC) * \\param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC) * \\param ui16AbsGoRice Rice parameter for coeff_abs_level_minus3 * \\param c1Idx * \\param c2Idx * \\param useLimitedPrefixLength * \\param maxLog2TrDynamicRange * \\returns cost of given absolute transform level */ #if JVET_K0072 inline int QuantRDOQ::xGetICRate( const uint32_t uiAbsLevel, const BinFracBits& fracBitsPar, const BinFracBits& fracBitsGt1, const BinFracBits& fracBitsGt2, const uint16_t ui16AbsGoRice, const bool useLimitedPrefixLength, const int maxLog2TrDynamicRange ) const { int iRate = int( xGetIEPRate() ); // cost of sign bit if( uiAbsLevel >= 5 ) { uint32_t symbol = ( uiAbsLevel - 5 ) >> 1; uint32_t length; const int threshold = g_auiGoRiceRange[ui16AbsGoRice]; if( symbol < ( threshold << ui16AbsGoRice ) ) { length = symbol >> ui16AbsGoRice; iRate += ( length + 1 + ui16AbsGoRice ) << SCALE_BITS; } else if( useLimitedPrefixLength ) { const uint32_t maximumPrefixLength = ( 32 - ( COEF_REMAIN_BIN_REDUCTION + maxLog2TrDynamicRange ) ); uint32_t prefixLength = 0; uint32_t suffix = ( symbol >> ui16AbsGoRice ) - COEF_REMAIN_BIN_REDUCTION; while( ( prefixLength < maximumPrefixLength ) && ( suffix > ( ( 2 << prefixLength ) - 2 ) ) ) { prefixLength++; } const uint32_t suffixLength = ( prefixLength == maximumPrefixLength ) ? ( maxLog2TrDynamicRange - ui16AbsGoRice ) : ( prefixLength + 1/*separator*/ ); iRate += ( COEF_REMAIN_BIN_REDUCTION + prefixLength + suffixLength + ui16AbsGoRice ) << SCALE_BITS; } else { length = ui16AbsGoRice; symbol = symbol - ( threshold << ui16AbsGoRice ); while( symbol >= ( 1 << length ) ) { symbol -= ( 1 << ( length++ ) ); } iRate += ( threshold + length + 1 - ui16AbsGoRice + length ) << SCALE_BITS; } iRate += fracBitsPar.intBits[( uiAbsLevel - 1 ) & 1]; iRate += fracBitsGt1.intBits[1]; iRate += fracBitsGt2.intBits[1]; } else if( uiAbsLevel == 1 ) { iRate += fracBitsPar.intBits[0]; iRate += fracBitsGt1.intBits[0]; } else if( uiAbsLevel == 2 ) { iRate += fracBitsPar.intBits[1]; iRate += fracBitsGt1.intBits[0]; } else if( uiAbsLevel == 3 ) { iRate += fracBitsPar.intBits[0]; iRate += fracBitsGt1.intBits[1]; iRate += fracBitsGt2.intBits[0]; } else if( uiAbsLevel == 4 ) { iRate += fracBitsPar.intBits[1]; iRate += fracBitsGt1.intBits[1]; iRate += fracBitsGt2.intBits[0]; } else { iRate = 0; } return iRate; } #else inline int QuantRDOQ::xGetICRate ( const uint32_t uiAbsLevel, const BinFracBits& fracBitsOne, const BinFracBits& fracBitsAbs, #if JEM_TOOLS const bool useAltRC, #endif const uint16_t ui16AbsGoRice, const uint32_t c1Idx, const uint32_t c2Idx, const bool useLimitedPrefixLength, const int maxLog2TrDynamicRange ) const { int iRate = int(xGetIEPRate()); // cost of sign bit uint32_t baseLevel = (c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx < C2FLAG_NUMBER)) : 1; if ( uiAbsLevel >= baseLevel ) { uint32_t symbol = uiAbsLevel - baseLevel; uint32_t length; #if JEM_TOOLS const int threshold = useAltRC ? g_auiGoRiceRange[ ui16AbsGoRice ] : COEF_REMAIN_BIN_REDUCTION; #else const int threshold = COEF_REMAIN_BIN_REDUCTION; #endif if( symbol < ( threshold << ui16AbsGoRice ) ) { length = symbol>>ui16AbsGoRice; iRate += (length+1+ui16AbsGoRice)<< SCALE_BITS; } else if (useLimitedPrefixLength) { const uint32_t maximumPrefixLength = (32 - (COEF_REMAIN_BIN_REDUCTION + maxLog2TrDynamicRange)); uint32_t prefixLength = 0; uint32_t suffix = (symbol >> ui16AbsGoRice) - COEF_REMAIN_BIN_REDUCTION; while ((prefixLength < maximumPrefixLength) && (suffix > ((2 << prefixLength) - 2))) { prefixLength++; } const uint32_t suffixLength = (prefixLength == maximumPrefixLength) ? (maxLog2TrDynamicRange - ui16AbsGoRice) : (prefixLength + 1/*separator*/); iRate += (COEF_REMAIN_BIN_REDUCTION + prefixLength + suffixLength + ui16AbsGoRice) << SCALE_BITS; } else { length = ui16AbsGoRice; symbol = symbol - ( threshold << ui16AbsGoRice); while (symbol >= (1< 3 ) { Cost += xGetIEPRate() * ((CtxX-2)>>1); } if( CtxY > 3 ) { Cost += xGetIEPRate() * ((CtxY-2)>>1); } return xGetICost( Cost ); } inline double QuantRDOQ::xGetRateSigCoef( const BinFracBits& fracBitsSig, unsigned uiSignificance ) const { return xGetICost( fracBitsSig.intBits[uiSignificance] ); } /** Get the cost for a specific rate * \\param dRate rate of a bit * \\returns cost at the specific rate */ inline double QuantRDOQ::xGetICost ( double dRate ) const { return m_dLambda * dRate; } /** Get the cost of an equal probable bit * \\returns cost of equal probable bit */ inline double QuantRDOQ::xGetIEPRate ( ) const { return 32768; } #if HEVC_USE_SCALING_LISTS /** set quantized matrix coefficient for encode * \\param scalingList quantized matrix address * \\param format chroma format * \\param maxLog2TrDynamicRange * \\param bitDepths reference to bit depth array for all channels */ void QuantRDOQ::setScalingList(ScalingList *scalingList, const int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths) { Quant::setScalingList( scalingList, maxLog2TrDynamicRange, bitDepths ); const int minimumQp = 0; const int maximumQp = SCALING_LIST_REM_NUM; for(uint32_t size = 0; size < SCALING_LIST_SIZE_NUM; size++) { for(uint32_t list = 0; list < SCALING_LIST_NUM; list++) { for(int qp = minimumQp; qp < maximumQp; qp++) { // xSetScalingListEnc(scalingList,list,size,qp); // xSetScalingListDec(*scalingList,list,size,qp); xSetErrScaleCoeff(list,size, size,qp,maxLog2TrDynamicRange, bitDepths); } } } } #if HM_QTBT_AS_IN_JEM_QUANT #endif #else double QuantRDOQ::xGetErrScaleCoeff( SizeType width, SizeType height, int qp, const int maxLog2TrDynamicRange, const int channelBitDepth ) { const int iTransformShift = getTransformShift(channelBitDepth, Size(width, height), maxLog2TrDynamicRange); #if HM_QTBT_AS_IN_JEM_QUANT double dErrScale = (double)( 1 << SCALE_BITS ); // Compensate for scaling of bitcount in Lagrange cost function bool needsSrqt2 = TU::needsBlockSizeTrafoScale( Size(width, height) );// ( ( (sizeX+sizeY) & 1 ) !=0 ); double dTransShift = (double)iTransformShift + ( needsSrqt2 ? -0.5 : 0.0 ); dErrScale = dErrScale*pow( 2.0, ( -2.0*dTransShift ) ); // Compensate for scaling through forward transform int QStep = ( needsSrqt2 ? ( ( g_quantScales[qp] * 181 ) >> 7 ) : g_quantScales[qp] ); #if DISTORTION_LAMBDA_BUGFIX double finalErrScale = dErrScale / QStep / QStep / (1 << (DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth) << 1)); #else double finalErrScale = dErrScale / QStep / QStep / (1 << DISTORTION_PRECISION_ADJUSTMENT(2 * (channelBitDepth - 8))); #endif #else #if DISTORTION_LAMBDA_BUGFIX int errShift = SCALE_BITS - ((iTransformShift + DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth)) << 1); #else int errShift = SCALE_BITS - ( ( iTransformShift + DISTORTION_PRECISION_ADJUSTMENT( channelBitDepth - 8 ) ) << 1 ); #endif double dErrScale = exp2( double( errShift ) ); double finalErrScale = dErrScale / double( g_quantScales[qp] * g_quantScales[qp] ); #endif return finalErrScale; } #endif #if HEVC_USE_SCALING_LISTS /** set error scale coefficients * \\param list list ID * \\param size * \\param qp quantization parameter * \\param maxLog2TrDynamicRange * \\param bitDepths reference to bit depth array for all channels */ void QuantRDOQ::xSetErrScaleCoeff( uint32_t list, uint32_t sizeX, uint32_t sizeY, int qp, const int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths ) { const int width = g_scalingListSizeX[sizeX]; const int height = g_scalingListSizeX[sizeY]; const ChannelType channelType = ( ( list == 0 ) || ( list == MAX_NUM_COMPONENT ) ) ? CHANNEL_TYPE_LUMA : CHANNEL_TYPE_CHROMA; const int channelBitDepth = bitDepths.recon[channelType]; const int iTransformShift = getTransformShift( channelBitDepth, Size( g_scalingListSizeX[sizeX], g_scalingListSizeX[sizeY] ), maxLog2TrDynamicRange[channelType] ); // Represents scaling through forward transform uint32_t i, uiMaxNumCoeff = width * height; int *piQuantcoeff; double *pdErrScale; piQuantcoeff = getQuantCoeff( list, qp, sizeX, sizeY ); pdErrScale = xGetErrScaleCoeff( list, sizeX, sizeY, qp ); #if HM_QTBT_AS_IN_JEM_QUANT double dErrScale = (double)( 1 << SCALE_BITS ); // Compensate for scaling of bitcount in Lagrange cost function bool needsSrqt2 = TU::needsBlockSizeTrafoScale( Size( g_scalingListSizeX[sizeX], g_scalingListSizeX[sizeY] ) );// ( ( (sizeX+sizeY) & 1 ) !=0 ); double dTransShift = (double)iTransformShift + ( needsSrqt2 ? -0.5 : 0.0 ); dErrScale = dErrScale*pow( 2.0, ( -2.0*dTransShift ) ); // Compensate for scaling through forward transform for( i = 0; i < uiMaxNumCoeff; i++ ) { #if DISTORTION_LAMBDA_BUGFIX pdErrScale[i] = dErrScale / piQuantcoeff[i] / piQuantcoeff[i] / (1 << (DISTORTION_PRECISION_ADJUSTMENT(bitDepths.recon[channelType]) << 1)); #else pdErrScale[i] = dErrScale / piQuantcoeff[i] / piQuantcoeff[i] / ( 1 << DISTORTION_PRECISION_ADJUSTMENT( 2 * ( bitDepths.recon[channelType] - 8 ) ) ); #endif } int QStep = ( needsSrqt2 ? ( ( g_quantScales[qp] * 181 ) >> 7 ) : g_quantScales[qp] ); #if DISTORTION_LAMBDA_BUGFIX xGetErrScaleCoeffNoScalingList(list, sizeX, sizeY, qp) = dErrScale / QStep / QStep / (1 << (DISTORTION_PRECISION_ADJUSTMENT(bitDepths.recon[channelType]) << 1)); #else xGetErrScaleCoeffNoScalingList( list, sizeX, sizeY, qp ) = dErrScale / QStep / QStep / ( 1 << DISTORTION_PRECISION_ADJUSTMENT( 2 * ( bitDepths.recon[channelType] - 8 ) ) ); #endif #else #if DISTORTION_LAMBDA_BUGFIX int errShift = SCALE_BITS - ((iTransformShift + DISTORTION_PRECISION_ADJUSTMENT(bitDepths.recon[channelType])) << 1); #else int errShift = SCALE_BITS - ( ( iTransformShift + DISTORTION_PRECISION_ADJUSTMENT( bitDepths.recon[channelType] - 8 ) ) << 1 ); #endif double dErrScale = exp2( double( errShift ) ); for( i = 0; i < uiMaxNumCoeff; i++ ) { pdErrScale[i] = dErrScale / double( piQuantcoeff[i] * piQuantcoeff[i] ); } xGetErrScaleCoeffNoScalingList( list, sizeX, sizeY, qp ) = dErrScale / double( g_quantScales[qp] * g_quantScales[qp] ); #endif } /** set flat matrix value to quantized coefficient */ void QuantRDOQ::setFlatScalingList(const int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE], const BitDepths &bitDepths) { Quant::setFlatScalingList( maxLog2TrDynamicRange, bitDepths ); const int minimumQp = 0; const int maximumQp = SCALING_LIST_REM_NUM; for(uint32_t sizeX = 0; sizeX < SCALING_LIST_SIZE_NUM; sizeX++) { for(uint32_t sizeY = 0; sizeY < SCALING_LIST_SIZE_NUM; sizeY++) { for(uint32_t list = 0; list < SCALING_LIST_NUM; list++) { for(int qp = minimumQp; qp < maximumQp; qp++) { xSetErrScaleCoeff( list, sizeX, sizeY, qp, maxLog2TrDynamicRange, bitDepths ); } } } } } /** initialization process of scaling list array */ void QuantRDOQ::xInitScalingList( const QuantRDOQ* other ) { m_isErrScaleListOwner = other == nullptr; for(uint32_t sizeIdX = 0; sizeIdX < SCALING_LIST_SIZE_NUM; sizeIdX++) { for(uint32_t sizeIdY = 0; sizeIdY < SCALING_LIST_SIZE_NUM; sizeIdY++) { for(uint32_t qp = 0; qp < SCALING_LIST_REM_NUM; qp++) { for(uint32_t listId = 0; listId < SCALING_LIST_NUM; listId++) { if( m_isErrScaleListOwner ) { m_errScale[sizeIdX][sizeIdY][listId][qp] = new double[g_scalingListSizeX[sizeIdX] * g_scalingListSizeX[sizeIdY]]; } else { m_errScale[sizeIdX][sizeIdY][listId][qp] = other->m_errScale[sizeIdX][sizeIdY][listId][qp]; } } // listID loop } } } } /** destroy quantization matrix array */ void QuantRDOQ::xDestroyScalingList() { if( !m_isErrScaleListOwner ) return; for(uint32_t sizeIdX = 0; sizeIdX < SCALING_LIST_SIZE_NUM; sizeIdX++) { for(uint32_t sizeIdY = 0; sizeIdY < SCALING_LIST_SIZE_NUM; sizeIdY++) { for(uint32_t listId = 0; listId < SCALING_LIST_NUM; listId++) { for(uint32_t qp = 0; qp < SCALING_LIST_REM_NUM; qp++) { if(m_errScale[sizeIdX][sizeIdY][listId][qp]) { delete [] m_errScale[sizeIdX][sizeIdY][listId][qp]; } } } } } // Quant::destroyScalingList(); } #endif void QuantRDOQ::quant(TransformUnit &tu, const ComponentID &compID, const CCoeffBuf &pSrc, TCoeff &uiAbsSum, const QpParam &cQP, const Ctx& ctx) { const CompArea &rect = tu.blocks[compID]; const uint32_t uiWidth = rect.width; const uint32_t uiHeight = rect.height; const CCoeffBuf &piCoef = pSrc; CoeffBuf piQCoef = tu.getCoeffs(compID); const bool useTransformSkip = tu.transformSkip[compID]; bool useRDOQ = useTransformSkip ? m_useRDOQTS : m_useRDOQ; { useRDOQ &= uiWidth > 2; useRDOQ &= uiHeight > 2; } if (useRDOQ && (isLuma(compID) || RDOQ_CHROMA)) { #if T0196_SELECTIVE_RDOQ if (!m_useSelectiveRDOQ || xNeedRDOQ(tu, compID, piCoef, cQP)) { #endif xRateDistOptQuant( tu, compID, pSrc, uiAbsSum, cQP, ctx ); #if T0196_SELECTIVE_RDOQ } else { piQCoef.fill(0); uiAbsSum = 0; } #endif } else { Quant::quant( tu, compID, pSrc, uiAbsSum, cQP, ctx ); } } void QuantRDOQ::xRateDistOptQuant(TransformUnit &tu, const ComponentID &compID, const CCoeffBuf &pSrc, TCoeff &uiAbsSum, const QpParam &cQP, const Ctx &ctx) { const FracBitsAccess& fracBits = ctx.getFracBitsAcess(); const SPS &sps = *tu.cs->sps; #if JVET_K0072 #else #if HEVC_USE_SIGN_HIDING const PPS &pps = *tu.cs->pps; #endif #endif const CompArea &rect = tu.blocks[compID]; const uint32_t uiWidth = rect.width; const uint32_t uiHeight = rect.height; const ChannelType chType = toChannelType(compID); const int channelBitDepth = sps.getBitDepth( chType ); const bool extendedPrecision = sps.getSpsRangeExtension().getExtendedPrecisionProcessingFlag(); const int maxLog2TrDynamicRange = sps.getMaxLog2TrDynamicRange(chType); /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller) * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result */ // Represents scaling through forward transform int iTransformShift = getTransformShift(channelBitDepth, rect.size(), maxLog2TrDynamicRange); if (tu.transformSkip[compID] && extendedPrecision) { iTransformShift = std::max(0, iTransformShift); } #if JVET_K0072 #else const bool bUseGolombRiceParameterAdaptation = sps.getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag(); const uint32_t initialGolombRiceParameter = ctx.getGRAdaptStats(TU::getGolombRiceStatisticsIndex(tu, compID)) >> 2; uint32_t uiGoRiceParam = initialGolombRiceParameter; #endif double d64BlockUncodedCost = 0; const uint32_t uiLog2BlockWidth = g_aucLog2[uiWidth]; #if HEVC_USE_SCALING_LISTS const uint32_t uiLog2BlockHeight = g_aucLog2[uiHeight]; #endif const uint32_t uiMaxNumCoeff = rect.area(); CHECK(compID >= MAX_NUM_TBLOCKS, ""Invalid component ID""); #if HEVC_USE_SCALING_LISTS int scalingListType = getScalingListType(tu.cu->predMode, compID); CHECK(scalingListType >= SCALING_LIST_NUM, ""Invalid scaling list""); #endif const TCoeff *plSrcCoeff = pSrc.buf; TCoeff *piDstCoeff = tu.getCoeffs(compID).buf; double *pdCostCoeff = m_pdCostCoeff; double *pdCostSig = m_pdCostSig; double *pdCostCoeff0 = m_pdCostCoeff0; #if HEVC_USE_SIGN_HIDING int *rateIncUp = m_rateIncUp; int *rateIncDown = m_rateIncDown; int *sigRateDelta = m_sigRateDelta; TCoeff *deltaU = m_deltaU; #endif memset( m_pdCostCoeff, 0, sizeof( double ) * uiMaxNumCoeff ); memset( m_pdCostSig, 0, sizeof( double ) * uiMaxNumCoeff ); #if HEVC_USE_SIGN_HIDING memset( m_rateIncUp, 0, sizeof( int ) * uiMaxNumCoeff ); memset( m_rateIncDown, 0, sizeof( int ) * uiMaxNumCoeff ); memset( m_sigRateDelta, 0, sizeof( int ) * uiMaxNumCoeff ); memset( m_deltaU, 0, sizeof( TCoeff ) * uiMaxNumCoeff ); #endif #if JVET_K0072 #else #if JEM_TOOLS const unsigned altResiCompId = tu.cs->sps->getSpsNext().getAltResiCompId(); #endif #endif const int iQBits = QUANT_SHIFT + cQP.per + iTransformShift; // Right shift of non-RDOQ quantizer; level = (coeff*uiQ + offset)>>q_bits #if HEVC_USE_SCALING_LISTS const double *const pdErrScale = xGetErrScaleCoeff(scalingListType, (uiLog2BlockWidth-1), (uiLog2BlockHeight-1), cQP.rem); const int *const piQCoef = getQuantCoeff(scalingListType, cQP.rem, (uiLog2BlockWidth-1), (uiLog2BlockHeight-1)); const bool enableScalingLists = getUseScalingList(uiWidth, uiHeight, tu.transformSkip[compID]); #if HM_QTBT_AS_IN_JEM_QUANT const int defaultQuantisationCoefficient = ( TU::needsSqrt2Scale( rect ) ? ( g_quantScales[cQP.rem] * 181 ) >> 7 : g_quantScales[cQP.rem] ); const double defaultErrorScale = xGetErrScaleCoeffNoScalingList(scalingListType, (uiLog2BlockWidth-1), (uiLog2BlockHeight-1), cQP.rem); #else const double blkErrScale = ( TU::needsQP3Offset( tu, compID ) ? 2.0 : 1.0 ); const int defaultQuantisationCoefficient = g_quantScales[cQP.rem]; const double defaultErrorScale = blkErrScale * xGetErrScaleCoeffNoScalingList( scalingListType, ( uiLog2BlockWidth - 1 ), ( uiLog2BlockHeight - 1 ), cQP.rem ); #endif #else //HEVC_USE_SCALING_LISTS #if HM_QTBT_AS_IN_JEM_QUANT const int quantisationCoefficient = ( TU::needsSqrt2Scale( rect ) ? ( g_quantScales[cQP.rem] * 181 ) >> 7 : g_quantScales[cQP.rem] ); const double errorScale = xGetErrScaleCoeff( uiWidth, uiHeight, cQP.rem, maxLog2TrDynamicRange, channelBitDepth ); #else const double blkErrScale = ( TU::needsQP3Offset( tu, compID ) ? 2.0 : 1.0 ); const int quantisationCoefficient = g_quantScales[cQP.rem]; const double errorScale = blkErrScale * xGetErrScaleCoeff( uiWidth, uiHeight, cQP.rem, maxLog2TrDynamicRange, channelBitDepth ); #endif #endif//HEVC_USE_SCALING_LISTS #if HEVC_USE_SIGN_HIDING const TCoeff entropyCodingMinimum = -(1 << maxLog2TrDynamicRange); #endif const TCoeff entropyCodingMaximum = (1 << maxLog2TrDynamicRange) - 1; #if HEVC_USE_SIGN_HIDING #if JVET_K0072 CoeffCodingContext cctx(tu, compID, tu.cs->slice->getSignDataHidingEnabledFlag()); #else CoeffCodingContext cctx(tu, compID, pps.getSignDataHidingEnabledFlag()); #endif #else CoeffCodingContext cctx(tu, compID); #endif const int iCGSizeM1 = (1 << cctx.log2CGSize()) - 1; int iCGLastScanPos = -1; #if JVET_K0072 #else int c1 = 1; int c2 = 0; #endif double d64BaseCost = 0; int iLastScanPos = -1; #if JVET_K0072 #else uint32_t c1Idx = 0; uint32_t c2Idx = 0; int baseLevel; #endif double *pdCostCoeffGroupSig = m_pdCostCoeffGroupSig; memset( pdCostCoeffGroupSig, 0, ( uiMaxNumCoeff >> cctx.log2CGSize() ) * sizeof( double ) ); const int iCGNum = uiWidth * uiHeight >> cctx.log2CGSize(); int iScanPos; coeffGroupRDStats rdStats; #if ENABLE_TRACING DTRACE( g_trace_ctx, D_RDOQ, ""%d: %3d, %3d, %dx%d, comp=%d\\n"", DTRACE_GET_COUNTER( g_trace_ctx, D_RDOQ ), rect.x, rect.y, rect.width, rect.height, compID ); #endif for (int subSetId = iCGNum - 1; subSetId >= 0; subSetId--) { cctx.initSubblock( subSetId ); memset( &rdStats, 0, sizeof (coeffGroupRDStats)); for (int iScanPosinCG = iCGSizeM1; iScanPosinCG >= 0; iScanPosinCG--) { iScanPos = cctx.minSubPos() + iScanPosinCG; //===== quantization ===== uint32_t uiBlkPos = cctx.blockPos(iScanPos); // set coeff #if HEVC_USE_SCALING_LISTS const int quantisationCoefficient = (enableScalingLists) ? piQCoef [uiBlkPos] : defaultQuantisationCoefficient; #if HM_QTBT_AS_IN_JEM_QUANT const double errorScale = (enableScalingLists) ? pdErrScale[uiBlkPos] : defaultErrorScale; #else const double errorScale = (enableScalingLists) ? pdErrScale[uiBlkPos] * blkErrScale : defaultErrorScale; #endif #endif const int64_t tmpLevel = int64_t(abs(plSrcCoeff[ uiBlkPos ])) * quantisationCoefficient; const Intermediate_Int lLevelDouble = (Intermediate_Int)std::min(tmpLevel, std::numeric_limits::max() - (Intermediate_Int(1) << (iQBits - 1))); uint32_t uiMaxAbsLevel = std::min(uint32_t(entropyCodingMaximum), uint32_t((lLevelDouble + (Intermediate_Int(1) << (iQBits - 1))) >> iQBits)); const double dErr = double( lLevelDouble ); pdCostCoeff0[ iScanPos ] = dErr * dErr * errorScale; d64BlockUncodedCost += pdCostCoeff0[ iScanPos ]; piDstCoeff[ uiBlkPos ] = uiMaxAbsLevel; if ( uiMaxAbsLevel > 0 && iLastScanPos < 0 ) { iLastScanPos = iScanPos; iCGLastScanPos = cctx.subSetId(); } if ( iLastScanPos >= 0 ) { #if ENABLE_TRACING uint32_t uiCGPosY = cctx.cgPosX(); uint32_t uiCGPosX = cctx.cgPosY(); uint32_t uiPosY = cctx.posY( iScanPos ); uint32_t uiPosX = cctx.posX( iScanPos ); DTRACE( g_trace_ctx, D_RDOQ, ""%d [%d][%d][%2d:%2d][%2d:%2d]"", DTRACE_GET_COUNTER( g_trace_ctx, D_RDOQ ), iScanPos, uiBlkPos, uiCGPosX, uiCGPosY, uiPosX, uiPosY ); #if JVET_K0072 #else DTRACE( g_trace_ctx, D_RDOQ, "" c1: %d, c2: %d, c1Idx: %d, c2Idx: %d\\n"", c1, c2, c1Idx, c2Idx ); #endif #endif //===== coefficient level estimation ===== unsigned ctxIdSig = 0; if( iScanPos != iLastScanPos ) { #if JVET_K0072 ctxIdSig = cctx.sigCtxIdAbs( iScanPos, piDstCoeff, 0 ); #else #if JEM_TOOLS ctxIdSig = altResiCompId ? cctx.sigCtxId( iScanPos, piDstCoeff ) : cctx.sigCtxId( iScanPos ); #else ctxIdSig = cctx.sigCtxId( iScanPos ); #endif #endif } uint32_t uiLevel; #if JVET_K0072 uint8_t ctxOffset = cctx.ctxOffsetAbs (); uint32_t uiParCtx = cctx.parityCtxIdAbs ( ctxOffset ); uint32_t uiGt1Ctx = cctx.greater1CtxIdAbs ( ctxOffset ); uint32_t uiGt2Ctx = cctx.greater2CtxIdAbs ( ctxOffset ); uint32_t uiGoRiceParam = cctx.GoRiceParAbs ( iScanPos, piDstCoeff ); const BinFracBits fracBitsPar = fracBits.getFracBitsArray( uiParCtx ); const BinFracBits fracBitsGt1 = fracBits.getFracBitsArray( uiGt1Ctx ); const BinFracBits fracBitsGt2 = fracBits.getFracBitsArray( uiGt2Ctx ); #else #if JEM_TOOLS #if ENABLE_TRACING uint32_t uiOneCtx = altResiCompId ? ( iScanPos == iLastScanPos ? cctx.greater1CtxIdOfs() : cctx.greater1CtxId( iScanPos, piDstCoeff ) ) : cctx.greater1CtxId( c1 ); uint32_t uiAbsCtx = altResiCompId ? ( iScanPos == iLastScanPos ? cctx.greater1CtxIdOfs() : cctx.greater2CtxId( iScanPos, piDstCoeff ) ) : cctx.greater2CtxId(); #endif const BinFracBits fracBitsOne = fracBits.getFracBitsArray( altResiCompId ? ( iScanPos == iLastScanPos ? cctx.greater1CtxIdOfs() : cctx.greater1CtxId( iScanPos, piDstCoeff ) ) : cctx.greater1CtxId( c1 ) ); const BinFracBits fracBitsAbs = fracBits.getFracBitsArray( altResiCompId ? ( iScanPos == iLastScanPos ? cctx.greater1CtxIdOfs() : cctx.greater2CtxId( iScanPos, piDstCoeff ) ) : cctx.greater2CtxId() ); uiGoRiceParam = altResiCompId ? cctx.GoRicePar( iScanPos, piDstCoeff ) : uiGoRiceParam; #else #if ENABLE_TRACING uint32_t uiOneCtx = cctx.greater1CtxId( c1 ); uint32_t uiAbsCtx = cctx.greater2CtxId(); #endif const BinFracBits fracBitsOne = fracBits.getFracBitsArray( cctx.greater1CtxId( c1 ) ); const BinFracBits fracBitsAbs = fracBits.getFracBitsArray( cctx.greater2CtxId() ); #endif DTRACE_COND( ( uiMaxAbsLevel != 0 ), g_trace_ctx, D_RDOQ_MORE, "" One=%d Abs=%d"", uiOneCtx, uiAbsCtx ); #endif if( iScanPos == iLastScanPos ) { #if JVET_K0072 uiLevel = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ], lLevelDouble, uiMaxAbsLevel, nullptr, fracBitsPar, fracBitsGt1, fracBitsGt2, uiGoRiceParam, iQBits, errorScale, 1, extendedPrecision, maxLog2TrDynamicRange ); #else uiLevel = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ], lLevelDouble, uiMaxAbsLevel, nullptr, fracBitsOne, fracBitsAbs, #if JEM_TOOLS altResiCompId, #endif uiGoRiceParam, c1Idx, c2Idx, iQBits, errorScale, 1, extendedPrecision, maxLog2TrDynamicRange ); #endif } else { DTRACE_COND( ( uiMaxAbsLevel != 0 ), g_trace_ctx, D_RDOQ_MORE, "" uiCtxSig=%d"", ctxIdSig ); const BinFracBits fracBitsSig = fracBits.getFracBitsArray( ctxIdSig ); #if JVET_K0072 uiLevel = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ], lLevelDouble, uiMaxAbsLevel, &fracBitsSig, fracBitsPar, fracBitsGt1, fracBitsGt2, uiGoRiceParam, iQBits, errorScale, 0, extendedPrecision, maxLog2TrDynamicRange ); #else uiLevel = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ], lLevelDouble, uiMaxAbsLevel, &fracBitsSig, fracBitsOne, fracBitsAbs, #if JEM_TOOLS altResiCompId, #endif uiGoRiceParam, c1Idx, c2Idx, iQBits, errorScale, 0, extendedPrecision, maxLog2TrDynamicRange ); #endif #if HEVC_USE_SIGN_HIDING sigRateDelta[ uiBlkPos ] = fracBitsSig.intBits[1] - fracBitsSig.intBits[0]; #endif } DTRACE( g_trace_ctx, D_RDOQ, "" Lev=%d \\n"", uiLevel ); DTRACE_COND( ( uiMaxAbsLevel != 0 ), g_trace_ctx, D_RDOQ, "" CostC0=%d\\n"", (int64_t)( pdCostCoeff0[iScanPos] ) ); DTRACE_COND( ( uiMaxAbsLevel != 0 ), g_trace_ctx, D_RDOQ, "" CostC =%d\\n"", (int64_t)( pdCostCoeff[iScanPos] ) ); #if HEVC_USE_SIGN_HIDING deltaU[ uiBlkPos ] = TCoeff((lLevelDouble - (Intermediate_Int(uiLevel) << iQBits)) >> (iQBits-8)); if( uiLevel > 0 ) { #if JVET_K0072 int rateNow = xGetICRate( uiLevel, fracBitsPar, fracBitsGt1, fracBitsGt2, uiGoRiceParam, extendedPrecision, maxLog2TrDynamicRange ); rateIncUp [ uiBlkPos ] = xGetICRate( uiLevel+1, fracBitsPar, fracBitsGt1, fracBitsGt2, uiGoRiceParam, extendedPrecision, maxLog2TrDynamicRange ) - rateNow; rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, fracBitsPar, fracBitsGt1, fracBitsGt2, uiGoRiceParam, extendedPrecision, maxLog2TrDynamicRange ) - rateNow; #elif JEM_TOOLS int rateNow = xGetICRate( uiLevel, fracBitsOne, fracBitsAbs, altResiCompId, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange ); rateIncUp [ uiBlkPos ] = xGetICRate( uiLevel+1, fracBitsOne, fracBitsAbs, altResiCompId, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange ) - rateNow; rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, fracBitsOne, fracBitsAbs, altResiCompId, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange ) - rateNow; #else int rateNow = xGetICRate( uiLevel, fracBitsOne, fracBitsAbs, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange ); rateIncUp [ uiBlkPos ] = xGetICRate( uiLevel+1, fracBitsOne, fracBitsAbs, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange ) - rateNow; rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, fracBitsOne, fracBitsAbs, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, maxLog2TrDynamicRange ) - rateNow; #endif } else // uiLevel == 0 { #if JVET_K0072 rateIncUp [ uiBlkPos ] = fracBitsPar.intBits[ 0 ] + fracBitsGt1.intBits[ 0 ]; #else rateIncUp [ uiBlkPos ] = fracBitsOne.intBits[ 0 ]; #endif } #endif piDstCoeff[ uiBlkPos ] = uiLevel; d64BaseCost += pdCostCoeff [ iScanPos ]; #if JVET_K0072 #else baseLevel = (c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx < C2FLAG_NUMBER)) : 1; if( uiLevel >= baseLevel ) { if (uiLevel > 3*(1<((uiGoRiceParam + 1), 4)); } } if ( uiLevel >= 1) { c1Idx ++; } //===== update bin model ===== if( uiLevel > 1 ) { c1 = 0; c2 += (c2 < 2); c2Idx ++; } else if( (c1 < 3) && (c1 > 0) && uiLevel) { c1++; } //===== context set update ===== if( ( (iScanPos & iCGSizeM1) == 0 ) && ( iScanPos > 0 ) ) { cctx.setGt2Flag( c1 == 0 ); c1 = 1; c2 = 0; c1Idx = 0; c2Idx = 0; uiGoRiceParam = initialGolombRiceParameter; } #endif } else { d64BaseCost += pdCostCoeff0[ iScanPos ]; } rdStats.d64SigCost += pdCostSig[ iScanPos ]; if (iScanPosinCG == 0 ) { rdStats.d64SigCost_0 = pdCostSig[ iScanPos ]; } if (piDstCoeff[ uiBlkPos ] ) { cctx.setSigGroup(); rdStats.d64CodedLevelandDist += pdCostCoeff[ iScanPos ] - pdCostSig[ iScanPos ]; rdStats.d64UncodedDist += pdCostCoeff0[ iScanPos ]; if ( iScanPosinCG != 0 ) { rdStats.iNNZbeforePos0++; } } } //end for (iScanPosinCG) if (iCGLastScanPos >= 0) { if( cctx.subSetId() ) { if( !cctx.isSigGroup() ) { const BinFracBits fracBitsSigGroup = fracBits.getFracBitsArray( cctx.sigGroupCtxId() ); d64BaseCost += xGetRateSigCoeffGroup(fracBitsSigGroup, 0) - rdStats.d64SigCost; pdCostCoeffGroupSig[ cctx.subSetId() ] = xGetRateSigCoeffGroup(fracBitsSigGroup, 0); } else { if (cctx.subSetId() < iCGLastScanPos) //skip the last coefficient group, which will be handled together with last position below. { if ( rdStats.iNNZbeforePos0 == 0 ) { d64BaseCost -= rdStats.d64SigCost_0; rdStats.d64SigCost -= rdStats.d64SigCost_0; } // rd-cost if SigCoeffGroupFlag = 0, initialization double d64CostZeroCG = d64BaseCost; const BinFracBits fracBitsSigGroup = fracBits.getFracBitsArray( cctx.sigGroupCtxId() ); if (cctx.subSetId() < iCGLastScanPos) { d64BaseCost += xGetRateSigCoeffGroup(fracBitsSigGroup,1); d64CostZeroCG += xGetRateSigCoeffGroup(fracBitsSigGroup,0); pdCostCoeffGroupSig[ cctx.subSetId() ] = xGetRateSigCoeffGroup(fracBitsSigGroup,1); } // try to convert the current coeff group from non-zero to all-zero d64CostZeroCG += rdStats.d64UncodedDist; // distortion for resetting non-zero levels to zero levels d64CostZeroCG -= rdStats.d64CodedLevelandDist; // distortion and level cost for keeping all non-zero levels d64CostZeroCG -= rdStats.d64SigCost; // sig cost for all coeffs, including zero levels and non-zerl levels // if we can save cost, change this block to all-zero block if ( d64CostZeroCG < d64BaseCost ) { cctx.resetSigGroup(); d64BaseCost = d64CostZeroCG; if (cctx.subSetId() < iCGLastScanPos) { pdCostCoeffGroupSig[ cctx.subSetId() ] = xGetRateSigCoeffGroup(fracBitsSigGroup,0); } // reset coeffs to 0 in this block for (int iScanPosinCG = iCGSizeM1; iScanPosinCG >= 0; iScanPosinCG--) { iScanPos = cctx.minSubPos() + iScanPosinCG; uint32_t uiBlkPos = cctx.blockPos( iScanPos ); if (piDstCoeff[ uiBlkPos ]) { piDstCoeff [ uiBlkPos ] = 0; pdCostCoeff[ iScanPos ] = pdCostCoeff0[ iScanPos ]; pdCostSig [ iScanPos ] = 0; } } } // end if ( d64CostAllZeros < d64BaseCost ) } } // end if if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0) } else { cctx.setSigGroup(); } } } //end for (cctx.subSetId) //===== estimate last position ===== if ( iLastScanPos < 0 ) { return; } double d64BestCost = 0; int iBestLastIdxP1 = 0; #if ENABLE_BMS if( !CU::isIntra( *tu.cu ) && isLuma( compID ) && tu.depth == 0 ) #else if( !CU::isIntra( *tu.cu ) && isLuma( compID ) ) #endif { const BinFracBits fracBitsQtRootCbf = fracBits.getFracBitsArray( Ctx::QtRootCbf() ); d64BestCost = d64BlockUncodedCost + xGetICost( fracBitsQtRootCbf.intBits[ 0 ] ); d64BaseCost += xGetICost( fracBitsQtRootCbf.intBits[ 1 ] ); } else { #if ENABLE_BMS #if JVET_K0072 BinFracBits fracBitsQtCbf = fracBits.getFracBitsArray( Ctx::QtCbf[compID]( DeriveCtx::CtxQtCbf( rect.compID, tu.depth, tu.cbf[COMPONENT_Cb] ) ) ); #else BinFracBits fracBitsQtCbf = fracBits.getFracBitsArray( Ctx::QtCbf[chType]( DeriveCtx::CtxQtCbf( rect.compID, tu.depth ) ) ); #endif #else #if JVET_K0072 BinFracBits fracBitsQtCbf = fracBits.getFracBitsArray( Ctx::QtCbf[compID]( DeriveCtx::CtxQtCbf( rect.compID, tu.cbf[COMPONENT_Cb] ) ) ); #else BinFracBits fracBitsQtCbf = fracBits.getFracBitsArray( Ctx::QtCbf[chType]( DeriveCtx::CtxQtCbf( rect.compID ) ) ); #endif #endif d64BestCost = d64BlockUncodedCost + xGetICost( fracBitsQtCbf.intBits[0] ); d64BaseCost += xGetICost( fracBitsQtCbf.intBits[1] ); } int lastBitsX[LAST_SIGNIFICANT_GROUPS] = { 0 }; int lastBitsY[LAST_SIGNIFICANT_GROUPS] = { 0 }; { #if HEVC_USE_MDCS int dim1 = ( cctx.scanType() == SCAN_VER ? uiHeight : uiWidth ); int dim2 = ( cctx.scanType() == SCAN_VER ? uiWidth : uiHeight ); #else int dim1 = uiWidth; int dim2 = uiHeight; #endif int bitsX = 0; int bitsY = 0; int ctxId; //X-coordinate for ( ctxId = 0; ctxId < g_uiGroupIdx[dim1-1]; ctxId++) { const BinFracBits fB = fracBits.getFracBitsArray( cctx.lastXCtxId(ctxId) ); lastBitsX[ ctxId ] = bitsX + fB.intBits[ 0 ]; bitsX += fB.intBits[ 1 ]; } lastBitsX[ctxId] = bitsX; //Y-coordinate for ( ctxId = 0; ctxId < g_uiGroupIdx[dim2-1]; ctxId++) { const BinFracBits fB = fracBits.getFracBitsArray( cctx.lastYCtxId(ctxId) ); lastBitsY[ ctxId ] = bitsY + fB.intBits[ 0 ]; bitsY += fB.intBits[ 1 ]; } lastBitsY[ctxId] = bitsY; } bool bFoundLast = false; for (int iCGScanPos = iCGLastScanPos; iCGScanPos >= 0; iCGScanPos--) { d64BaseCost -= pdCostCoeffGroupSig [ iCGScanPos ]; if (cctx.isSigGroup( iCGScanPos ) ) { for (int iScanPosinCG = iCGSizeM1; iScanPosinCG >= 0; iScanPosinCG--) { iScanPos = iCGScanPos * (iCGSizeM1 + 1) + iScanPosinCG; if (iScanPos > iLastScanPos) { continue; } uint32_t uiBlkPos = cctx.blockPos( iScanPos ); if( piDstCoeff[ uiBlkPos ] ) { uint32_t uiPosY = uiBlkPos >> uiLog2BlockWidth; uint32_t uiPosX = uiBlkPos - ( uiPosY << uiLog2BlockWidth ); #if HEVC_USE_MDCS double d64CostLast = ( cctx.scanType() == SCAN_VER ? xGetRateLast( lastBitsX, lastBitsY, uiPosY, uiPosX ) : xGetRateLast( lastBitsX, lastBitsY, uiPosX, uiPosY ) ); #else double d64CostLast = xGetRateLast( lastBitsX, lastBitsY, uiPosX, uiPosY ); #endif double totalCost = d64BaseCost + d64CostLast - pdCostSig[ iScanPos ]; if( totalCost < d64BestCost ) { iBestLastIdxP1 = iScanPos + 1; d64BestCost = totalCost; } if( piDstCoeff[ uiBlkPos ] > 1 ) { bFoundLast = true; break; } d64BaseCost -= pdCostCoeff[ iScanPos ]; d64BaseCost += pdCostCoeff0[ iScanPos ]; } else { d64BaseCost -= pdCostSig[ iScanPos ]; } } //end for if (bFoundLast) { break; } } // end if (uiSigCoeffGroupFlag[ uiCGBlkPos ]) DTRACE( g_trace_ctx, D_RDOQ_COST, ""%d: %3d, %3d, %dx%d, comp=%d\\n"", DTRACE_GET_COUNTER( g_trace_ctx, D_RDOQ_COST ), rect.x, rect.y, rect.width, rect.height, compID ); DTRACE( g_trace_ctx, D_RDOQ_COST, ""Uncoded=%d\\n"", (int64_t)( d64BlockUncodedCost ) ); DTRACE( g_trace_ctx, D_RDOQ_COST, ""Coded =%d\\n"", (int64_t)( d64BaseCost ) ); } // end for for ( int scanPos = 0; scanPos < iBestLastIdxP1; scanPos++ ) { int blkPos = cctx.blockPos( scanPos ); TCoeff level = piDstCoeff[ blkPos ]; uiAbsSum += level; piDstCoeff[ blkPos ] = ( plSrcCoeff[ blkPos ] < 0 ) ? -level : level; } //===== clean uncoded coefficients ===== for ( int scanPos = iBestLastIdxP1; scanPos <= iLastScanPos; scanPos++ ) { piDstCoeff[ cctx.blockPos( scanPos ) ] = 0; } #if HEVC_USE_SIGN_HIDING if( cctx.signHiding() && uiAbsSum>=2) { const double inverseQuantScale = double(g_invQuantScales[cQP.rem]); #if DISTORTION_LAMBDA_BUGFIX int64_t rdFactor = (int64_t)(inverseQuantScale * inverseQuantScale * (1 << (2 * cQP.per)) / m_dLambda / 16 / (1 << (2 * DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth))) #else int64_t rdFactor = (int64_t)(inverseQuantScale * inverseQuantScale * (1 << (2 * cQP.per)) / m_dLambda / 16 / (1 << (2 * DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth - 8))) #endif #if HM_QTBT_AS_IN_JEM_QUANT #else * blkErrScale #endif + 0.5); int lastCG = -1; int absSum = 0 ; int n ; for( int subSet = (uiWidth*uiHeight-1) >> cctx.log2CGSize(); subSet >= 0; subSet-- ) { int subPos = subSet << cctx.log2CGSize(); int firstNZPosInCG = iCGSizeM1 + 1, lastNZPosInCG = -1; absSum = 0 ; for( n = iCGSizeM1; n >= 0; --n ) { if( piDstCoeff[ cctx.blockPos( n + subPos )] ) { lastNZPosInCG = n; break; } } for( n = 0; n <= iCGSizeM1; n++ ) { if( piDstCoeff[ cctx.blockPos( n + subPos )] ) { firstNZPosInCG = n; break; } } for( n = firstNZPosInCG; n <= lastNZPosInCG; n++ ) { absSum += int(piDstCoeff[ cctx.blockPos( n + subPos )]); } if(lastNZPosInCG>=0 && lastCG==-1) { lastCG = 1; } if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD ) { uint32_t signbit = (piDstCoeff[cctx.blockPos(subPos+firstNZPosInCG)]>0?0:1); if( signbit!=(absSum&0x1) ) // hide but need tune { // calculate the cost int64_t minCostInc = std::numeric_limits::max(), curCost = std::numeric_limits::max(); int minPos = -1, finalChange = 0, curChange = 0; for( n = (lastCG == 1 ? lastNZPosInCG : iCGSizeM1); n >= 0; --n ) { uint32_t uiBlkPos = cctx.blockPos( n + subPos ); if(piDstCoeff[ uiBlkPos ] != 0 ) { int64_t costUp = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos]; int64_t costDown = rdFactor * ( deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos] - ((abs(piDstCoeff[uiBlkPos]) == 1) ? sigRateDelta[uiBlkPos] : 0); if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1) { costDown -= (4<::max(); } else { curCost = costDown; } } } else { curCost = rdFactor * ( - (abs(deltaU[uiBlkPos])) ) + (1<=0?0:1); if(thissignbit != signbit ) { curCost = std::numeric_limits::max(); } } } if( curCost=0) { piDstCoeff[minPos] += finalChange ; } else { piDstCoeff[minPos] -= finalChange ; } } } if(lastCG==1) { lastCG=0 ; } } } #endif } //! \\} ",16130,True,3035.173468882632,median "// This file is part of AsmJit project // // See asmjit.h or LICENSE.md for license and copyright information // SPDX-License-Identifier: Zlib #include ""../core/api-build_p.h"" #ifndef ASMJIT_NO_COMPILER #include ""../core/formatter.h"" #include ""../core/ralocal_p.h"" #include ""../core/rapass_p.h"" #include ""../core/support.h"" #include ""../core/type.h"" #include ""../core/zonestack.h"" ASMJIT_BEGIN_NAMESPACE // RABlock - Control Flow // ====================== Error RABlock::appendSuccessor(RABlock* successor) noexcept { RABlock* predecessor = this; if (predecessor->hasSuccessor(successor)) return kErrorOk; ASMJIT_PROPAGATE(successor->_predecessors.willGrow(allocator())); ASMJIT_PROPAGATE(predecessor->_successors.willGrow(allocator())); predecessor->_successors.appendUnsafe(successor); successor->_predecessors.appendUnsafe(predecessor); return kErrorOk; } Error RABlock::prependSuccessor(RABlock* successor) noexcept { RABlock* predecessor = this; if (predecessor->hasSuccessor(successor)) return kErrorOk; ASMJIT_PROPAGATE(successor->_predecessors.willGrow(allocator())); ASMJIT_PROPAGATE(predecessor->_successors.willGrow(allocator())); predecessor->_successors.prependUnsafe(successor); successor->_predecessors.prependUnsafe(predecessor); return kErrorOk; } // BaseRAPass - Construction & Destruction // ======================================= BaseRAPass::BaseRAPass() noexcept : FuncPass(""BaseRAPass"") {} BaseRAPass::~BaseRAPass() noexcept {} // BaseRAPass - RunOnFunction // ========================== static void BaseRAPass_reset(BaseRAPass* self, FuncDetail* funcDetail) noexcept { ZoneAllocator* allocator = self->allocator(); self->_blocks.reset(); self->_exits.reset(); self->_pov.reset(); self->_workRegs.reset(); self->_instructionCount = 0; self->_createdBlockCount = 0; self->_sharedAssignments.reset(); self->_lastTimestamp = 0; self->_archTraits = nullptr; self->_physRegIndex.reset(); self->_physRegCount.reset(); self->_physRegTotal = 0; self->_scratchRegIndexes.fill(BaseReg::kIdBad); self->_availableRegs.reset(); self->_availableRegCount.reset(); self->_clobberedRegs.reset(); self->_workRegs.reset(); self->_workRegsOfGroup.forEach([](RAWorkRegs& regs) { regs.reset(); }); self->_strategy.forEach([](RAStrategy& strategy) { strategy.reset(); }); self->_globalLiveSpans.fill(nullptr); self->_globalMaxLiveCount.reset(); self->_temporaryMem.reset(); self->_stackAllocator.reset(allocator); self->_argsAssignment.reset(funcDetail); self->_numStackArgsToStackSlots = 0; self->_maxWorkRegNameSize = 0; } static void BaseRAPass_resetVirtRegData(BaseRAPass* self) noexcept { for (RAWorkReg* wReg : self->_workRegs) { VirtReg* vReg = wReg->virtReg(); // Update the information regarding the stack of the virtual register. if (wReg->hasStackSlot()) { RAStackSlot* slot = wReg->stackSlot(); vReg->assignStackSlot(slot->offset()); } // Reset work reg association so it cannot be used by accident (RAWorkReg data will be destroyed). vReg->_workReg = nullptr; } } Error BaseRAPass::runOnFunction(Zone* zone, Logger* logger, FuncNode* func) { _allocator.reset(zone); #ifndef ASMJIT_NO_LOGGING _logger = logger; _formatOptions.reset(); _diagnosticOptions = DiagnosticOptions::kNone; if (logger) { _formatOptions = logger->options(); _diagnosticOptions = _cb->diagnosticOptions(); } #else DebugUtils::unused(logger); #endif // Initialize all core structures to use `zone` and `func`. BaseNode* end = func->endNode(); _func = func; _stop = end->next(); _extraBlock = end; BaseRAPass_reset(this, &_func->_funcDetail); // Initialize architecture-specific members. onInit(); // Perform all allocation steps required. Error err = onPerformAllSteps(); // Must be called regardless of the allocation status. onDone(); // Reset possible connections introduced by the register allocator. BaseRAPass_resetVirtRegData(this); // Reset all core structures and everything that depends on the passed `Zone`. BaseRAPass_reset(this, nullptr); _allocator.reset(nullptr); #ifndef ASMJIT_NO_LOGGING _logger = nullptr; _formatOptions.reset(); _diagnosticOptions = DiagnosticOptions::kNone; #endif _func = nullptr; _stop = nullptr; _extraBlock = nullptr; // Reset `Zone` as nothing should persist between `runOnFunction()` calls. zone->reset(); // We alter the compiler cursor, because it doesn't make sense to reference it after the compilation - some // nodes may disappear and the old cursor can go out anyway. cc()->_setCursor(cc()->lastNode()); return err; } Error BaseRAPass::onPerformAllSteps() noexcept { ASMJIT_PROPAGATE(buildCFG()); ASMJIT_PROPAGATE(buildCFGViews()); ASMJIT_PROPAGATE(removeUnreachableCode()); ASMJIT_PROPAGATE(buildCFGDominators()); ASMJIT_PROPAGATE(buildLiveness()); ASMJIT_PROPAGATE(assignArgIndexToWorkRegs()); #ifndef ASMJIT_NO_LOGGING if (hasDiagnosticOption(DiagnosticOptions::kRAAnnotate)) ASMJIT_PROPAGATE(annotateCode()); #endif ASMJIT_PROPAGATE(runGlobalAllocator()); ASMJIT_PROPAGATE(runLocalAllocator()); ASMJIT_PROPAGATE(updateStackFrame()); ASMJIT_PROPAGATE(insertPrologEpilog()); ASMJIT_PROPAGATE(rewrite()); return kErrorOk; } // BaseRAPass - CFG - Basic Block Management // ========================================= RABlock* BaseRAPass::newBlock(BaseNode* initialNode) noexcept { RABlock* block = zone()->newT(this); if (ASMJIT_UNLIKELY(!block)) return nullptr; block->setFirst(initialNode); block->setLast(initialNode); _createdBlockCount++; return block; } RABlock* BaseRAPass::newBlockOrExistingAt(LabelNode* cbLabel, BaseNode** stoppedAt) noexcept { if (cbLabel->hasPassData()) return cbLabel->passData(); FuncNode* func = this->func(); BaseNode* node = cbLabel->prev(); RABlock* block = nullptr; // Try to find some label, but terminate the loop on any code. We try hard to coalesce code that contains two // consecutive labels or a combination of non-code nodes between 2 or more labels. // // Possible cases that would share the same basic block: // // 1. Two or more consecutive labels: // Label1: // Label2: // // 2. Two or more labels separated by non-code nodes: // Label1: // ; Some comment... // .align 16 // Label2: size_t nPendingLabels = 0; while (node) { if (node->type() == NodeType::kLabel) { // Function has a different NodeType, just make sure this was not messed up as we must never associate // BasicBlock with a `func` itself. ASMJIT_ASSERT(node != func); block = node->passData(); if (block) { // Exit node has always a block associated with it. If we went here it means that `cbLabel` passed here // is after the end of the function and cannot be merged with the function exit block. if (node == func->exitNode()) block = nullptr; break; } nPendingLabels++; } else if (node->type() == NodeType::kAlign) { // Align node is fine. } else { break; } node = node->prev(); } if (stoppedAt) *stoppedAt = node; if (!block) { block = newBlock(); if (ASMJIT_UNLIKELY(!block)) return nullptr; } cbLabel->setPassData(block); node = cbLabel; while (nPendingLabels) { node = node->prev(); for (;;) { if (node->type() == NodeType::kLabel) { node->setPassData(block); nPendingLabels--; break; } node = node->prev(); ASMJIT_ASSERT(node != nullptr); } } if (!block->first()) { block->setFirst(node); block->setLast(cbLabel); } return block; } Error BaseRAPass::addBlock(RABlock* block) noexcept { ASMJIT_PROPAGATE(_blocks.willGrow(allocator())); block->_blockId = blockCount(); _blocks.appendUnsafe(block); return kErrorOk; } // BaseRAPass - CFG - Build // ======================== Error BaseRAPass::initSharedAssignments(const ZoneVector& sharedAssignmentsMap) noexcept { if (sharedAssignmentsMap.empty()) return kErrorOk; uint32_t count = 0; for (RABlock* block : _blocks) { if (block->hasSharedAssignmentId()) { uint32_t sharedAssignmentId = sharedAssignmentsMap[block->sharedAssignmentId()]; block->setSharedAssignmentId(sharedAssignmentId); count = Support::max(count, sharedAssignmentId + 1); } } ASMJIT_PROPAGATE(_sharedAssignments.resize(allocator(), count)); // Aggregate all entry scratch GP regs from blocks of the same assignment to the assignment itself. It will then be // used instead of RABlock's own scratch regs mask, as shared assignments have precedence. for (RABlock* block : _blocks) { if (block->hasJumpTable()) { const RABlocks& successors = block->successors(); if (!successors.empty()) { RABlock* firstSuccessor = successors[0]; // NOTE: Shared assignments connect all possible successors so we only need the first to propagate exit scratch // GP registers. ASMJIT_ASSERT(firstSuccessor->hasSharedAssignmentId()); RASharedAssignment& sa = _sharedAssignments[firstSuccessor->sharedAssignmentId()]; sa.addEntryScratchGpRegs(block->exitScratchGpRegs()); } } if (block->hasSharedAssignmentId()) { RASharedAssignment& sa = _sharedAssignments[block->sharedAssignmentId()]; sa.addEntryScratchGpRegs(block->_entryScratchGpRegs); } } return kErrorOk; } // BaseRAPass - CFG - Views Order // ============================== class RABlockVisitItem { public: inline RABlockVisitItem(RABlock* block, uint32_t index) noexcept : _block(block), _index(index) {} inline RABlockVisitItem(const RABlockVisitItem& other) noexcept : _block(other._block), _index(other._index) {} inline RABlockVisitItem& operator=(const RABlockVisitItem& other) noexcept = default; inline RABlock* block() const noexcept { return _block; } inline uint32_t index() const noexcept { return _index; } RABlock* _block; uint32_t _index; }; Error BaseRAPass::buildCFGViews() noexcept { #ifndef ASMJIT_NO_LOGGING Logger* logger = getLoggerIf(DiagnosticOptions::kRADebugCFG); ASMJIT_RA_LOG_FORMAT(""[BuildCFGViews]\\n""); #endif uint32_t count = blockCount(); if (ASMJIT_UNLIKELY(!count)) return kErrorOk; ASMJIT_PROPAGATE(_pov.reserve(allocator(), count)); ZoneStack stack; ASMJIT_PROPAGATE(stack.init(allocator())); ZoneBitVector visited; ASMJIT_PROPAGATE(visited.resize(allocator(), count)); RABlock* current = _blocks[0]; uint32_t i = 0; for (;;) { for (;;) { if (i >= current->successors().size()) break; // Skip if already visited. RABlock* child = current->successors()[i++]; if (visited.bitAt(child->blockId())) continue; // Mark as visited to prevent visiting the same block multiple times. visited.setBit(child->blockId(), true); // Add the current block on the stack, we will get back to it later. ASMJIT_PROPAGATE(stack.append(RABlockVisitItem(current, i))); current = child; i = 0; } current->makeReachable(); current->_povOrder = _pov.size(); _pov.appendUnsafe(current); if (stack.empty()) break; RABlockVisitItem top = stack.pop(); current = top.block(); i = top.index(); } ASMJIT_RA_LOG_COMPLEX({ StringTmp<1024> sb; for (RABlock* block : blocks()) { sb.clear(); if (block->hasSuccessors()) { sb.appendFormat("" #%u -> {"", block->blockId()); _dumpBlockIds(sb, block->successors()); sb.append(""}\\n""); } else { sb.appendFormat("" #%u -> {Exit}\\n"", block->blockId()); } logger->log(sb); } }); visited.release(allocator()); return kErrorOk; } // BaseRAPass - CFG - Dominators // ============================= static ASMJIT_FORCE_INLINE RABlock* intersectBlocks(RABlock* b1, RABlock* b2) noexcept { while (b1 != b2) { while (b2->povOrder() > b1->povOrder()) b1 = b1->iDom(); while (b1->povOrder() > b2->povOrder()) b2 = b2->iDom(); } return b1; } // Based on ""A Simple, Fast Dominance Algorithm"". Error BaseRAPass::buildCFGDominators() noexcept { #ifndef ASMJIT_NO_LOGGING Logger* logger = getLoggerIf(DiagnosticOptions::kRADebugCFG); ASMJIT_RA_LOG_FORMAT(""[BuildCFGDominators]\\n""); #endif if (_blocks.empty()) return kErrorOk; RABlock* entryBlock = this->entryBlock(); entryBlock->setIDom(entryBlock); bool changed = true; uint32_t nIters = 0; while (changed) { nIters++; changed = false; uint32_t i = _pov.size(); while (i) { RABlock* block = _pov[--i]; if (block == entryBlock) continue; RABlock* iDom = nullptr; const RABlocks& preds = block->predecessors(); uint32_t j = preds.size(); while (j) { RABlock* p = preds[--j]; if (!p->iDom()) continue; iDom = !iDom ? p : intersectBlocks(iDom, p); } if (block->iDom() != iDom) { ASMJIT_ASSUME(iDom != nullptr); ASMJIT_RA_LOG_FORMAT("" IDom of #%u -> #%u\\n"", block->blockId(), iDom->blockId()); block->setIDom(iDom); changed = true; } } } ASMJIT_RA_LOG_FORMAT("" Done (%u iterations)\\n"", nIters); return kErrorOk; } bool BaseRAPass::_strictlyDominates(const RABlock* a, const RABlock* b) const noexcept { ASMJIT_ASSERT(a != nullptr); // There must be at least one block if this function is ASMJIT_ASSERT(b != nullptr); // called, as both `a` and `b` must be valid blocks. ASMJIT_ASSERT(a != b); // Checked by `dominates()` and `strictlyDominates()`. // Nothing strictly dominates the entry block. const RABlock* entryBlock = this->entryBlock(); if (a == entryBlock) return false; const RABlock* iDom = b->iDom(); while (iDom != a && iDom != entryBlock) iDom = iDom->iDom(); return iDom != entryBlock; } const RABlock* BaseRAPass::_nearestCommonDominator(const RABlock* a, const RABlock* b) const noexcept { ASMJIT_ASSERT(a != nullptr); // There must be at least one block if this function is ASMJIT_ASSERT(b != nullptr); // called, as both `a` and `b` must be valid blocks. ASMJIT_ASSERT(a != b); // Checked by `dominates()` and `properlyDominates()`. if (a == b) return a; // If `a` strictly dominates `b` then `a` is the nearest common dominator. if (_strictlyDominates(a, b)) return a; // If `b` strictly dominates `a` then `b` is the nearest common dominator. if (_strictlyDominates(b, a)) return b; const RABlock* entryBlock = this->entryBlock(); uint64_t timestamp = nextTimestamp(); // Mark all A's dominators. const RABlock* block = a->iDom(); while (block != entryBlock) { block->setTimestamp(timestamp); block = block->iDom(); } // Check all B's dominators against marked dominators of A. block = b->iDom(); while (block != entryBlock) { if (block->hasTimestamp(timestamp)) return block; block = block->iDom(); } return entryBlock; } // BaseRAPass - CFG - Utilities // ============================ Error BaseRAPass::removeUnreachableCode() noexcept { uint32_t numAllBlocks = blockCount(); uint32_t numReachableBlocks = reachableBlockCount(); // All reachable -> nothing to do. if (numAllBlocks == numReachableBlocks) return kErrorOk; #ifndef ASMJIT_NO_LOGGING StringTmp<256> sb; Logger* logger = getLoggerIf(DiagnosticOptions::kRADebugUnreachable); ASMJIT_RA_LOG_FORMAT(""[RemoveUnreachableCode - detected %u of %u unreachable blocks]\\n"", numAllBlocks - numReachableBlocks, numAllBlocks); #endif for (uint32_t i = 0; i < numAllBlocks; i++) { RABlock* block = _blocks[i]; if (block->isReachable()) continue; ASMJIT_RA_LOG_FORMAT("" Removing code from unreachable block {%u}\\n"", i); BaseNode* first = block->first(); BaseNode* last = block->last(); BaseNode* beforeFirst = first->prev(); BaseNode* afterLast = last->next(); BaseNode* node = first; while (node != afterLast) { BaseNode* next = node->next(); if (node->isCode() || node->isRemovable()) { #ifndef ASMJIT_NO_LOGGING if (logger) { sb.clear(); Formatter::formatNode(sb, _formatOptions, cc(), node); logger->logf("" %s\\n"", sb.data()); } #endif cc()->removeNode(node); } node = next; } if (beforeFirst->next() == afterLast) { block->setFirst(nullptr); block->setLast(nullptr); } else { block->setFirst(beforeFirst->next()); block->setLast(afterLast->prev()); } } return kErrorOk; } BaseNode* BaseRAPass::findSuccessorStartingAt(BaseNode* node) noexcept { while (node && (node->isInformative() || node->hasNoEffect())) node = node->next(); return node; } bool BaseRAPass::isNextTo(BaseNode* node, BaseNode* target) noexcept { for (;;) { node = node->next(); if (node == target) return true; if (!node) return false; if (node->isCode() || node->isData()) return false; } } // BaseRAPass - Registers - VirtReg / WorkReg Mapping // ================================================== Error BaseRAPass::_asWorkReg(VirtReg* vReg, RAWorkReg** out) noexcept { // Checked by `asWorkReg()` - must be true. ASMJIT_ASSERT(vReg->_workReg == nullptr); RegGroup group = vReg->group(); ASMJIT_ASSERT(group <= RegGroup::kMaxVirt); RAWorkRegs& wRegs = workRegs(); RAWorkRegs& wRegsByGroup = workRegs(group); ASMJIT_PROPAGATE(wRegs.willGrow(allocator())); ASMJIT_PROPAGATE(wRegsByGroup.willGrow(allocator())); RAWorkReg* wReg = zone()->newT(vReg, wRegs.size()); if (ASMJIT_UNLIKELY(!wReg)) return DebugUtils::errored(kErrorOutOfMemory); vReg->setWorkReg(wReg); if (!vReg->isStack()) wReg->setRegByteMask(Support::lsbMask(vReg->virtSize())); wRegs.appendUnsafe(wReg); wRegsByGroup.appendUnsafe(wReg); // Only used by RA logging. _maxWorkRegNameSize = Support::max(_maxWorkRegNameSize, vReg->nameSize()); *out = wReg; return kErrorOk; } RAAssignment::WorkToPhysMap* BaseRAPass::newWorkToPhysMap() noexcept { uint32_t count = workRegCount(); size_t size = WorkToPhysMap::sizeOf(count); // If no registers are used it could be zero, in that case return a dummy // map instead of NULL. if (ASMJIT_UNLIKELY(!size)) { static const RAAssignment::WorkToPhysMap nullMap = {{ 0 }}; return const_cast(&nullMap); } WorkToPhysMap* map = zone()->allocT(size); if (ASMJIT_UNLIKELY(!map)) return nullptr; map->reset(count); return map; } RAAssignment::PhysToWorkMap* BaseRAPass::newPhysToWorkMap() noexcept { uint32_t count = physRegTotal(); size_t size = PhysToWorkMap::sizeOf(count); PhysToWorkMap* map = zone()->allocT(size); if (ASMJIT_UNLIKELY(!map)) return nullptr; map->reset(count); return map; } // BaseRAPass - Registers - Liveness Analysis and Statistics // ========================================================= namespace LiveOps { typedef ZoneBitVector::BitWord BitWord; struct In { static ASMJIT_FORCE_INLINE BitWord op(BitWord dst, BitWord out, BitWord gen, BitWord kill) noexcept { DebugUtils::unused(dst); return (out | gen) & ~kill; } }; template static ASMJIT_FORCE_INLINE bool op(BitWord* dst, const BitWord* a, uint32_t n) noexcept { BitWord changed = 0; for (uint32_t i = 0; i < n; i++) { BitWord before = dst[i]; BitWord after = Operator::op(before, a[i]); dst[i] = after; changed |= (before ^ after); } return changed != 0; } template static ASMJIT_FORCE_INLINE bool op(BitWord* dst, const BitWord* a, const BitWord* b, uint32_t n) noexcept { BitWord changed = 0; for (uint32_t i = 0; i < n; i++) { BitWord before = dst[i]; BitWord after = Operator::op(before, a[i], b[i]); dst[i] = after; changed |= (before ^ after); } return changed != 0; } template static ASMJIT_FORCE_INLINE bool op(BitWord* dst, const BitWord* a, const BitWord* b, const BitWord* c, uint32_t n) noexcept { BitWord changed = 0; for (uint32_t i = 0; i < n; i++) { BitWord before = dst[i]; BitWord after = Operator::op(before, a[i], b[i], c[i]); dst[i] = after; changed |= (before ^ after); } return changed != 0; } static ASMJIT_FORCE_INLINE bool recalcInOut(RABlock* block, uint32_t numBitWords, bool initial = false) noexcept { bool changed = initial; const RABlocks& successors = block->successors(); uint32_t numSuccessors = successors.size(); // Calculate `OUT` based on `IN` of all successors. for (uint32_t i = 0; i < numSuccessors; i++) changed |= op(block->liveOut().data(), successors[i]->liveIn().data(), numBitWords); // Calculate `IN` based on `OUT`, `GEN`, and `KILL` bits. if (changed) changed = op(block->liveIn().data(), block->liveOut().data(), block->gen().data(), block->kill().data(), numBitWords); return changed; } } ASMJIT_FAVOR_SPEED Error BaseRAPass::buildLiveness() noexcept { #ifndef ASMJIT_NO_LOGGING Logger* logger = getLoggerIf(DiagnosticOptions::kRADebugLiveness); StringTmp<512> sb; #endif ASMJIT_RA_LOG_FORMAT(""[BuildLiveness]\\n""); uint32_t i; uint32_t numAllBlocks = blockCount(); uint32_t numReachableBlocks = reachableBlockCount(); uint32_t numVisits = numReachableBlocks; uint32_t numWorkRegs = workRegCount(); uint32_t numBitWords = ZoneBitVector::_wordsPerBits(numWorkRegs); if (!numWorkRegs) { ASMJIT_RA_LOG_FORMAT("" Done (no virtual registers)\\n""); return kErrorOk; } ZoneVector nUsesPerWorkReg; // Number of USEs of each RAWorkReg. ZoneVector nOutsPerWorkReg; // Number of OUTs of each RAWorkReg. ZoneVector nInstsPerBlock; // Number of instructions of each RABlock. ASMJIT_PROPAGATE(nUsesPerWorkReg.resize(allocator(), numWorkRegs)); ASMJIT_PROPAGATE(nOutsPerWorkReg.resize(allocator(), numWorkRegs)); ASMJIT_PROPAGATE(nInstsPerBlock.resize(allocator(), numAllBlocks)); // Calculate GEN/KILL of Each Block // -------------------------------- for (i = 0; i < numReachableBlocks; i++) { RABlock* block = _pov[i]; ASMJIT_PROPAGATE(block->resizeLiveBits(numWorkRegs)); BaseNode* node = block->last(); BaseNode* stop = block->first(); uint32_t nInsts = 0; for (;;) { if (node->isInst()) { InstNode* inst = node->as(); RAInst* raInst = inst->passData(); ASMJIT_ASSERT(raInst != nullptr); RATiedReg* tiedRegs = raInst->tiedRegs(); uint32_t count = raInst->tiedCount(); for (uint32_t j = 0; j < count; j++) { RATiedReg* tiedReg = &tiedRegs[j]; uint32_t workId = tiedReg->workId(); // Update `nUses` and `nOuts`. nUsesPerWorkReg[workId] += 1u; nOutsPerWorkReg[workId] += uint32_t(tiedReg->isWrite()); // Mark as: // KILL - if this VirtReg is killed afterwards. // LAST - if this VirtReg is last in this basic block. if (block->kill().bitAt(workId)) tiedReg->addFlags(RATiedFlags::kKill); else if (!block->gen().bitAt(workId)) tiedReg->addFlags(RATiedFlags::kLast); if (tiedReg->isWriteOnly()) { // KILL. block->kill().setBit(workId, true); } else { // GEN. block->kill().setBit(workId, false); block->gen().setBit(workId, true); } if (tiedReg->isLeadConsecutive()) { RAWorkReg* workReg = workRegById(workId); workReg->markLeadConsecutive(); } if (tiedReg->hasConsecutiveParent()) { RAWorkReg* consecutiveParentReg = workRegById(tiedReg->consecutiveParent()); consecutiveParentReg->addImmediateConsecutive(allocator(), workId); } } nInsts++; } if (node == stop) break; node = node->prev(); ASMJIT_ASSERT(node != nullptr); } nInstsPerBlock[block->blockId()] = nInsts; } // Calculate IN/OUT of Each Block // ------------------------------ { ZoneStack workList; ZoneBitVector workBits; ASMJIT_PROPAGATE(workList.init(allocator())); ASMJIT_PROPAGATE(workBits.resize(allocator(), blockCount(), true)); for (i = 0; i < numReachableBlocks; i++) { RABlock* block = _pov[i]; LiveOps::recalcInOut(block, numBitWords, true); ASMJIT_PROPAGATE(workList.append(block)); } while (!workList.empty()) { RABlock* block = workList.popFirst(); uint32_t blockId = block->blockId(); workBits.setBit(blockId, false); if (LiveOps::recalcInOut(block, numBitWords)) { const RABlocks& predecessors = block->predecessors(); uint32_t numPredecessors = predecessors.size(); for (uint32_t j = 0; j < numPredecessors; j++) { RABlock* pred = predecessors[j]; if (!workBits.bitAt(pred->blockId())) { workBits.setBit(pred->blockId(), true); ASMJIT_PROPAGATE(workList.append(pred)); } } } numVisits++; } workList.reset(); workBits.release(allocator()); } ASMJIT_RA_LOG_COMPLEX({ logger->logf("" LiveIn/Out Done (%u visits)\\n"", numVisits); for (i = 0; i < numAllBlocks; i++) { RABlock* block = _blocks[i]; ASMJIT_PROPAGATE(sb.assignFormat("" {#%u}\\n"", block->blockId())); ASMJIT_PROPAGATE(_dumpBlockLiveness(sb, block)); logger->log(sb); } }); // Reserve the space in each `RAWorkReg` for references // ---------------------------------------------------- for (i = 0; i < numWorkRegs; i++) { RAWorkReg* workReg = workRegById(i); ASMJIT_PROPAGATE(workReg->_refs.reserve(allocator(), nUsesPerWorkReg[i])); ASMJIT_PROPAGATE(workReg->_writes.reserve(allocator(), nOutsPerWorkReg[i])); } // Assign block and instruction positions, build LiveCount and LiveSpans // --------------------------------------------------------------------- uint32_t position = 2; for (i = 0; i < numAllBlocks; i++) { RABlock* block = _blocks[i]; if (!block->isReachable()) continue; BaseNode* node = block->first(); BaseNode* stop = block->last(); uint32_t endPosition = position + nInstsPerBlock[i] * 2; block->setFirstPosition(position); block->setEndPosition(endPosition); RALiveCount curLiveCount; RALiveCount maxLiveCount; // Process LIVE-IN. ZoneBitVector::ForEachBitSet it(block->liveIn()); while (it.hasNext()) { RAWorkReg* workReg = _workRegs[uint32_t(it.next())]; curLiveCount[workReg->group()]++; ASMJIT_PROPAGATE(workReg->liveSpans().openAt(allocator(), position, endPosition)); } for (;;) { if (node->isInst()) { InstNode* inst = node->as(); RAInst* raInst = inst->passData(); ASMJIT_ASSERT(raInst != nullptr); RATiedReg* tiedRegs = raInst->tiedRegs(); uint32_t count = raInst->tiedCount(); inst->setPosition(position); raInst->_liveCount = curLiveCount; for (uint32_t j = 0; j < count; j++) { RATiedReg* tiedReg = &tiedRegs[j]; uint32_t workId = tiedReg->workId(); // Create refs and writes. RAWorkReg* workReg = workRegById(workId); workReg->_refs.appendUnsafe(node); if (tiedReg->isWrite()) workReg->_writes.appendUnsafe(node); // We couldn't calculate this in previous steps, but since we know all LIVE-OUT at this point it becomes // trivial. If this is the last instruction that uses this `workReg` and it's not LIVE-OUT then it is // KILLed here. if (tiedReg->isLast() && !block->liveOut().bitAt(workId)) tiedReg->addFlags(RATiedFlags::kKill); LiveRegSpans& liveSpans = workReg->liveSpans(); bool wasOpen; ASMJIT_PROPAGATE(liveSpans.openAt(allocator(), position + !tiedReg->isRead(), endPosition, wasOpen)); RegGroup group = workReg->group(); if (!wasOpen) { curLiveCount[group]++; raInst->_liveCount[group]++; } if (tiedReg->isKill()) { liveSpans.closeAt(position + !tiedReg->isRead() + 1); curLiveCount[group]--; } // Update `RAWorkReg::useIdMask` and `RAWorkReg::hintRegId`. if (tiedReg->hasUseId()) { uint32_t useId = tiedReg->useId(); workReg->addUseIdMask(Support::bitMask(useId)); if (!workReg->hasHintRegId() && !Support::bitTest(raInst->_clobberedRegs[group], useId)) workReg->setHintRegId(useId); } if (tiedReg->useRegMask()) { workReg->restrictPreferredMask(tiedReg->useRegMask()); if (workReg->isLeadConsecutive()) workReg->restrictConsecutiveMask(tiedReg->useRegMask()); } if (tiedReg->outRegMask()) { workReg->restrictPreferredMask(tiedReg->outRegMask()); if (workReg->isLeadConsecutive()) workReg->restrictConsecutiveMask(tiedReg->outRegMask()); } // Update `RAWorkReg::clobberedSurvivalMask`. if (raInst->_clobberedRegs[group] && !tiedReg->isOutOrKill()) { workReg->addClobberSurvivalMask(raInst->_clobberedRegs[group]); } } position += 2; maxLiveCount.op(raInst->_liveCount); } if (node == stop) break; node = node->next(); ASMJIT_ASSERT(node != nullptr); } block->_maxLiveCount = maxLiveCount; _globalMaxLiveCount.op(maxLiveCount); ASMJIT_ASSERT(position == block->endPosition()); } // Calculate WorkReg statistics // ---------------------------- for (i = 0; i < numWorkRegs; i++) { RAWorkReg* workReg = _workRegs[i]; LiveRegSpans& spans = workReg->liveSpans(); uint32_t width = spans.width(); float freq = width ? float(double(workReg->_refs.size()) / double(width)) : float(0); RALiveStats& stats = workReg->liveStats(); stats._width = width; stats._freq = freq; stats._priority = freq + float(int(workReg->virtReg()->weight())) * 0.01f; } ASMJIT_RA_LOG_COMPLEX({ sb.clear(); _dumpLiveSpans(sb); logger->log(sb); }); nUsesPerWorkReg.release(allocator()); nOutsPerWorkReg.release(allocator()); nInstsPerBlock.release(allocator()); return kErrorOk; } Error BaseRAPass::assignArgIndexToWorkRegs() noexcept { ZoneBitVector& liveIn = entryBlock()->liveIn(); uint32_t argCount = func()->argCount(); for (uint32_t argIndex = 0; argIndex < argCount; argIndex++) { for (uint32_t valueIndex = 0; valueIndex < Globals::kMaxValuePack; valueIndex++) { // Unassigned argument. const RegOnly& regArg = func()->argPack(argIndex)[valueIndex]; if (!regArg.isReg() || !cc()->isVirtIdValid(regArg.id())) continue; VirtReg* virtReg = cc()->virtRegById(regArg.id()); if (!virtReg) continue; // Unreferenced argument. RAWorkReg* workReg = virtReg->workReg(); if (!workReg) continue; // Overwritten argument. uint32_t workId = workReg->workId(); if (!liveIn.bitAt(workId)) continue; workReg->setArgIndex(argIndex, valueIndex); const FuncValue& arg = func()->detail().arg(argIndex, valueIndex); if (arg.isReg() && _archTraits->regTypeToGroup(arg.regType()) == workReg->group()) { workReg->setHintRegId(arg.regId()); } } } return kErrorOk; } // BaseRAPass - Allocation - Global // ================================ #ifndef ASMJIT_NO_LOGGING static void RAPass_dumpSpans(String& sb, uint32_t index, const LiveRegSpans& liveSpans) noexcept { sb.appendFormat("" %02u: "", index); for (uint32_t i = 0; i < liveSpans.size(); i++) { const LiveRegSpan& liveSpan = liveSpans[i]; if (i) sb.append("", ""); sb.appendFormat(""[%u:%u@%u]"", liveSpan.a, liveSpan.b, liveSpan.id); } sb.append('\\n'); } #endif Error BaseRAPass::runGlobalAllocator() noexcept { ASMJIT_PROPAGATE(initGlobalLiveSpans()); for (RegGroup group : RegGroupVirtValues{}) { ASMJIT_PROPAGATE(binPack(group)); } return kErrorOk; } ASMJIT_FAVOR_SPEED Error BaseRAPass::initGlobalLiveSpans() noexcept { for (RegGroup group : RegGroupVirtValues{}) { size_t physCount = _physRegCount[group]; LiveRegSpans* liveSpans = nullptr; if (physCount) { liveSpans = allocator()->allocT(physCount * sizeof(LiveRegSpans)); if (ASMJIT_UNLIKELY(!liveSpans)) return DebugUtils::errored(kErrorOutOfMemory); for (size_t physId = 0; physId < physCount; physId++) new(&liveSpans[physId]) LiveRegSpans(); } _globalLiveSpans[group] = liveSpans; } return kErrorOk; } struct RAConsecutiveReg { RAWorkReg* workReg; RAWorkReg* parentReg; }; ASMJIT_FAVOR_SPEED Error BaseRAPass::binPack(RegGroup group) noexcept { if (workRegCount(group) == 0) return kErrorOk; #ifndef ASMJIT_NO_LOGGING Logger* logger = getLoggerIf(DiagnosticOptions::kRADebugAssignment); StringTmp<512> sb; ASMJIT_RA_LOG_FORMAT(""[BinPack] Available=%u (0x%08X) Count=%u RegGroup=%u\\n"", Support::popcnt(_availableRegs[group]), _availableRegs[group], workRegCount(group), uint32_t(group)); #endif uint32_t i; uint32_t physCount = _physRegCount[group]; RAWorkRegs workRegs; ZoneVector consecutiveRegs; LiveRegSpans tmpSpans; ASMJIT_PROPAGATE(workRegs.concat(allocator(), this->workRegs(group))); workRegs.sort([](const RAWorkReg* a, const RAWorkReg* b) noexcept { return b->liveStats().priority() - a->liveStats().priority(); }); uint32_t numWorkRegs = workRegs.size(); RegMask availableRegs = _availableRegs[group]; // First try to pack everything that provides register-id hint as these are most likely function arguments and fixed // (precolored) virtual registers. if (!workRegs.empty()) { uint32_t dstIndex = 0; for (i = 0; i < numWorkRegs; i++) { RAWorkReg* workReg = workRegs[i]; if (workReg->isLeadConsecutive()) { ASMJIT_PROPAGATE(consecutiveRegs.append(allocator(), RAConsecutiveReg{workReg, nullptr})); workReg->markProcessedConsecutive(); } if (workReg->hasHintRegId()) { uint32_t physId = workReg->hintRegId(); if (Support::bitTest(availableRegs, physId)) { LiveRegSpans& live = _globalLiveSpans[group][physId]; Error err = tmpSpans.nonOverlappingUnionOf(allocator(), live, workReg->liveSpans(), LiveRegData(workReg->virtId())); if (err == kErrorOk) { live.swap(tmpSpans); workReg->setHomeRegId(physId); workReg->markAllocated(); continue; } if (err != 0xFFFFFFFFu) return err; } } workRegs[dstIndex++] = workReg; } workRegs._setSize(dstIndex); numWorkRegs = dstIndex; } // Allocate consecutive registers - both leads and all consecutives. This is important and prioritized over the rest, // because once a lead is allocated we really need to allocate its consecutives, otherwise we may bin pack other // registers into their places, which would result in wrong hints to the local allocator, and then into many moves // or spills. if (!consecutiveRegs.empty()) { // This loop appends all other consecutive registers into `consecutiveRegs` array. Leads are at the beginning, // non-leads follow. i = 0; for (;;) { uint32_t stop = consecutiveRegs.size(); if (i == stop) break; while (i < stop) { RAWorkReg* workReg = consecutiveRegs[i].workReg; if (workReg->hasImmediateConsecutives()) { ZoneBitVector::ForEachBitSet it(workReg->immediateConsecutives()); while (it.hasNext()) { uint32_t consecutiveWorkId = uint32_t(it.next()); RAWorkReg* consecutiveReg = workRegById(consecutiveWorkId); if (!consecutiveReg->isProcessedConsecutive()) { ASMJIT_PROPAGATE(consecutiveRegs.append(allocator(), RAConsecutiveReg{consecutiveReg, workReg})); consecutiveReg->markProcessedConsecutive(); } } } i++; } } uint32_t numConsecutiveRegs = consecutiveRegs.size(); for (i = 0; i < numConsecutiveRegs; i++) { RAWorkReg* workReg = consecutiveRegs[i].workReg; if (workReg->isAllocated()) continue; RAWorkReg* parentReg = consecutiveRegs[i].parentReg; RegMask physRegs = 0; if (!parentReg) { physRegs = availableRegs & workReg->preferredMask(); if (!physRegs) { physRegs = availableRegs & workReg->consecutiveMask(); // NOTE: This should never be true as it would mean we would never allocate this virtual register // (not here, and not later when local register allocator processes RATiedReg sets). if (ASMJIT_UNLIKELY(!physRegs)) return DebugUtils::errored(kErrorConsecutiveRegsAllocation); } } else if (parentReg->hasHomeRegId()) { uint32_t consecutiveId = parentReg->homeRegId() + 1; // NOTE: We don't support wrapping. If this goes beyond all allocable registers there is something wrong. if (consecutiveId > 31 || !Support::bitTest(availableRegs, consecutiveId)) return DebugUtils::errored(kErrorConsecutiveRegsAllocation); workReg->setHintRegId(consecutiveId); physRegs = Support::bitMask(consecutiveId); } while (physRegs) { uint32_t physId = Support::bitSizeOf() - 1 - Support::clz(physRegs); LiveRegSpans& live = _globalLiveSpans[group][physId]; Error err = tmpSpans.nonOverlappingUnionOf(allocator(), live, workReg->liveSpans(), LiveRegData(workReg->virtId())); if (err == kErrorOk) { workReg->setHomeRegId(physId); workReg->markAllocated(); live.swap(tmpSpans); break; } if (ASMJIT_UNLIKELY(err != 0xFFFFFFFFu)) return err; physRegs ^= Support::bitMask(physId); } } } // Try to pack the rest. if (!workRegs.empty()) { uint32_t dstIndex = 0; for (i = 0; i < numWorkRegs; i++) { RAWorkReg* workReg = workRegs[i]; if (workReg->isAllocated()) continue; RegMask physRegs = availableRegs; if (physRegs & workReg->preferredMask()) physRegs &= workReg->preferredMask(); while (physRegs) { RegMask preferredMask = physRegs; uint32_t physId = Support::ctz(preferredMask); if (workReg->clobberSurvivalMask()) { preferredMask &= workReg->clobberSurvivalMask(); if (preferredMask) physId = Support::ctz(preferredMask); } LiveRegSpans& live = _globalLiveSpans[group][physId]; Error err = tmpSpans.nonOverlappingUnionOf(allocator(), live, workReg->liveSpans(), LiveRegData(workReg->virtId())); if (err == kErrorOk) { workReg->setHomeRegId(physId); workReg->markAllocated(); live.swap(tmpSpans); break; } if (ASMJIT_UNLIKELY(err != 0xFFFFFFFFu)) return err; physRegs ^= Support::bitMask(physId); } // Keep it in `workRegs` if it was not allocated. if (!physRegs) workRegs[dstIndex++] = workReg; } workRegs._setSize(dstIndex); numWorkRegs = dstIndex; } ASMJIT_RA_LOG_COMPLEX({ for (uint32_t physId = 0; physId < physCount; physId++) { LiveRegSpans& live = _globalLiveSpans[group][physId]; if (live.empty()) continue; sb.clear(); RAPass_dumpSpans(sb, physId, live); logger->log(sb); } }); // Maybe unused if logging is disabled. DebugUtils::unused(physCount); if (workRegs.empty()) { ASMJIT_RA_LOG_FORMAT("" Completed.\\n""); } else { _strategy[group].setType(RAStrategyType::kComplex); for (RAWorkReg* workReg : workRegs) workReg->markStackPreferred(); ASMJIT_RA_LOG_COMPLEX({ uint32_t count = workRegs.size(); sb.clear(); sb.appendFormat("" Unassigned (%u): "", count); for (i = 0; i < numWorkRegs; i++) { RAWorkReg* workReg = workRegs[i]; if (i) sb.append("", ""); sb.append(workReg->name()); } sb.append('\\n'); logger->log(sb); }); } return kErrorOk; } // BaseRAPass - Allocation - Local // =============================== Error BaseRAPass::runLocalAllocator() noexcept { RALocalAllocator lra(this); ASMJIT_PROPAGATE(lra.init()); if (!blockCount()) return kErrorOk; // The allocation is done when this reaches zero. uint32_t blocksRemaining = reachableBlockCount(); // Current block. uint32_t blockId = 0; RABlock* block = _blocks[blockId]; // The first block (entry) must always be reachable. ASMJIT_ASSERT(block->isReachable()); // Assign function arguments for the initial block. The `lra` is valid now. lra.makeInitialAssignment(); ASMJIT_PROPAGATE(setBlockEntryAssignment(block, block, lra._curAssignment)); // The loop starts from the first block and iterates blocks in order, however, the algorithm also allows to jump to // any other block when finished if it's a jump target. In-order iteration just makes sure that all blocks are visited. for (;;) { BaseNode* first = block->first(); BaseNode* last = block->last(); BaseNode* terminator = block->hasTerminator() ? last : nullptr; BaseNode* beforeFirst = first->prev(); BaseNode* afterLast = last->next(); bool unconditionalJump = false; RABlock* consecutive = nullptr; if (block->hasSuccessors()) consecutive = block->successors()[0]; lra.setBlock(block); block->makeAllocated(); BaseNode* node = first; while (node != afterLast) { BaseNode* next = node->next(); if (node->isInst()) { InstNode* inst = node->as(); if (ASMJIT_UNLIKELY(inst == terminator)) { const RABlocks& successors = block->successors(); if (block->hasConsecutive()) { ASMJIT_PROPAGATE(lra.allocBranch(inst, successors.last(), successors.first())); node = next; continue; } else if (successors.size() > 1) { RABlock* cont = block->hasConsecutive() ? successors.first() : nullptr; ASMJIT_PROPAGATE(lra.allocJumpTable(inst, successors, cont)); node = next; continue; } else { // Otherwise this is an unconditional jump, special handling isn't required. unconditionalJump = true; } } ASMJIT_PROPAGATE(lra.allocInst(inst)); if (inst->type() == NodeType::kInvoke) ASMJIT_PROPAGATE(emitPreCall(inst->as())); else ASMJIT_PROPAGATE(lra.spillAfterAllocation(inst)); } node = next; } if (consecutive) { BaseNode* prev = afterLast ? afterLast->prev() : cc()->lastNode(); cc()->_setCursor(unconditionalJump ? prev->prev() : prev); if (consecutive->hasEntryAssignment()) { ASMJIT_PROPAGATE( lra.switchToAssignment( consecutive->entryPhysToWorkMap(), consecutive->entryWorkToPhysMap(), consecutive->liveIn(), consecutive->isAllocated(), false)); } else { ASMJIT_PROPAGATE(lra.spillRegsBeforeEntry(consecutive)); ASMJIT_PROPAGATE(setBlockEntryAssignment(consecutive, block, lra._curAssignment)); lra._curAssignment.copyFrom(consecutive->entryPhysToWorkMap(), consecutive->entryWorkToPhysMap()); } } // Important as the local allocator can insert instructions before // and after any instruction within the basic block. block->setFirst(beforeFirst->next()); block->setLast(afterLast ? afterLast->prev() : cc()->lastNode()); if (--blocksRemaining == 0) break; // Switch to the next consecutive block, if any. if (consecutive) { block = consecutive; if (!block->isAllocated()) continue; } // Get the next block. for (;;) { if (++blockId >= blockCount()) blockId = 0; block = _blocks[blockId]; if (!block->isReachable() || block->isAllocated() || !block->hasEntryAssignment()) continue; break; } // If we switched to some block we have to update the local allocator. lra.replaceAssignment(block->entryPhysToWorkMap(), block->entryWorkToPhysMap()); } _clobberedRegs.op(lra._clobberedRegs); return kErrorOk; } Error BaseRAPass::setBlockEntryAssignment(RABlock* block, const RABlock* fromBlock, const RAAssignment& fromAssignment) noexcept { if (block->hasSharedAssignmentId()) { uint32_t sharedAssignmentId = block->sharedAssignmentId(); // Shouldn't happen. Entry assignment of a block that has a shared-state will assign to all blocks // with the same sharedAssignmentId. It's a bug if the shared state has been already assigned. if (!_sharedAssignments[sharedAssignmentId].empty()) return DebugUtils::errored(kErrorInvalidState); return setSharedAssignment(sharedAssignmentId, fromAssignment); } PhysToWorkMap* physToWorkMap = clonePhysToWorkMap(fromAssignment.physToWorkMap()); WorkToPhysMap* workToPhysMap = cloneWorkToPhysMap(fromAssignment.workToPhysMap()); if (ASMJIT_UNLIKELY(!physToWorkMap || !workToPhysMap)) return DebugUtils::errored(kErrorOutOfMemory); block->setEntryAssignment(physToWorkMap, workToPhysMap); // True if this is the first (entry) block, nothing to do in this case. if (block == fromBlock) { // Entry block should never have a shared state. if (block->hasSharedAssignmentId()) return DebugUtils::errored(kErrorInvalidState); return kErrorOk; } RAAssignment as; as.initLayout(_physRegCount, workRegs()); as.initMaps(physToWorkMap, workToPhysMap); const ZoneBitVector& liveOut = fromBlock->liveOut(); const ZoneBitVector& liveIn = block->liveIn(); // It's possible that `fromBlock` has LIVE-OUT regs that `block` doesn't // have in LIVE-IN, these have to be unassigned. { ZoneBitVector::ForEachBitOp it(liveOut, liveIn); while (it.hasNext()) { uint32_t workId = uint32_t(it.next()); RAWorkReg* workReg = workRegById(workId); RegGroup group = workReg->group(); uint32_t physId = as.workToPhysId(group, workId); if (physId != RAAssignment::kPhysNone) as.unassign(group, workId, physId); } } return blockEntryAssigned(as); } Error BaseRAPass::setSharedAssignment(uint32_t sharedAssignmentId, const RAAssignment& fromAssignment) noexcept { ASMJIT_ASSERT(_sharedAssignments[sharedAssignmentId].empty()); PhysToWorkMap* physToWorkMap = clonePhysToWorkMap(fromAssignment.physToWorkMap()); WorkToPhysMap* workToPhysMap = cloneWorkToPhysMap(fromAssignment.workToPhysMap()); if (ASMJIT_UNLIKELY(!physToWorkMap || !workToPhysMap)) return DebugUtils::errored(kErrorOutOfMemory); _sharedAssignments[sharedAssignmentId].assignMaps(physToWorkMap, workToPhysMap); ZoneBitVector& sharedLiveIn = _sharedAssignments[sharedAssignmentId]._liveIn; ASMJIT_PROPAGATE(sharedLiveIn.resize(allocator(), workRegCount())); RAAssignment as; as.initLayout(_physRegCount, workRegs()); Support::Array sharedAssigned {}; for (RABlock* block : blocks()) { if (block->sharedAssignmentId() == sharedAssignmentId) { ASMJIT_ASSERT(!block->hasEntryAssignment()); PhysToWorkMap* entryPhysToWorkMap = clonePhysToWorkMap(fromAssignment.physToWorkMap()); WorkToPhysMap* entryWorkToPhysMap = cloneWorkToPhysMap(fromAssignment.workToPhysMap()); if (ASMJIT_UNLIKELY(!entryPhysToWorkMap || !entryWorkToPhysMap)) return DebugUtils::errored(kErrorOutOfMemory); block->setEntryAssignment(entryPhysToWorkMap, entryWorkToPhysMap); as.initMaps(entryPhysToWorkMap, entryWorkToPhysMap); const ZoneBitVector& liveIn = block->liveIn(); sharedLiveIn.or_(liveIn); for (RegGroup group : RegGroupVirtValues{}) { sharedAssigned[group] |= entryPhysToWorkMap->assigned[group]; Support::BitWordIterator it(entryPhysToWorkMap->assigned[group]); while (it.hasNext()) { uint32_t physId = it.next(); uint32_t workId = as.physToWorkId(group, physId); if (!liveIn.bitAt(workId)) as.unassign(group, workId, physId); } } } } { as.initMaps(physToWorkMap, workToPhysMap); for (RegGroup group : RegGroupVirtValues{}) { Support::BitWordIterator it(_availableRegs[group] & ~sharedAssigned[group]); while (it.hasNext()) { uint32_t physId = it.next(); if (as.isPhysAssigned(group, physId)) { uint32_t workId = as.physToWorkId(group, physId); as.unassign(group, workId, physId); } } } } return blockEntryAssigned(as); } Error BaseRAPass::blockEntryAssigned(const RAAssignment& as) noexcept { // Complex allocation strategy requires to record register assignments upon block entry (or per shared state). for (RegGroup group : RegGroupVirtValues{}) { if (!_strategy[group].isComplex()) continue; Support::BitWordIterator it(as.assigned(group)); while (it.hasNext()) { uint32_t physId = it.next(); uint32_t workId = as.physToWorkId(group, physId); RAWorkReg* workReg = workRegById(workId); workReg->addAllocatedMask(Support::bitMask(physId)); } } return kErrorOk; } // BaseRAPass - Allocation - Utilities // =================================== Error BaseRAPass::useTemporaryMem(BaseMem& out, uint32_t size, uint32_t alignment) noexcept { ASMJIT_ASSERT(alignment <= 64); if (_temporaryMem.isNone()) { ASMJIT_PROPAGATE(cc()->_newStack(&_temporaryMem.as(), size, alignment)); } else { ASMJIT_ASSERT(_temporaryMem.as().isRegHome()); uint32_t virtId = _temporaryMem.as().baseId(); VirtReg* virtReg = cc()->virtRegById(virtId); cc()->setStackSize(virtId, Support::max(virtReg->virtSize(), size), Support::max(virtReg->alignment(), alignment)); } out = _temporaryMem.as(); return kErrorOk; } // BaseRAPass - Allocation - Prolog & Epilog // ========================================= Error BaseRAPass::updateStackFrame() noexcept { // Update some StackFrame information that we updated during allocation. The only information we don't have at the // moment is final local stack size, which is calculated last. FuncFrame& frame = func()->frame(); for (RegGroup group : RegGroupVirtValues{}) frame.addDirtyRegs(group, _clobberedRegs[group]); frame.setLocalStackAlignment(_stackAllocator.alignment()); // If there are stack arguments that are not assigned to registers upon entry and the function doesn't require // dynamic stack alignment we keep these arguments where they are. This will also mark all stack slots that match // these arguments as allocated. if (_numStackArgsToStackSlots) ASMJIT_PROPAGATE(_markStackArgsToKeep()); // Calculate offsets of all stack slots and update StackSize to reflect the calculated local stack size. ASMJIT_PROPAGATE(_stackAllocator.calculateStackFrame()); frame.setLocalStackSize(_stackAllocator.stackSize()); // Update the stack frame based on `_argsAssignment` and finalize it. Finalization means to apply final calculation // to the stack layout. ASMJIT_PROPAGATE(_argsAssignment.updateFuncFrame(frame)); ASMJIT_PROPAGATE(frame.finalize()); // StackAllocator allocates all stots starting from [0], adjust them when necessary. if (frame.localStackOffset() != 0) ASMJIT_PROPAGATE(_stackAllocator.adjustSlotOffsets(int32_t(frame.localStackOffset()))); // Again, if there are stack arguments allocated in function's stack we have to handle them. This handles all cases // (either regular or dynamic stack alignment). if (_numStackArgsToStackSlots) ASMJIT_PROPAGATE(_updateStackArgs()); return kErrorOk; } Error BaseRAPass::_markStackArgsToKeep() noexcept { FuncFrame& frame = func()->frame(); bool hasSAReg = frame.hasPreservedFP() || !frame.hasDynamicAlignment(); RAWorkRegs& workRegs = _workRegs; uint32_t numWorkRegs = workRegCount(); for (uint32_t workId = 0; workId < numWorkRegs; workId++) { RAWorkReg* workReg = workRegs[workId]; if (workReg->hasFlag(RAWorkRegFlags::kStackArgToStack)) { ASMJIT_ASSERT(workReg->hasArgIndex()); const FuncValue& srcArg = _func->detail().arg(workReg->argIndex()); // If the register doesn't have stack slot then we failed. It doesn't make much sense as it was marked as // `kFlagStackArgToStack`, which requires the WorkReg was live-in upon function entry. RAStackSlot* slot = workReg->stackSlot(); if (ASMJIT_UNLIKELY(!slot)) return DebugUtils::errored(kErrorInvalidState); if (hasSAReg && srcArg.isStack() && !srcArg.isIndirect()) { uint32_t typeSize = TypeUtils::sizeOf(srcArg.typeId()); if (typeSize == slot->size()) { slot->addFlags(RAStackSlot::kFlagStackArg); continue; } } // NOTE: Update StackOffset here so when `_argsAssignment.updateFuncFrame()` is called it will take into // consideration moving to stack slots. Without this we may miss some scratch registers later. FuncValue& dstArg = _argsAssignment.arg(workReg->argIndex(), workReg->argValueIndex()); dstArg.assignStackOffset(0); } } return kErrorOk; } Error BaseRAPass::_updateStackArgs() noexcept { FuncFrame& frame = func()->frame(); RAWorkRegs& workRegs = _workRegs; uint32_t numWorkRegs = workRegCount(); for (uint32_t workId = 0; workId < numWorkRegs; workId++) { RAWorkReg* workReg = workRegs[workId]; if (workReg->hasFlag(RAWorkRegFlags::kStackArgToStack)) { ASMJIT_ASSERT(workReg->hasArgIndex()); RAStackSlot* slot = workReg->stackSlot(); if (ASMJIT_UNLIKELY(!slot)) return DebugUtils::errored(kErrorInvalidState); if (slot->isStackArg()) { const FuncValue& srcArg = _func->detail().arg(workReg->argIndex()); if (frame.hasPreservedFP()) { slot->setBaseRegId(_fp.id()); slot->setOffset(int32_t(frame.saOffsetFromSA()) + srcArg.stackOffset()); } else { slot->setOffset(int32_t(frame.saOffsetFromSP()) + srcArg.stackOffset()); } } else { FuncValue& dstArg = _argsAssignment.arg(workReg->argIndex(), workReg->argValueIndex()); dstArg.setStackOffset(slot->offset()); } } } return kErrorOk; } Error BaseRAPass::insertPrologEpilog() noexcept { FuncFrame& frame = _func->frame(); cc()->_setCursor(func()); ASMJIT_PROPAGATE(cc()->emitProlog(frame)); ASMJIT_PROPAGATE(_iEmitHelper->emitArgsAssignment(frame, _argsAssignment)); cc()->_setCursor(func()->exitNode()); ASMJIT_PROPAGATE(cc()->emitEpilog(frame)); return kErrorOk; } // BaseRAPass - Rewriter // ===================== Error BaseRAPass::rewrite() noexcept { return _rewrite(_func, _stop); } // BaseRAPass - Logging // ==================== #ifndef ASMJIT_NO_LOGGING static void RAPass_formatLiveness(BaseRAPass* pass, String& sb, const RAInst* raInst) noexcept { const RATiedReg* tiedRegs = raInst->tiedRegs(); uint32_t tiedCount = raInst->tiedCount(); for (uint32_t i = 0; i < tiedCount; i++) { const RATiedReg& tiedReg = tiedRegs[i]; if (i != 0) sb.append(' '); sb.appendFormat(""%s{"", pass->workRegById(tiedReg.workId())->name()); sb.append(tiedReg.isReadWrite() ? 'X' : tiedReg.isRead() ? 'R' : tiedReg.isWrite() ? 'W' : '?'); if (tiedReg.isLeadConsecutive()) sb.appendFormat(""|Lead[%u]"", tiedReg.consecutiveData() + 1u); if (tiedReg.hasUseId()) sb.appendFormat(""|Use=%u"", tiedReg.useId()); else if (tiedReg.isUse()) sb.append(""|Use""); if (tiedReg.isUseConsecutive() && !tiedReg.isLeadConsecutive()) sb.appendFormat(""+%u"", tiedReg.consecutiveData()); if (tiedReg.hasOutId()) sb.appendFormat(""|Out=%u"", tiedReg.outId()); else if (tiedReg.isOut()) sb.append(""|Out""); if (tiedReg.isOutConsecutive() && !tiedReg.isLeadConsecutive()) sb.appendFormat(""+%u"", tiedReg.consecutiveData()); if (tiedReg.isLast()) sb.append(""|Last""); if (tiedReg.isKill()) sb.append(""|Kill""); sb.append(""}""); } } ASMJIT_FAVOR_SIZE Error BaseRAPass::annotateCode() noexcept { StringTmp<1024> sb; for (const RABlock* block : _blocks) { BaseNode* node = block->first(); if (!node) continue; BaseNode* last = block->last(); for (;;) { sb.clear(); Formatter::formatNode(sb, _formatOptions, cc(), node); if (hasDiagnosticOption(DiagnosticOptions::kRADebugLiveness) && node->isInst() && node->hasPassData()) { const RAInst* raInst = node->passData(); if (raInst->tiedCount() > 0) { sb.padEnd(40); sb.append("" | ""); RAPass_formatLiveness(this, sb, raInst); } } node->setInlineComment(static_cast(cc()->_dataZone.dup(sb.data(), sb.size(), true))); if (node == last) break; node = node->next(); } } return kErrorOk; } ASMJIT_FAVOR_SIZE Error BaseRAPass::_dumpBlockIds(String& sb, const RABlocks& blocks) noexcept { for (uint32_t i = 0, size = blocks.size(); i < size; i++) { const RABlock* block = blocks[i]; if (i != 0) ASMJIT_PROPAGATE(sb.appendFormat("", #%u"", block->blockId())); else ASMJIT_PROPAGATE(sb.appendFormat(""#%u"", block->blockId())); } return kErrorOk; } ASMJIT_FAVOR_SIZE Error BaseRAPass::_dumpBlockLiveness(String& sb, const RABlock* block) noexcept { for (uint32_t liveType = 0; liveType < RABlock::kLiveCount; liveType++) { const char* bitsName = liveType == RABlock::kLiveIn ? ""IN "" : liveType == RABlock::kLiveOut ? ""OUT "" : liveType == RABlock::kLiveGen ? ""GEN "" : ""KILL""; const ZoneBitVector& bits = block->_liveBits[liveType]; uint32_t size = bits.size(); ASMJIT_ASSERT(size <= workRegCount()); uint32_t n = 0; for (uint32_t workId = 0; workId < size; workId++) { if (bits.bitAt(workId)) { RAWorkReg* wReg = workRegById(workId); if (!n) sb.appendFormat("" %s ["", bitsName); else sb.append("", ""); sb.append(wReg->name()); n++; } } if (n) sb.append(""]\\n""); } return kErrorOk; } ASMJIT_FAVOR_SIZE Error BaseRAPass::_dumpLiveSpans(String& sb) noexcept { uint32_t numWorkRegs = _workRegs.size(); uint32_t maxSize = _maxWorkRegNameSize; for (uint32_t workId = 0; workId < numWorkRegs; workId++) { RAWorkReg* workReg = _workRegs[workId]; sb.append("" ""); size_t oldSize = sb.size(); sb.append(workReg->name()); sb.padEnd(oldSize + maxSize); RALiveStats& stats = workReg->liveStats(); sb.appendFormat("" {id:%04u width: %-4u freq: %0.4f priority=%0.4f}"", workReg->virtId(), stats.width(), stats.freq(), stats.priority()); sb.append("": ""); LiveRegSpans& liveSpans = workReg->liveSpans(); for (uint32_t x = 0; x < liveSpans.size(); x++) { const LiveRegSpan& liveSpan = liveSpans[x]; if (x) sb.append("", ""); sb.appendFormat(""[%u:%u]"", liveSpan.a, liveSpan.b); } sb.append('\\n'); } return kErrorOk; } #endif ASMJIT_END_NAMESPACE #endif // !ASMJIT_NO_COMPILER ",16322,True,3171.5162022330856,median "/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the ""License""). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the ""license"" file accompanying this file. This file 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 #include ""APLClient/AplCoreTextMeasurement.h"" #include ""APLClient/AplCoreLocaleMethods.h"" #include ""APLClient/AplCoreConnectionManager.h"" #include ""APLClient/AplCoreViewhostMessage.h"" #include #include namespace APLClient { /// The keys used in ProvideState. static const char TOKEN_KEY[] = ""token""; static const char VERSION_KEY[] = ""version""; static const char VISUAL_CONTEXT_KEY[] = ""componentsVisibleOnScreen""; static const char DATASOURCE_CONTEXT_KEY[] = ""dataSources""; /// The value used in ProvideState. static const char CLIENT_VERSION_PREFIX[] = ""AplClientLibrary-""; // Key used in messaging static const char SEQNO_KEY[] = ""seqno""; /// APL Scaling bias constant static const float SCALING_BIAS_CONSTANT = 10.0f; /// APL Scaling cost override static const bool SCALING_SHAPE_OVERRIDES_COST = true; /// The keys used in APL context creation. static const char HEIGHT_KEY[] = ""height""; static const char WIDTH_KEY[] = ""width""; static const char DPI_KEY[] = ""dpi""; static const char MODE_KEY[] = ""mode""; static const char SHAPE_KEY[] = ""shape""; static const char SCALING_KEY[] = ""scaling""; static const char SCALE_FACTOR_KEY[] = ""scaleFactor""; static const char VIEWPORT_WIDTH_KEY[] = ""viewportWidth""; static const char VIEWPORT_HEIGHT_KEY[] = ""viewportHeight""; static const char HIERARCHY_KEY[] = ""hierarchy""; static const char REHIERARCHY_KEY[] = ""reHierarchy""; static const char X_KEY[] = ""x""; static const char Y_KEY[] = ""y""; static const char DOCTHEME_KEY[] = ""docTheme""; static const char BACKGROUND_KEY[] = ""background""; static const char SCREENLOCK_KEY[] = ""screenLock""; static const char COLOR_KEY[] = ""color""; static const char GRADIENT_KEY[] = ""gradient""; static const char ENSURELAYOUT_KEY[] = ""ensureLayout""; static const char AGENTNAME_KEY[] = ""agentName""; static const char AGENTVERSION_KEY[] = ""agentVersion""; static const char ALLOWOPENURL_KEY[] = ""allowOpenUrl""; static const char DISALLOWVIDEO_KEY[] = ""disallowVideo""; static const char ANIMATIONQUALITY_KEY[] = ""animationQuality""; static const char SUPPORTED_EXTENSIONS[] = ""supportedExtensions""; static const char EXTENSION_MESSAGE_KEY[] = ""extension""; /// The keys used in OS accessibility settings. static const char FONTSCALE_KEY[] = ""fontScale""; static const char SCREENMODE_KEY[] = ""screenMode""; static const char SCREENREADER_KEY[] = ""screenReader""; /// Document settings keys. static const char SUPPORTS_RESIZING_KEY[] = ""supportsResizing""; /// The keys used in APL event execution. static const char ERROR_KEY[] = ""error""; static const char EVENT_KEY[] = ""event""; static const char ARGUMENT_KEY[] = ""argument""; static const char EVENT_TERMINATE_KEY[] = ""eventTerminate""; static const char DIRTY_KEY[] = ""dirty""; /// SendEvent keys static const char PRESENTATION_TOKEN_KEY[] = ""presentationToken""; static const char SOURCE_KEY[] = ""source""; static const char ARGUMENTS_KEY[] = ""arguments""; static const char COMPONENTS_KEY[] = ""components""; /// RuntimeError keys static const char ERRORS_KEY[] = ""errors""; /// Media update keys static const char MEDIA_STATE_KEY[] = ""mediaState""; static const char FROM_EVENT_KEY[] = ""fromEvent""; static const char TRACK_INDEX_KEY[] = ""trackIndex""; static const char TRACK_COUNT_KEY[] = ""trackCount""; static const char TRACK_STATE_KEY[] = ""trackState""; static const char CURRENT_TIME_KEY[] = ""currentTime""; static const char DURATION_KEY[] = ""duration""; static const char PAUSED_KEY[] = ""paused""; static const char ENDED_KEY[] = ""ended""; /// Activity tracking sources static const std::string APL_COMMAND_EXECUTION{""APLCommandExecution""}; static const std::string APL_SCREEN_LOCK{""APLScreenLock""}; static const char RENDERING_OPTIONS_KEY[] = ""renderingOptions""; static const char LEGACY_KARAOKE_KEY[] = ""legacyKaraoke""; /// HandlePointerEvent keys static const char POINTEREVENTTYPE_KEY[] = ""pointerEventType""; static const char POINTERTYPE_KEY[] = ""pointerType""; static const char POINTERID_KEY[] = ""pointerId""; /// Data sources static const std::vector KNOWN_DATA_SOURCES = { apl::DynamicIndexListConstants::DEFAULT_TYPE_NAME, apl::DynamicTokenListConstants::DEFAULT_TYPE_NAME, }; static apl::Bimap AVS_VIEWPORT_MODE_MAP = { {""HUB"", apl::ViewportMode::kViewportModeHub}, {""TV"", apl::ViewportMode::kViewportModeTV}, {""MOBILE"", apl::ViewportMode::kViewportModeMobile}, {""AUTO"", apl::ViewportMode::kViewportModeAuto}, {""PC"", apl::ViewportMode::kViewportModePC}, }; static apl::Bimap AVS_VIEWPORT_SHAPE_MAP = { {""ROUND"", apl::ScreenShape::ROUND}, {""RECTANGLE"", apl::ScreenShape::RECTANGLE}, }; static apl::Bimap AVS_SCREEN_MODE_MAP = { {""normal"", apl::RootConfig::kScreenModeNormal}, {""high-contrast"", apl::RootConfig::kScreenModeHighContrast}, }; AplCoreConnectionManager::AplCoreConnectionManager(AplConfigurationPtr config) : m_aplConfiguration{config}, m_ScreenLock{false}, m_SequenceNumber{0}, m_replyExpectedSequenceNumber{0}, m_blockingSendReplyExpected{false} { m_StartTime = getCurrentTime(); m_extensionManager = std::make_shared(); m_messageHandlers.emplace(""build"", [this](const rapidjson::Value& payload) { handleBuild(payload); }); m_messageHandlers.emplace(""configurationChange"",[this](const rapidjson::Value& payload) { handleConfigurationChange(payload); }); m_messageHandlers.emplace(""updateDisplayState"", [this](const rapidjson::Value& payload) { handleUpdateDisplayState(payload); }); m_messageHandlers.emplace(""update"", [this](const rapidjson::Value& payload) { handleUpdate(payload); }); m_messageHandlers.emplace(""updateMedia"", [this](const rapidjson::Value& payload) { handleMediaUpdate(payload); }); m_messageHandlers.emplace(""updateGraphic"", [this](const rapidjson::Value& payload) { handleGraphicUpdate(payload); }); m_messageHandlers.emplace(""response"", [this](const rapidjson::Value& payload) { handleEventResponse(payload); }); m_messageHandlers.emplace(""ensureLayout"", [this](const rapidjson::Value& payload) { handleEnsureLayout(payload); }); m_messageHandlers.emplace(""scrollToRectInComponent"",[this](const rapidjson::Value& payload) { handleScrollToRectInComponent(payload); }); m_messageHandlers.emplace(""handleKeyboard"", [this](const rapidjson::Value& payload) { handleHandleKeyboard(payload); }); m_messageHandlers.emplace(""getFocusableAreas"", [this](const rapidjson::Value& payload) { getFocusableAreas(payload); }); m_messageHandlers.emplace(""getFocused"", [this](const rapidjson::Value& payload) { getFocused(payload); }); m_messageHandlers.emplace(""setFocus"", [this](const rapidjson::Value& payload) { setFocus(payload); }); m_messageHandlers.emplace(""updateCursorPosition"", [this](const rapidjson::Value& payload) { handleUpdateCursorPosition(payload); }); m_messageHandlers.emplace(""handlePointerEvent"", [this](const rapidjson::Value& payload) { handleHandlePointerEvent(payload); }); m_messageHandlers.emplace(""isCharacterValid"", [this](const rapidjson::Value& payload) { handleIsCharacterValid(payload); }); m_messageHandlers.emplace(""reInflate"", [this](const rapidjson::Value& payload) { handleReInflate(payload); }); m_messageHandlers.emplace(""reHierarchy"", [this](const rapidjson::Value& payload) { handleReHierarchy(payload); }); m_messageHandlers.emplace(""extension"", [this](const rapidjson::Value& payload) { handleExtensionMessage(payload); }); m_messageHandlers.emplace(""mediaLoaded"", [this](const rapidjson::Value& payload) { mediaLoaded(payload); }); m_messageHandlers.emplace(""mediaLoadFailed"", [this](const rapidjson::Value& payload) { mediaLoadFailed(payload); }); } void AplCoreConnectionManager::setContent(const apl::ContentPtr content, const std::string& token) { m_Content = content; m_aplToken = token; m_ConfigurationChange.clear(); m_aplConfiguration->getAplOptions()->resetViewhost(token); } void AplCoreConnectionManager::setSupportedViewports(const std::string& jsonPayload) { rapidjson::Document doc; auto aplOptions = m_aplConfiguration->getAplOptions(); if (doc.Parse(jsonPayload.c_str()).HasParseError()) { aplOptions->logMessage(LogLevel::ERROR, ""setSupportedViewportsFailed"", ""Failed to parse json payload""); return; } if (doc.GetType() != rapidjson::Type::kArrayType) { aplOptions->logMessage(LogLevel::ERROR, ""setSupportedViewportsFailed"", ""Unexpected json document type""); return; } m_ViewportSizeSpecifications.clear(); for (auto& spec : doc.GetArray()) { double minWidth = getOptionalValue(spec, ""minWidth"", 1); double maxWidth = getOptionalValue(spec, ""maxWidth"", INT_MAX); double minHeight = getOptionalValue(spec, ""minHeight"", 1); double maxHeight = getOptionalValue(spec, ""maxHeight"", INT_MAX); std::string mode = getOptionalValue(spec, ""mode"", ""HUB""); std::string shape = spec.FindMember(""shape"")->value.GetString(); m_ViewportSizeSpecifications.emplace_back( minWidth, maxWidth, minHeight, maxHeight, AVS_VIEWPORT_MODE_MAP.at(mode), AVS_VIEWPORT_SHAPE_MAP.at(shape) == apl::ScreenShape::ROUND); } } double AplCoreConnectionManager::getOptionalValue( const rapidjson::Value& jsonNode, const std::string& key, double defaultValue) { double value = defaultValue; const auto& valueIt = jsonNode.FindMember(key); if (valueIt != jsonNode.MemberEnd()) { value = valueIt->value.GetDouble(); } return value; } std::string AplCoreConnectionManager::getOptionalValue( const rapidjson::Value& jsonNode, const std::string& key, const std::string& defaultValue) { std::string value = defaultValue; const auto& valueIt = jsonNode.FindMember(key); if (valueIt != jsonNode.MemberEnd()) { value = valueIt->value.GetString(); } return value; } bool AplCoreConnectionManager::getOptionalBool( const rapidjson::Value& jsonNode, const std::string& key, bool defaultValue) { bool value = defaultValue; const auto& valueIt = jsonNode.FindMember(key); if (valueIt != jsonNode.MemberEnd()) { value = valueIt->value.GetBool(); } return value; } int AplCoreConnectionManager::getOptionalInt( const rapidjson::Value& jsonNode, const std::string& key, int defaultValue) { if (jsonNode.HasMember(key) && jsonNode[key].IsInt()) { return jsonNode[key].GetInt(); } return defaultValue; } bool AplCoreConnectionManager::shouldHandleMessage(const std::string& message) { if (m_blockingSendReplyExpected) { rapidjson::Document doc; if (doc.Parse(message.c_str()).HasParseError()) { auto aplOptions = m_aplConfiguration->getAplOptions(); aplOptions->logMessage(LogLevel::ERROR, ""shouldHandleMessageFailed"", ""Error whilst parsing message""); return false; } if (doc.HasMember(SEQNO_KEY) && doc[SEQNO_KEY].IsNumber()) { unsigned int seqno = doc[SEQNO_KEY].GetUint(); if (seqno == m_replyExpectedSequenceNumber) { m_blockingSendReplyExpected = false; m_replyPromise.set_value(message); return false; } } } return true; } void AplCoreConnectionManager::handleMessage(const std::string& message) { auto aplOptions = m_aplConfiguration->getAplOptions(); rapidjson::Document doc; if (doc.Parse(message.c_str()).HasParseError()) { aplOptions->logMessage(LogLevel::ERROR, ""handleMessageFailed"", ""Error whilst parsing message""); return; } if (!doc.HasMember(""type"")) { aplOptions->logMessage(LogLevel::ERROR, ""handleMessageFailed"", ""Unable to find type in message""); return; } std::string type = doc[""type""].GetString(); auto payload = doc.FindMember(""payload""); if (payload == doc.MemberEnd()) { aplOptions->logMessage(LogLevel::ERROR, ""handleMessageFailed"", ""Unable to find payload in message""); return; } auto fit = m_messageHandlers.find(type); if (fit != m_messageHandlers.end()) { fit->second(payload->value); } else { aplOptions->logMessage(LogLevel::ERROR, ""handleMessageFailed"", ""Unrecognized message type: "" + type); } } void AplCoreConnectionManager::handleConfigurationChange(const rapidjson::Value& configurationChange) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root || !m_AplCoreMetrics) { aplOptions->logMessage(LogLevel::ERROR, ""handleConfigurationChangeFailed"", ""Root context is missing""); return; } apl::ConfigurationChange configChange = apl::ConfigurationChange(); // config change for width and height if (configurationChange.HasMember(WIDTH_KEY) && configurationChange[WIDTH_KEY].IsInt() && configurationChange.HasMember(HEIGHT_KEY) && configurationChange[HEIGHT_KEY].IsInt()) { m_Metrics.size((int) configurationChange[WIDTH_KEY].GetInt(), (int) configurationChange[HEIGHT_KEY].GetInt()); m_AplCoreMetrics.reset(); apl::ScalingOptions scalingOptions = { m_ViewportSizeSpecifications, SCALING_BIAS_CONSTANT, SCALING_SHAPE_OVERRIDES_COST}; if (!scalingOptions.getSpecifications().empty()) { m_AplCoreMetrics = std::make_shared(m_Metrics, scalingOptions); } else { m_AplCoreMetrics = std::make_shared(m_Metrics); } const int pixelWidth = (int) m_AplCoreMetrics->toCorePixel(m_AplCoreMetrics->getViewhostWidth()); const int pixelHeight = (int) m_AplCoreMetrics->toCorePixel(m_AplCoreMetrics->getViewhostHeight()); configChange = configChange.size(pixelWidth, pixelHeight); sendViewhostScalingMessage(); } // config change for theme if (configurationChange.HasMember(DOCTHEME_KEY) && configurationChange[DOCTHEME_KEY].IsString()) { configChange = configChange.theme(configurationChange[DOCTHEME_KEY].GetString()); sendDocumentThemeMessage(); } // config change for mode if (configurationChange.HasMember(MODE_KEY) && configurationChange[MODE_KEY].IsString() && AVS_VIEWPORT_MODE_MAP.find(configurationChange[MODE_KEY].GetString()) != AVS_VIEWPORT_MODE_MAP.end()) { configChange = configChange.mode(AVS_VIEWPORT_MODE_MAP.at(configurationChange[MODE_KEY].GetString())); } // config change for fontScale if (configurationChange.HasMember(FONTSCALE_KEY) && configurationChange[FONTSCALE_KEY].IsFloat()) { configChange = configChange.fontScale(configurationChange[FONTSCALE_KEY].GetFloat()); } // config change for screenMode if (configurationChange.HasMember(SCREENMODE_KEY) && configurationChange[SCREENMODE_KEY].IsString() && AVS_SCREEN_MODE_MAP.find(configurationChange[SCREENMODE_KEY].GetString()) != AVS_SCREEN_MODE_MAP.end()) { configChange = configChange.screenMode(AVS_SCREEN_MODE_MAP.at(configurationChange[SCREENMODE_KEY].GetString())); } // config change for screenReader if (configurationChange.HasMember(SCREENREADER_KEY) && configurationChange[SCREENREADER_KEY].IsBool()) { configChange = configChange.screenReader(configurationChange[SCREENREADER_KEY].GetBool()); } updateConfigurationChange(configChange); m_Root->configurationChange(configChange); } void AplCoreConnectionManager::handleUpdateDisplayState(const rapidjson::Value& displayState) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleUpdateDisplayStateFailed"", ""Root context is missing""); return; } /// Display State Mapping std::map displayStateMapping = { {0, apl::DisplayState::kDisplayStateHidden}, {1, apl::DisplayState::kDisplayStateBackground}, {2, apl::DisplayState::kDisplayStateForeground} }; int state = displayState.GetInt(); if (displayStateMapping.find(state) == displayStateMapping.end()) { aplOptions->logMessage(LogLevel::ERROR, ""handleUpdateDisplayStateFailed"", ""Valid state not found""); return; } else { m_Root->updateDisplayState(displayStateMapping[state]); } } void AplCoreConnectionManager::executeCommands(const std::string& command, const std::string& token) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""executeCommandsFailed"", ""Root context is missing""); return; } std::shared_ptr document(new rapidjson::Document); if (document->Parse(command).HasParseError()) { aplOptions->logMessage(LogLevel::ERROR, ""executeCommandsFailed"", ""Parse commands failed""); return; } auto it = document->FindMember(""commands""); if (it == document->MemberEnd() || it->value.GetType() != rapidjson::Type::kArrayType) { aplOptions->logMessage(LogLevel::ERROR, ""executeCommandsFailed"", ""Missing commands, or is not array""); return; } apl::Object object{it->value}; auto action = m_Root->executeCommands(object, false); if (!action) { aplOptions->logMessage(LogLevel::ERROR, ""executeCommandsFailed"", ""Execute commands failed""); return; } aplOptions->onActivityStarted(token, APL_COMMAND_EXECUTION); action->then([this, document, token](const apl::ActionPtr& action) { auto aplOptions = m_aplConfiguration->getAplOptions(); aplOptions->logMessage(LogLevel::DBG, ""executeCommands"", ""Command sequence complete""); aplOptions->onCommandExecutionComplete(token, true); aplOptions->onActivityEnded(token, APL_COMMAND_EXECUTION); }); action->addTerminateCallback([this, document, token](const apl::TimersPtr&) { auto aplOptions = m_aplConfiguration->getAplOptions(); aplOptions->logMessage(LogLevel::DBG, ""executeCommandsFailed"", ""Command sequence failed""); aplOptions->onCommandExecutionComplete(token, false); aplOptions->onActivityEnded(token, APL_COMMAND_EXECUTION); }); } void AplCoreConnectionManager::onExtensionEvent( const std::string& uri, const std::string& name, const std::string& source, const std::string& params, unsigned int event, std::shared_ptr resultCallback) { rapidjson::Document sourceDoc; rapidjson::Document paramsDoc; auto aplOptions = m_aplConfiguration->getAplOptions(); if (sourceDoc.Parse(source).HasParseError()) { aplOptions->logMessage(LogLevel::ERROR, ""onExtensionEventFailed"", ""Parse source failed""); return; } if (paramsDoc.Parse(params).HasParseError()) { aplOptions->logMessage(LogLevel::ERROR, ""onExtensionEventFailed"", ""Parse params failed""); return; } m_extensionManager->onExtensionEvent( uri, name, apl::Object(sourceDoc), apl::Object(paramsDoc), event, resultCallback); } void AplCoreConnectionManager::onExtensionEventResult(unsigned int event, bool succeeded) { rapidjson::Document response(rapidjson::kObjectType); rapidjson::Document::AllocatorType& allocator = response.GetAllocator(); rapidjson::Value payload(rapidjson::kObjectType); payload.AddMember(EVENT_KEY, event, allocator); payload.AddMember(ARGUMENT_KEY, succeeded ? 0 : 1, allocator); handleEventResponse(payload); } AplDocumentStatePtr AplCoreConnectionManager::getActiveDocumentState() { // If we have active content, report it as an AplDocumentState if (m_Content && m_Root && m_AplCoreMetrics) { auto documentState = std::make_shared(m_aplToken, m_Root, m_AplCoreMetrics); return documentState; } return nullptr; } void AplCoreConnectionManager::restoreDocumentState(AplDocumentStatePtr documentState) { m_documentStateToRestore = std::move(documentState); m_documentStateToRestore->configurationChange = m_ConfigurationChange; reset(); m_aplConfiguration->getAplOptions()->resetViewhost(m_documentStateToRestore->token); } void AplCoreConnectionManager::invokeExtensionEventHandler( const std::string& uri, const std::string& name, const apl::ObjectMap& data, bool fastMode) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""invokeExtensionEventHandlerFailed"", ""Root context is missing""); return; } aplOptions->logMessage(LogLevel::DBG, ""invokeExtensionEventHandler"", +""< "" + uri + "":"" + name + "" >""); auto actnPtr = m_Root->invokeExtensionEventHandler(uri, name, data, fastMode); if (actnPtr == nullptr) { aplOptions->logMessage(LogLevel::ERROR, ""invokeExtensionEventHandlerFailed"", ""No handler found""); } } void AplCoreConnectionManager::sendExtensionEvent( const std::string &uri, const std::string &name, const apl::Object &source, const apl::Object ¶ms, unsigned int event, std::shared_ptr resultCallback) { auto message = AplCoreViewhostMessage(EXTENSION_MESSAGE_KEY); auto &mAlloc = message.alloc(); rapidjson::Value payload(rapidjson::kObjectType); payload.AddMember(""URI"", uri, mAlloc); payload.AddMember(""type"", ""event"", mAlloc); payload.AddMember(""name"", name, mAlloc); rapidjson::Value jsonParams = params.serialize(mAlloc); payload.AddMember(""params"", jsonParams, mAlloc); message.setPayload(std::move(payload)); send(message); } void AplCoreConnectionManager::dataSourceUpdate( const std::string& sourceType, const std::string& jsonPayload, const std::string& token) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""dataSourceUpdateFailed"", ""Root context is missing""); return; } auto provider = m_Root->getRootConfig().getDataSourceProvider(sourceType); if (!provider) { aplOptions->logMessage(LogLevel::ERROR, ""dataSourceUpdateFailed"", ""Unknown provider requested.""); return; } bool result = provider->processUpdate(jsonPayload); if (!result) { aplOptions->logMessage(LogLevel::ERROR, ""dataSourceUpdateFailed"", ""Update is not processed.""); checkAndSendDataSourceErrors(); } } void AplCoreConnectionManager::provideState(unsigned int stateRequestToken) { auto aplOptions = m_aplConfiguration->getAplOptions(); auto timer = m_aplConfiguration->getMetricsRecorder()->createTimer( Telemetry::AplMetricsRecorderInterface::CURRENT_DOCUMENT, ""APL-Web.RootContext.notifyVisualContext""); timer->start(); rapidjson::Document state(rapidjson::kObjectType); rapidjson::Document::AllocatorType& allocator = state.GetAllocator(); rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); // Add presentation token info state.AddMember(TOKEN_KEY, m_aplToken, allocator); // Add version info state.AddMember(VERSION_KEY, CLIENT_VERSION_PREFIX + apl::APLVersion::getDefaultReportedVersionString(), allocator); // Add visual context info state.AddMember(VISUAL_CONTEXT_KEY, getVisualContext(allocator), allocator); // Add datasource context info state.AddMember(DATASOURCE_CONTEXT_KEY, getDatasourceContext(allocator), allocator); state.Accept(writer); aplOptions->onVisualContextAvailable(m_aplToken, stateRequestToken, buffer.GetString()); timer->stop(); } rapidjson::Value AplCoreConnectionManager::getVisualContext(rapidjson::Document::AllocatorType& allocator) { auto aplOptions = m_aplConfiguration->getAplOptions(); auto timer = m_aplConfiguration->getMetricsRecorder()->createTimer( Telemetry::AplMetricsRecorderInterface::CURRENT_DOCUMENT, ""APL-Web.RootContext.serializeVisualContext""); timer->start(); rapidjson::Value arr(rapidjson::kArrayType); if (m_Root) { auto context = m_Root->serializeVisualContext(allocator); arr.PushBack(context, allocator); } else { aplOptions->logMessage(LogLevel::ERROR, ""getVisualContextFailed"", ""Unable to get visual context""); rapidjson::Value emptyObj(rapidjson::kObjectType); // add an empty visual context arr.PushBack(emptyObj, allocator); } timer->stop(); return arr; } rapidjson::Value AplCoreConnectionManager::getDatasourceContext(rapidjson::Document::AllocatorType& allocator) { auto aplOptions = m_aplConfiguration->getAplOptions(); auto timer = m_aplConfiguration->getMetricsRecorder()->createTimer( Telemetry::AplMetricsRecorderInterface::CURRENT_DOCUMENT, ""APL-Web.RootContext.serializeDataSourceContext""); timer->start(); rapidjson::Value context; if (m_Root) { context = m_Root->serializeDataSourceContext(allocator); } else { aplOptions->logMessage(LogLevel::ERROR, ""getDatasourceContextFailed"", ""Unable to get datasource context""); rapidjson::Value emptyDataSource(rapidjson::kArrayType); // return empty datasource context context = emptyDataSource; } timer->stop(); return context; } void AplCoreConnectionManager::interruptCommandSequence() { if (m_Root) { m_Root->cancelExecution(); } } void AplCoreConnectionManager::handleBuild(const rapidjson::Value& message) { auto aplOptions = m_aplConfiguration->getAplOptions(); auto inflationTimer = m_aplConfiguration->getMetricsRecorder()->createTimer( Telemetry::AplMetricsRecorderInterface::LATEST_DOCUMENT, Telemetry::AplRenderingSegment::kRootContextInflation); inflationTimer->start(); /* APL Document Inflation started */ aplOptions->onRenderingEvent(m_aplToken, AplRenderingEvent::INFLATE_BEGIN); apl::RootConfig config; if (m_documentStateToRestore) { // Restore from document state m_aplToken = m_documentStateToRestore->token; m_Root = m_documentStateToRestore->rootContext; m_Content = m_Root->content(); config = m_documentStateToRestore->rootContext->getRootConfig(); m_Root->configurationChange(m_documentStateToRestore->configurationChange); coreFrameUpdate(); } if (!m_Content) { aplOptions->logMessage(LogLevel::WARN, ""handleBuildFailed"", ""No content to build""); sendError(""No content to build""); inflationTimer->fail(); return; } // Get APL Version for content std::string aplVersion = m_Content->getAPLVersion(); // If we're not restoring a document state, create a new RootConfig. if (!m_documentStateToRestore) { std::string agentName = getOptionalValue(message, AGENTNAME_KEY, ""wssHost""); std::string agentVersion = getOptionalValue(message, AGENTVERSION_KEY, ""1.0""); bool allowOpenUrl = getOptionalBool(message, ALLOWOPENURL_KEY, false); bool disallowVideo = getOptionalBool(message, DISALLOWVIDEO_KEY, false); int animationQuality = getOptionalInt(message, ANIMATIONQUALITY_KEY, apl::RootConfig::AnimationQuality::kAnimationQualityNormal); config = apl::RootConfig() .agent(agentName, agentVersion) .allowOpenUrl(allowOpenUrl) .disallowVideo(disallowVideo) .animationQuality(static_cast(animationQuality)) .measure(std::make_shared(shared_from_this(), m_aplConfiguration)) .localeMethods(std::make_shared(shared_from_this(), m_aplConfiguration)) .utcTime(getCurrentTime().count()) .localTimeAdjustment(aplOptions->getTimezoneOffset().count()) .enforceAPLVersion(apl::APLVersion::kAPLVersionIgnore) .sequenceChildCache(5) .enableExperimentalFeature(apl::RootConfig::ExperimentalFeature::kExperimentalFeatureManageMediaRequests) .set(apl::RootProperty::kDefaultIdleTimeout, -1); // Data Sources config.dataSourceProvider( apl::DynamicIndexListConstants::DEFAULT_TYPE_NAME, std::make_shared()); config.dataSourceProvider( apl::DynamicTokenListConstants::DEFAULT_TYPE_NAME, std::make_shared()); } // Add Extensions which are supported, requested, and available to the config if (message.HasMember(SUPPORTED_EXTENSIONS) && message[SUPPORTED_EXTENSIONS].IsArray()) { // Extensions supported by the client renderer instance auto supportedExtensions = message[SUPPORTED_EXTENSIONS].GetArray(); // Extensions requested by the content auto requestedExtensions = m_Content->getExtensionRequests(); for (auto& ext : supportedExtensions) { auto uri = ext.GetString(); // If the supported extension is both requested and available, register it with the config if (requestedExtensions.find(uri) != requestedExtensions.end()) { if (auto extension = m_extensionManager->getExtension(uri)) { // Apply content defined settings to extension extension->applySettings(m_Content->getExtensionSettings(uri)); m_extensionManager->registerRequestedExtension(extension->getUri(), config); } } } } auto renderingOptionsMsg = AplCoreViewhostMessage(RENDERING_OPTIONS_KEY); rapidjson::Value renderingOptions(rapidjson::kObjectType); renderingOptions.AddMember(LEGACY_KARAOKE_KEY, aplVersion == ""1.0"", renderingOptionsMsg.alloc()); send(renderingOptionsMsg.setPayload(std::move(renderingOptions))); m_PendingEvents.clear(); // Release the activity tracker aplOptions->onActivityEnded(m_aplToken, APL_COMMAND_EXECUTION); if (m_ScreenLock) { aplOptions->onActivityEnded(m_aplToken, APL_SCREEN_LOCK); m_ScreenLock = false; } m_StartTime = getCurrentTime(); // If we're not restoring a document state, then create metrics and RootContext if (!m_documentStateToRestore) { // Handle metrics data m_Metrics.size(message[WIDTH_KEY].GetInt(), message[HEIGHT_KEY].GetInt()) .dpi(message[DPI_KEY].GetInt()) .shape(AVS_VIEWPORT_SHAPE_MAP.at(message[SHAPE_KEY].GetString())) .mode(AVS_VIEWPORT_MODE_MAP.at(message[MODE_KEY].GetString())); do { apl::ScalingOptions scalingOptions = { m_ViewportSizeSpecifications, SCALING_BIAS_CONSTANT, SCALING_SHAPE_OVERRIDES_COST}; if (!scalingOptions.getSpecifications().empty()) { m_AplCoreMetrics = std::make_shared(m_Metrics, scalingOptions); } else { m_AplCoreMetrics = std::make_shared(m_Metrics); } sendViewhostScalingMessage(); m_StartTime = getCurrentTime(); m_Root = apl::RootContext::create(m_AplCoreMetrics->getMetrics(), m_Content, config); if (m_Root) { break; } else if (!m_ViewportSizeSpecifications.empty()) { aplOptions->logMessage( LogLevel::WARN, __func__, ""Unable to inflate document with current chosen scaling.""); } auto it = m_ViewportSizeSpecifications.begin(); for (; it != m_ViewportSizeSpecifications.end(); it++) { if (*it == m_AplCoreMetrics->getChosenSpec()) { m_ViewportSizeSpecifications.erase(it); break; } } if (it == m_ViewportSizeSpecifications.end()) { // Core returned specification that is not in list. Something went wrong. Prevent infinite loop. break; } } while (!m_ViewportSizeSpecifications.empty()); } // Make sure we only restore a documentState once. if (m_documentStateToRestore) { m_documentStateToRestore.reset(); } // Get background apl::Object background = m_Content->getBackground(m_AplCoreMetrics->getMetrics(), config); bool supportsResizing = false; // Get Document Settings if (auto documentSettings = m_Content->getDocumentSettings()) { // Get resizing setting supportsResizing = documentSettings->getValue(SUPPORTS_RESIZING_KEY).asBoolean(); } sendSupportsResizingMessage(supportsResizing); /* APL Core Inflation ended */ aplOptions->onRenderingEvent(m_aplToken, AplRenderingEvent::INFLATE_END); if (m_Root) { inflationTimer->stop(); // Init viewhost globals sendViewhostScalingMessage(); sendDocumentThemeMessage(); sendDocumentBackgroundMessage(background); // Start rendering component hierarchy // and displaying Children sendHierarchy(HIERARCHY_KEY); auto idleTimeout = std::chrono::milliseconds(m_Root->settings().idleTimeout(config)); aplOptions->onSetDocumentIdleTimeout(m_aplToken, idleTimeout); aplOptions->onRenderDocumentComplete(m_aplToken, true, """"); } else { inflationTimer->fail(); aplOptions->logMessage(LogLevel::ERROR, ""handleBuildFailed"", ""Unable to inflate document""); sendError(""Unable to inflate document""); aplOptions->onRenderDocumentComplete(m_aplToken, false, ""Unable to inflate document""); // Send DataSource errors if any checkAndSendDataSourceErrors(); } } void AplCoreConnectionManager::onDocumentRendered( const std::chrono::steady_clock::time_point &renderTime, uint64_t complexityScore) { auto metricsRecorder = m_aplConfiguration->getMetricsRecorder(); metricsRecorder->flush(); } void AplCoreConnectionManager::sendViewhostScalingMessage() { if (m_AplCoreMetrics) { // Send scaling metrics out to viewhost auto reply = AplCoreViewhostMessage(SCALING_KEY); rapidjson::Value scaling(rapidjson::kObjectType); scaling.AddMember(SCALE_FACTOR_KEY, m_AplCoreMetrics->toViewhost(1.0f), reply.alloc()); scaling.AddMember(VIEWPORT_WIDTH_KEY, m_AplCoreMetrics->getViewhostWidth(), reply.alloc()); scaling.AddMember(VIEWPORT_HEIGHT_KEY, m_AplCoreMetrics->getViewhostHeight(), reply.alloc()); send(reply.setPayload(std::move(scaling))); } } void AplCoreConnectionManager::sendDocumentThemeMessage() { if (m_Root) { auto themeMsg = AplCoreViewhostMessage(DOCTHEME_KEY); auto& alloc = themeMsg.alloc(); rapidjson::Value payload(rapidjson::kObjectType); std::string docTheme = ""dark""; docTheme = m_Root->getTheme(); payload.AddMember(DOCTHEME_KEY, rapidjson::Value(docTheme.c_str(), alloc).Move(), alloc); themeMsg.setPayload(std::move(payload)); send(themeMsg); } } void AplCoreConnectionManager::sendDocumentBackgroundMessage(const apl::Object& background) { auto backgroundMsg = AplCoreViewhostMessage(BACKGROUND_KEY); auto& alloc = backgroundMsg.alloc(); rapidjson::Value payload(rapidjson::kObjectType); rapidjson::Value backgroundValue(rapidjson::kObjectType); if (background.isColor()) { backgroundValue.AddMember(COLOR_KEY, background.asString(), alloc); } else if (background.isGradient()) { backgroundValue.AddMember(GRADIENT_KEY, background.getGradient().serialize(alloc), alloc); } else { backgroundValue.AddMember(COLOR_KEY, apl::Color().asString(), alloc); } payload.AddMember(BACKGROUND_KEY, backgroundValue, alloc); backgroundMsg.setPayload(std::move(payload)); send(backgroundMsg); } void AplCoreConnectionManager::sendScreenLockMessage(bool screenLock) { auto screenLockMsg = AplCoreViewhostMessage(SCREENLOCK_KEY); auto& alloc = screenLockMsg.alloc(); rapidjson::Value payload(rapidjson::kObjectType); payload.AddMember(SCREENLOCK_KEY, screenLock, alloc); screenLockMsg.setPayload(std::move(payload)); send(screenLockMsg); } void AplCoreConnectionManager::sendSupportsResizingMessage(bool supportsResizing) { auto supportsResizingMsg = AplCoreViewhostMessage(SUPPORTS_RESIZING_KEY); auto& alloc = supportsResizingMsg.alloc(); rapidjson::Value payload(rapidjson::kObjectType); payload.AddMember(SUPPORTS_RESIZING_KEY, supportsResizing, alloc); supportsResizingMsg.setPayload(std::move(payload)); send(supportsResizingMsg); } void AplCoreConnectionManager::handleUpdate(const rapidjson::Value& update) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleUpdateFailed"", ""Root context is null""); return; } auto id = update[""id""].GetString(); auto component = m_Root->findComponentById(id); if (!component) { aplOptions->logMessage( LogLevel::ERROR, ""handleUpdateFailed"", std::string(""Unable to find component with id: "") + id); sendError(""Unable to find component""); return; } auto type = static_cast(update[""type""].GetInt()); if (update[""value""].IsString()) { std::string value = update[""value""].GetString(); component->update(type, value); } else { auto value = update[""value""].GetFloat(); if (type == apl::UpdateType::kUpdateScrollPosition) { value = m_AplCoreMetrics->toCore(value); } component->update(type, value); } } void AplCoreConnectionManager::handleMediaUpdate(const rapidjson::Value& update) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleMediaUpdateFailed"", ""Root context is null""); return; } auto id = update[""id""].GetString(); auto component = m_Root->findComponentById(id); if (!component) { aplOptions->logMessage( LogLevel::ERROR, ""handleMediaUpdateFailed"", std::string(""Unable to find component with id: "") + id); sendError(""Unable to find component""); return; } if (!update.HasMember(MEDIA_STATE_KEY) || !update.HasMember(FROM_EVENT_KEY)) { aplOptions->logMessage( LogLevel::ERROR, ""handleMediaUpdateFailed"", ""State update object is missing parameters""); sendError(""Can't update media state.""); return; } auto& state = update[MEDIA_STATE_KEY]; auto fromEvent = update[FROM_EVENT_KEY].GetBool(); if (!state.HasMember(TRACK_INDEX_KEY) || !state.HasMember(TRACK_COUNT_KEY) || !state.HasMember(CURRENT_TIME_KEY) || !state.HasMember(DURATION_KEY) || !state.HasMember(PAUSED_KEY) || !state.HasMember(ENDED_KEY) || !state.HasMember(TRACK_STATE_KEY)) { aplOptions->logMessage( LogLevel::ERROR, ""handleMediaUpdateFailed"", ""Can't update media state. MediaStatus structure is wrong""); sendError(""Can't update media state.""); return; } // numeric parameters are sometimes converted to null during stringification, set these to 0 const int trackIndex = getOptionalInt(state, TRACK_INDEX_KEY, 0); const int trackCount = getOptionalInt(state, TRACK_COUNT_KEY, 0); const int currentTime = getOptionalInt(state, CURRENT_TIME_KEY, 0); const int duration = getOptionalInt(state, DURATION_KEY, 0); const auto trackState = static_cast(state[TRACK_STATE_KEY].GetInt()); apl::MediaState mediaState( trackIndex, trackCount, currentTime, duration, state[PAUSED_KEY].GetBool(), state[ENDED_KEY].GetBool()); mediaState.withTrackState(trackState); component->updateMediaState(mediaState, fromEvent); } void AplCoreConnectionManager::handleGraphicUpdate(const rapidjson::Value& update) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleGraphicUpdateFailed"", ""Root context is null""); return; } auto id = update[""id""].GetString(); auto component = m_Root->findComponentById(id); if (!component) { aplOptions->logMessage( LogLevel::ERROR, ""handleGraphicUpdateFailed"", std::string(""Unable to find component with id:"") + id); sendError(""Unable to find component""); return; } auto json = apl::GraphicContent::create(update[""avg""].GetString()); component->updateGraphic(json); } void AplCoreConnectionManager::handleEnsureLayout(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleEnsureLayoutFailed"", ""Root context is null""); return; } auto id = payload[""id""].GetString(); auto component = m_Root->findComponentById(id); if (!component) { aplOptions->logMessage( LogLevel::ERROR, ""handleEnsureLayoutFailed"", std::string(""Unable to find component with id:"") + id); sendError(""Unable to find component""); return; } component->ensureLayout(true); auto msg = AplCoreViewhostMessage(ENSURELAYOUT_KEY); send(msg.setPayload(id)); } void AplCoreConnectionManager::handleScrollToRectInComponent(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleScrollToRectInComponentFailed"", ""Root context is null""); return; } auto id = payload[""id""].GetString(); auto component = m_Root->findComponentById(id); if (!component) { aplOptions->logMessage( LogLevel::ERROR, ""handleScrollToRectInComponentFailed"", std::string(""Unable to find component with id:"") + id); sendError(""Unable to find component""); return; } apl::Rect rect = convertJsonToScaledRect(payload); m_Root->scrollToRectInComponent(component, rect, static_cast(payload[""align""].GetInt())); } void AplCoreConnectionManager::handleHandleKeyboard(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleHandleKeyboardFailed"", ""Root context is null""); return; } auto messageId = payload[""messageId""].GetString(); auto keyType = payload[""keyType""].GetInt(); auto code = payload[""code""].GetString(); auto key = payload[""key""].GetString(); auto repeat = payload[""repeat""].GetBool(); auto altKey = payload[""altKey""].GetBool(); auto ctrlKey = payload[""ctrlKey""].GetBool(); auto metaKey = payload[""metaKey""].GetBool(); auto shiftKey = payload[""shiftKey""].GetBool(); apl::Keyboard keyboard(code, key); keyboard.repeat(repeat); keyboard.alt(altKey); keyboard.ctrl(ctrlKey); keyboard.meta(metaKey); keyboard.shift(shiftKey); bool result = m_Root->handleKeyboard(static_cast(keyType), keyboard); auto handleKeyboardResultMessage = AplCoreViewhostMessage(""handleKeyboard""); auto& alloc = handleKeyboardResultMessage.alloc(); rapidjson::Value handleKeyboardResultValue(rapidjson::kObjectType); rapidjson::Value value; value.SetString(messageId, alloc); handleKeyboardResultValue.AddMember(""messageId"", value, alloc); handleKeyboardResultValue.AddMember(""result"", result, alloc); handleKeyboardResultMessage.setPayload(std::move(handleKeyboardResultValue)); send(handleKeyboardResultMessage); } void AplCoreConnectionManager::getFocusableAreas(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""getFocusableAreasFailed"", ""Root context is null""); return; } auto messageId = payload[""messageId""].GetString(); auto message = AplCoreViewhostMessage(""getFocusableAreas""); auto result = m_Root->getFocusableAreas(); auto& alloc = message.alloc(); rapidjson::Value outPayload(rapidjson::kObjectType); rapidjson::Value value; value.SetString(messageId, alloc); outPayload.AddMember(""messageId"", value, alloc); rapidjson::Value areas(rapidjson::kObjectType); for (auto iterator = result.begin(); iterator != result.end(); iterator++) { auto top = iterator->second.getTop(); auto left = iterator->second.getLeft(); auto width = iterator->second.getWidth(); auto height = iterator->second.getHeight(); rapidjson::Value rectangle(rapidjson::kObjectType); rectangle.AddMember(""top"", top, alloc); rectangle.AddMember(""left"", left, alloc); rectangle.AddMember(""width"", width, alloc); rectangle.AddMember(""height"", height, alloc); rapidjson::Value key(rapidjson::kStringType); key.SetString(iterator->first.c_str(), alloc); areas.AddMember(key, rectangle, alloc); } outPayload.AddMember(""areas"", areas, alloc); message.setPayload(std::move(outPayload)); send(message); } void AplCoreConnectionManager::getFocused(const rapidjson::Value& payload) { auto messageId = payload[""messageId""].GetString(); auto message = AplCoreViewhostMessage(""getFocused""); auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""getFocusedFailed"", ""Root context is null""); return; } auto result = m_Root->getFocused(); auto& alloc = message.alloc(); rapidjson::Value outPayload(rapidjson::kObjectType); rapidjson::Value value; value.SetString(messageId, alloc); outPayload.AddMember(""messageId"", value, alloc); outPayload.AddMember(""result"", result, alloc); message.setPayload(std::move(outPayload)); send(message); } void AplCoreConnectionManager::setFocus(const rapidjson::Value& payload) { auto direction = payload[""direction""].GetInt(); auto top = payload[""origin""].FindMember(""top"")->value.Get(); auto left = payload[""origin""].FindMember(""left"")->value.Get(); auto width = payload[""origin""].FindMember(""width"")->value.Get(); auto height = payload[""origin""].FindMember(""height"")->value.Get(); auto origin = apl::Rect(top, left, width, height); auto targetId = payload[""targetId""].GetString(); m_Root->setFocus(static_cast(direction), origin, targetId); } void AplCoreConnectionManager::mediaLoaded(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""AplCoreConnectionManager:mediaLoaded"", ""Root context is null""); return; } auto source = payload[""source""].GetString(); m_Root->mediaLoaded(source); } void AplCoreConnectionManager::mediaLoadFailed(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""AplCoreConnectionManager::mediaLoadFailed"", ""Root context is null""); return; } auto source = payload[""source""].GetString(); auto errorCode = payload[""errorCode""].GetInt(); auto error = payload[""error""].GetString(); m_Root->mediaLoadFailed(source, errorCode, error); } void AplCoreConnectionManager::handleUpdateCursorPosition(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleUpdateCursorPositionFailed"", ""Root context is null""); return; } const float x = payload[X_KEY].GetFloat(); const float y = payload[Y_KEY].GetFloat(); apl::Point cursorPosition(m_AplCoreMetrics->toCore(x), m_AplCoreMetrics->toCore(y)); m_Root->updateCursorPosition(cursorPosition); } void AplCoreConnectionManager::handleHandlePointerEvent(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleHandlePointerEventFailed"", ""Root context is null""); return; } const float x = payload[X_KEY].GetFloat(); const float y = payload[Y_KEY].GetFloat(); apl::Point point = apl::Point(m_AplCoreMetrics->toCore(x), m_AplCoreMetrics->toCore(y)); apl::PointerEventType pointerEventType = static_cast(payload[POINTEREVENTTYPE_KEY].GetInt()); apl::PointerType pointerType = static_cast(payload[POINTERTYPE_KEY].GetInt()); auto pointerId = static_cast(payload[POINTERID_KEY].GetInt()); apl::PointerEvent pointerEvent = apl::PointerEvent(pointerEventType, point, pointerId, pointerType); m_Root->handlePointerEvent(pointerEvent); } void AplCoreConnectionManager::handleEventResponse(const rapidjson::Value& response) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleEventResponseFailed"", ""Root context is null""); return; } if (!response[EVENT_KEY].IsInt()) { aplOptions->logMessage(LogLevel::ERROR, ""handleEventResponseFailed"", ""Invalid event response""); sendError(""Invalid event response""); return; } auto event = response[EVENT_KEY].GetInt(); auto it = m_PendingEvents.find(event); if (it != m_PendingEvents.end()) { auto rectJson = response.FindMember(""rectArgument""); if (rectJson != response.MemberEnd()) { apl::Rect rect = convertJsonToScaledRect(rectJson->value); it->second.resolve(rect); } else { auto arg = response.FindMember(ARGUMENT_KEY); if (arg != response.MemberEnd()) { it->second.resolve(arg->value.GetInt()); } else { it->second.resolve(); } } m_PendingEvents.erase(it); } } unsigned int AplCoreConnectionManager::send(AplCoreViewhostMessage& message) { unsigned int seqno = ++m_SequenceNumber; m_aplConfiguration->getAplOptions()->sendMessage(m_aplToken, message.setSequenceNumber(seqno).get()); return seqno; } rapidjson::Document AplCoreConnectionManager::blockingSend( AplCoreViewhostMessage& message, const std::chrono::milliseconds& timeout) { std::lock_guard lock{m_blockingSendMutex}; m_replyPromise = std::promise(); m_blockingSendReplyExpected = true; m_replyExpectedSequenceNumber = send(message); auto aplOptions = m_aplConfiguration->getAplOptions(); auto future = m_replyPromise.get_future(); auto status = future.wait_for(timeout); if (status != std::future_status::ready) { m_blockingSendReplyExpected = false; // Under the situation that finish command destroys the renderer, there is no response. aplOptions->logMessage(LogLevel::WARN, ""blockingSendFailed"", ""Did not receive response""); return rapidjson::Document(rapidjson::kNullType); } rapidjson::Document doc; if (doc.Parse(future.get()).HasParseError()) { aplOptions->logMessage(LogLevel::ERROR, ""blockingSendFailed"", ""parsingFailed""); return rapidjson::Document(rapidjson::kNullType); } return doc; } void AplCoreConnectionManager::sendError(const std::string& message) { auto reply = AplCoreViewhostMessage(ERROR_KEY); send(reply.setPayload(message)); } void AplCoreConnectionManager::handleScreenLock() { auto aplOptions = m_aplConfiguration->getAplOptions(); if (m_Root->screenLock() && !m_ScreenLock) { aplOptions->onActivityStarted(m_aplToken, APL_SCREEN_LOCK); m_ScreenLock = true; } else if (!m_Root->screenLock() && m_ScreenLock) { aplOptions->onActivityEnded(m_aplToken, APL_SCREEN_LOCK); m_ScreenLock = false; } else { return; } sendScreenLockMessage(m_ScreenLock); } void AplCoreConnectionManager::processEvent(const apl::Event& event) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (apl::EventType::kEventTypeFinish == event.getType()) { aplOptions->onFinish(m_aplToken); return; } if (apl::EventType::kEventTypeSendEvent == event.getType()) { rapidjson::Document userEventPayloadJson(rapidjson::kObjectType); auto& allocator = userEventPayloadJson.GetAllocator(); auto source = event.getValue(apl::EventProperty::kEventPropertySource); auto components = event.getValue(apl::EventProperty::kEventPropertyComponents); auto arguments = event.getValue(apl::EventProperty::kEventPropertyArguments); userEventPayloadJson.AddMember( PRESENTATION_TOKEN_KEY, rapidjson::Value(m_aplToken.c_str(), allocator).Move(), allocator); userEventPayloadJson.AddMember(SOURCE_KEY, source.serialize(allocator).Move(), allocator); userEventPayloadJson.AddMember(ARGUMENTS_KEY, arguments.serialize(allocator).Move(), allocator); userEventPayloadJson.AddMember(COMPONENTS_KEY, components.serialize(allocator).Move(), allocator); rapidjson::StringBuffer sb; rapidjson::Writer writer(sb); userEventPayloadJson.Accept(writer); aplOptions->onSendEvent(m_aplToken, sb.GetString()); return; } if (apl::EventType::kEventTypeDataSourceFetchRequest == event.getType()) { rapidjson::Document fetchRequestPayloadJson(rapidjson::kObjectType); auto& allocator = fetchRequestPayloadJson.GetAllocator(); auto type = event.getValue(apl::EventProperty::kEventPropertyName); auto payload = event.getValue(apl::EventProperty::kEventPropertyValue); apl::ObjectMap fetchRequest(payload.getMap()); fetchRequest.emplace(PRESENTATION_TOKEN_KEY, m_aplToken); auto fetch = apl::Object(std::make_shared(fetchRequest)).serialize(allocator); rapidjson::StringBuffer sb; rapidjson::Writer writer(sb); fetch.Accept(writer); aplOptions->onDataSourceFetchRequestEvent(m_aplToken, type.asString(), sb.GetString()); return; } if (apl::EventType::kEventTypeExtension == event.getType()) { /** * Extension Events are received when registered ExtensionCommands are fired * https://github.com/alexa/apl-core-library/blob/master/aplcore/include/apl/content/extensioncommanddefinition.h */ rapidjson::Document extensionEventPayloadJson(rapidjson::kObjectType); auto& allocator = extensionEventPayloadJson.GetAllocator(); auto uri = event.getValue(apl::EventProperty::kEventPropertyExtensionURI); auto name = event.getValue(apl::EventProperty::kEventPropertyName); auto source = event.getValue(apl::EventProperty::kEventPropertySource); auto params = event.getValue(apl::EventProperty::kEventPropertyExtension); std::string sourceStr; std::string paramsStr; serializeJSONValueToString(source.serialize(allocator).Move(), &sourceStr); serializeJSONValueToString(params.serialize(allocator).Move(), ¶msStr); /** * If the registered ExtensionCommand requires resolution, the resultCallback should be registered with the * extension * https://github.com/alexa/apl-core-library/blob/master/aplcore/include/apl/content/extensioncommanddefinition.h#L87 */ auto token = ++m_SequenceNumber; auto resultCallback = addPendingEvent(token, event, false) ? shared_from_this() : nullptr; aplOptions->onExtensionEvent(m_aplToken, uri.getString(), name.getString(), sourceStr, paramsStr, token, resultCallback); return; } auto msg = AplCoreViewhostMessage(EVENT_KEY); auto token = send(msg.setPayload(event.serialize(msg.alloc()))); addPendingEvent(token, event); } bool AplCoreConnectionManager::addPendingEvent(unsigned int token, const apl::Event& event, bool isViewhostEvent) { // If the event had an action ref, stash the reference for future use auto ref = event.getActionRef(); if (!ref.isEmpty()) { m_PendingEvents.emplace(token, ref); ref.addTerminateCallback([this, token, isViewhostEvent](const apl::TimersPtr&) { auto it = m_PendingEvents.find(token); if (it != m_PendingEvents.end()) { if (isViewhostEvent) { auto msg = AplCoreViewhostMessage(EVENT_TERMINATE_KEY); rapidjson::Value payload(rapidjson::kObjectType); payload.AddMember(""token"", token, msg.alloc()); send(msg.setPayload(std::move(payload))); } m_PendingEvents.erase(it); // Remove the pending event } else { m_aplConfiguration->getAplOptions()->logMessage(LogLevel::WARN, __func__, ""Event was not pending""); } }); return true; } return false; } void AplCoreConnectionManager::sendHierarchy(const std::string& messageKey, bool blocking) { if (m_Root) { auto reply = AplCoreViewhostMessage(messageKey); rapidjson::Value hierarchy(rapidjson::kObjectType); hierarchy.AddMember(""hierarchy"", m_Root->topComponent()->serialize(reply.alloc()), reply.alloc()); rapidjson::Value displayedChildrenHierarchy = buildDisplayedChildrenHierarchy(m_Root->topComponent(), reply); hierarchy.AddMember(""displayedChildrenHierarchy"", displayedChildrenHierarchy, reply.alloc()); if (blocking) { blockingSend(reply.setPayload(std::move(hierarchy))); } else { send(reply.setPayload(std::move(hierarchy))); } } } rapidjson::Value AplCoreConnectionManager::buildDisplayedChildrenHierarchy(const apl::ComponentPtr& component, AplCoreViewhostMessage& message) { rapidjson::Value displayedChildrenHierarchy(rapidjson::kObjectType); std::vector stack; stack.push_back(component); while(!stack.empty()) { rapidjson::Value displayedChildrenUniqueIds(rapidjson::kArrayType); apl::ComponentPtr node = stack.back(); stack.pop_back(); auto count = node->getDisplayedChildCount(); for (size_t i = 0; i < count; i++) { auto childComponent = node->getDisplayedChildAt(i); auto str = childComponent->getUniqueId(); displayedChildrenUniqueIds.PushBack(rapidjson::Value{}.SetString(str.c_str(), str.length(), message.alloc()), message.alloc()); stack.push_back(childComponent); } displayedChildrenHierarchy.AddMember( rapidjson::Value{}.SetString(node->getUniqueId().c_str(), node->getUniqueId().length(),message.alloc()), displayedChildrenUniqueIds, message.alloc()); } return displayedChildrenHierarchy; } void AplCoreConnectionManager::processDirty(const std::set& dirty) { std::map tempDirty; auto msg = AplCoreViewhostMessage(DIRTY_KEY); for (auto& component : dirty) { if (component->getDirty().count(apl::kPropertyNotifyChildrenChanged)) { auto notify = component->getCalculated(apl::kPropertyNotifyChildrenChanged); const auto& changed = notify.getArray(); // Whenever we get NotifyChildrenChanged we get 2 types of action // Either insert or delete. The delete will happen on the viewhost level // However, insert needs the full serialized component from core & will be initalized // on apl-client side for (size_t i = 0; i < changed.size(); i++) { auto newChildId = changed.at(i).get(""uid"").asString(); auto newChildIndex = changed.at(i).get(""index"").asInt(); auto action = changed.at(i).get(""action"").asString(); if (action == ""insert"") { auto newComponent = component->getChildAt(newChildIndex); rapidjson::Value newComponentHierarchy = newComponent->serialize(msg.alloc()); rapidjson::Value displayedChildrenHierarchy = buildDisplayedChildrenHierarchy(newComponent, msg); newComponentHierarchy.AddMember(""displayedChildrenHierarchy"", displayedChildrenHierarchy, msg.alloc()); tempDirty[newChildId] = newComponentHierarchy; } } if (tempDirty.find(component->getUniqueId()) == tempDirty.end()) { // notify children change needs to update displayed children ids rapidjson::Value dirtyWithChildChange = component->serializeDirty(msg.alloc()); rapidjson::Value displayedChildrenHierarchy = buildDisplayedChildrenHierarchy(component, msg); dirtyWithChildChange.AddMember(""displayedChildrenHierarchy"", displayedChildrenHierarchy, msg.alloc()); tempDirty[component->getUniqueId()] = dirtyWithChildChange; } } if (component->getDirty().count(apl::kPropertyGraphic)) { // for graphic component, apl-client need walk into graphicPtr to get dirty and dirtyPropertyKeys. rapidjson::Value vectorGraphicComponent = component->serializeDirty(msg.alloc()); rapidjson::Value dirtyGraphicElement(rapidjson::kArrayType); const apl::GraphicPtr graphic = component->getCalculated(apl::kPropertyGraphic).getGraphic(); for (auto& graphicDirty : graphic->getDirty()) { rapidjson::Value serializedGraphicElement = graphicDirty->serialize(msg.alloc()); rapidjson::Value dirtyPropertyKeys(rapidjson::kArrayType); for (auto& dirtyPropertyKey : graphicDirty->getDirtyProperties()) { dirtyPropertyKeys.PushBack(dirtyPropertyKey, msg.alloc()); } serializedGraphicElement.AddMember(""dirtyProperties"", dirtyPropertyKeys, msg.alloc()); dirtyGraphicElement.PushBack(serializedGraphicElement, msg.alloc()); } if (vectorGraphicComponent.HasMember(""graphic"") && vectorGraphicComponent[""graphic""].IsObject()) { vectorGraphicComponent[""graphic""].AddMember(""dirty"", dirtyGraphicElement, msg.alloc()); } tempDirty[component->getUniqueId()] = vectorGraphicComponent; } if (tempDirty.find(component->getUniqueId()) == tempDirty.end()) { tempDirty.emplace(component->getUniqueId(), component->serializeDirty(msg.alloc())); } } rapidjson::Value array(rapidjson::kArrayType); for (auto rit = tempDirty.rbegin(); rit != tempDirty.rend(); rit++) { auto uid = rit->first; auto& update = rit->second; array.PushBack(update.Move(), msg.alloc()); } send(msg.setPayload(std::move(array))); } void AplCoreConnectionManager::coreFrameUpdate() { auto aplOptions = m_aplConfiguration->getAplOptions(); auto now = getCurrentTime() - m_StartTime; m_Root->updateTime(now.count(), getCurrentTime().count()); m_Root->setLocalTimeAdjustment(aplOptions->getTimezoneOffset().count()); m_Root->clearPending(); while (m_Root->hasEvent()) { processEvent(m_Root->popEvent()); } if (m_Root->isDirty()) { processDirty(m_Root->getDirty()); m_Root->clearDirty(); } handleScreenLock(); } void AplCoreConnectionManager::onUpdateTick() { if (m_Root) { coreFrameUpdate(); // Check regularly as something like timed-out fetch requests could come up. checkAndSendDataSourceErrors(); } } apl::Rect AplCoreConnectionManager::convertJsonToScaledRect(const rapidjson::Value& jsonNode) { const float scale = m_AplCoreMetrics->toCore(1.0f); const float x = jsonNode[X_KEY].IsNumber() ? jsonNode[X_KEY].GetFloat() : 0.0f; const float y = jsonNode[Y_KEY].IsNumber() ? jsonNode[Y_KEY].GetFloat() : 0.0f; const float width = jsonNode[WIDTH_KEY].IsNumber() ? jsonNode[WIDTH_KEY].GetFloat() : 0.0f; const float height = jsonNode[HEIGHT_KEY].IsNumber() ? jsonNode[HEIGHT_KEY].GetFloat() : 0.0f; return apl::Rect(x * scale, y * scale, width * scale, height * scale); } void AplCoreConnectionManager::checkAndSendDataSourceErrors() { if (!m_Root) return; std::vector errorArray; for (auto& type : KNOWN_DATA_SOURCES) { auto provider = m_Root->getRootConfig().getDataSourceProvider(type); if (provider) { auto pendingErrors = provider->getPendingErrors(); if (!pendingErrors.empty() && pendingErrors.isArray()) { errorArray.insert(errorArray.end(), pendingErrors.getArray().begin(), pendingErrors.getArray().end()); } } } auto errors = apl::Object(std::make_shared(errorArray)); if (!errors.empty()) { auto errorEvent = std::make_shared(); errorEvent->emplace(PRESENTATION_TOKEN_KEY, m_aplToken); errorEvent->emplace(ERRORS_KEY, errors); rapidjson::Document runtimeErrorPayloadJson(rapidjson::kObjectType); auto& allocator = runtimeErrorPayloadJson.GetAllocator(); auto runtimeError = apl::Object(errorEvent).serialize(allocator); rapidjson::StringBuffer sb; rapidjson::Writer writer(sb); runtimeError.Accept(writer); m_aplConfiguration->getAplOptions()->onRuntimeErrorEvent(m_aplToken, sb.GetString()); } } const std::string AplCoreConnectionManager::getAPLToken() { return m_aplToken; } void AplCoreConnectionManager::serializeJSONValueToString(const rapidjson::Value& documentNode, std::string* value) { rapidjson::StringBuffer stringBuffer; rapidjson::Writer writer(stringBuffer); if (!documentNode.Accept(writer)) { auto aplOptions = m_aplConfiguration->getAplOptions(); aplOptions->logMessage(LogLevel::ERROR, ""serializeJSONValueToStringFailed"", ""acceptFailed""); return; } *value = stringBuffer.GetString(); } void AplCoreConnectionManager::addExtensions( std::unordered_set> extensions) { for (auto& extension : extensions) { extension->setEventHandler(shared_from_this()); m_extensionManager->addExtension(extension); } } std::shared_ptr AplCoreConnectionManager::getExtension(const std::string& uri) { return m_extensionManager->getExtension(uri); } void AplCoreConnectionManager::reset() { m_aplToken = """"; m_Root.reset(); m_Content.reset(); } void AplCoreConnectionManager::handleIsCharacterValid(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleIsCharacterValidFailed"", ""Root context is null""); return; } auto messageId = payload[""messageId""].GetString(); if (!messageId) { aplOptions->logMessage( LogLevel::ERROR, ""handleIsCharacterValidFailed"", std::string(""Payload does not contain messageId"")); sendError(""Payload does not contain messageId""); return; } auto character = payload[""character""].GetString(); if (!character) { aplOptions->logMessage( LogLevel::ERROR, ""handleIsCharacterValidFailed"", std::string(""Payload does not contain character"")); sendError(""Payload does not contain character""); return; } auto componentId = payload[""componentId""].GetString(); if (!componentId) { aplOptions->logMessage( LogLevel::ERROR, ""handleIsCharacterValidFailed"", std::string(""Payload does not contain componentId"")); sendError(""Payload does not contain componentId""); return; } auto component = m_Root->findComponentById(componentId); if (!component) { aplOptions->logMessage( LogLevel::ERROR, ""handleIsCharacterValidFailed"", std::string(""Unable to find component with id: "") + componentId); sendError(""Unable to find component""); return; } auto result = component->isCharacterValid(character[0]); auto resultMessage = AplCoreViewhostMessage(""isCharacterValid""); auto& alloc = resultMessage.alloc(); rapidjson::Value resultMessageValue(rapidjson::kObjectType); rapidjson::Value messageIdValue; messageIdValue.SetString(messageId, alloc); resultMessageValue.AddMember(""messageId"", messageIdValue, alloc); resultMessageValue.AddMember(""valid"", result, alloc); rapidjson::Value componentIdValue; componentIdValue.SetString(componentId, alloc); resultMessageValue.AddMember(""componentId"", componentIdValue, alloc); resultMessage.setPayload(std::move(resultMessageValue)); send(resultMessage); } void AplCoreConnectionManager::handleReInflate(const rapidjson::Value& payload) { auto aplOptions = m_aplConfiguration->getAplOptions(); if (!m_Root) { aplOptions->logMessage(LogLevel::ERROR, ""handleIsCharacterValidFailed"", ""Root context is null""); return; } m_Root->reinflate(); // update component hierarchy sendHierarchy(HIERARCHY_KEY); } void AplCoreConnectionManager::handleReHierarchy(const rapidjson::Value& payload) { // send component hierarchy sendHierarchy(REHIERARCHY_KEY, true); } void AplCoreConnectionManager::updateConfigurationChange(const apl::ConfigurationChange& configurationChange) { m_ConfigurationChange.mergeConfigurationChange(configurationChange); } void AplCoreConnectionManager::handleExtensionMessage(const rapidjson::Value& payload) { auto const& uriMember = payload.FindMember(""uri"")->value; auto const& nameMember = payload.FindMember(""name"")->value; auto const& fastModeMember = payload.FindMember(""fastMode"")->value; auto const aplOptions = m_aplConfiguration->getAplOptions(); if (!uriMember.IsString() || !nameMember.IsString() || !fastModeMember.IsBool()) { aplOptions->logMessage(LogLevel::ERROR, ""handleExtensionMessageFailed"", ""Could not parse extensionMessage""); return; } auto const uri = uriMember.GetString(); auto const name = nameMember.GetString(); auto const fastMode = fastModeMember.GetBool(); auto const& dataMember = payload.FindMember(""data"")->value; apl::ObjectMap data; for (auto itr = dataMember.MemberBegin(); itr != dataMember.MemberEnd(); ++itr) { if (!itr->value.IsString()) { aplOptions->logMessage(LogLevel::ERROR, ""handleExtensionMessageFailed"", ""Could not parse extensionMessage data""); continue; } data.emplace(itr->name.GetString(), itr->value.GetString()); } invokeExtensionEventHandler(uri, name, data, fastMode); } } // namespace APLClient ",16373,True,3137.7175278270734,median "[[install-config-syncing-groups-with-ldap]] = Syncing groups With LDAP {product-author} {product-version} :data-uri: :icons: :experimental: :toc: macro :toc-title: toc::[] == Overview As an {product-title} administrator, you can use groups to manage users, change their permissions, and enhance collaboration. Your organization may have already created user groups and stored them in an LDAP server. {product-title} can sync those LDAP records with internal {product-title} records, enabling you to manage your groups in one place. {product-title} currently supports group sync with LDAP servers using three common schemas for defining group membership: RFC 2307, Active Directory, and augmented Active Directory. [NOTE] ==== You must have xref:../architecture/additional_concepts/authorization.adoc#roles[`cluster-admin` privileges] to sync groups. ==== [[configuring-ldap-sync]] == Configuring LDAP sync Before you can xref:running-ldap-sync[run LDAP sync], you need a sync configuration file. This file contains LDAP client configuration details: * Configuration for connecting to your LDAP server. * Sync configuration options that are dependent on the schema used in your LDAP server. A sync configuration file can also contain an administrator-defined list of name mappings that maps {product-title} group names to groups in your LDAP server. [[ldap-client-configuration]] === LDAP client configuration .LDAP client configuration [source,yaml] ---- url: ldap://10.0.0.0:389 <1> bindDN: cn=admin,dc=example,dc=com <2> bindPassword: password <3> insecure: false <4> ca: my-ldap-ca-bundle.crt <5> ---- <1> The connection protocol, IP address of the LDAP server hosting your database, and the port to connect to, formatted as `scheme://host:port`. <2> Optional distinguished name (DN) to use as the Bind DN. {product-title} uses this if elevated privilege is required to retrieve entries for the sync operation. <3> Optional password to use to bind. {product-title} uses this if elevated privilege is necessary to retrieve entries for the sync operation. This value may also be provided in an xref:../install_config/master_node_configuration.adoc#master-node-configuration-passwords-and-other-data[environment variable, external file, or encrypted file]. <4> When `true`, no TLS connection is made to the server. When `false`, secure LDAP (`ldaps://`) URLs connect using TLS, and insecure LDAP (`ldap://`) URLs are upgraded to TLS. <5> The certificate bundle to use for validating server certificates for the configured URL. If empty, {product-title} uses system-trusted roots. This only applies if `insecure` is set to `false`. [[ldap-query-definition]] === LDAP query definition Sync configurations consist of LDAP query definitions for the entries that are required for synchronization. The specific definition of an LDAP query depends on the schema used to store membership information in the LDAP server. .LDAP query definition [source,yaml] ---- baseDN: ou=users,dc=example,dc=com <1> scope: sub <2> derefAliases: never <3> timeout: 0 <4> filter: (objectClass=inetOrgPerson) <5> pageSize: 0 <6> ---- <1> The distinguished name (DN) of the branch of the directory where all searches will start from. It is required that you specify the top of your directory tree, but you can also specify a subtree in the directory. <2> The scope of the search. Valid values are `base`, `one`, or `sub`. If this is left undefined, then a scope of `sub` is assumed. Descriptions of the scope options can be found in the xref:ldap-search[table below]. <3> The behavior of the search with respect to aliases in the LDAP tree. Valid values are `never`, `search`, `base`, or `always`. If this is left undefined, then the default is to `always` dereference aliases. Descriptions of the dereferencing behaviors can be found in the xref:deref-aliases[table below]. <4> The time limit allowed for the search by the client, in seconds. A value of 0 imposes no client-side limit. <5> A valid LDAP search filter. If this is left undefined, then the default is `(objectClass=*)`. <6> The optional maximum size of response pages from the server, measured in LDAP entries. If set to 0, no size restrictions will be made on pages of responses. Setting paging sizes is necessary when queries return more entries than the client or server allow by default. [[ldap-search]] .LDAP search scope options [cols=""2a,8a"",options=""header""] |=== |LDAP Search Scope | Description .^|`base` | Only consider the object specified by the base DN given for the query. .^|`one` | Consider all of the objects on the same level in the tree as the base DN for the query. .^|`sub` | Consider the entire subtree rooted at the base DN given for the query. |=== [[deref-aliases]] .LDAP dereferencing behaviors [cols=""2a,8a"",options=""header""] |=== |Dereferencing Behavior | Description .^|`never` | Never dereference any aliases found in the LDAP tree. .^|`search` | Only dereference aliases found while searching. .^|`base` | Only dereference aliases while finding the base object. .^|`always` | Always dereference all aliases found in the LDAP tree. |=== [[user-defined-name-mapping]] === User-defined name mapping A user-defined name mapping explicitly maps the names of {product-title} groups to unique identifiers that find groups on your LDAP server. The mapping uses normal YAML syntax. A user-defined mapping can contain an entry for every group in your LDAP server or only a subset of those groups. If there are groups on the LDAP server that do not have a user-defined name mapping, the default behavior during sync is to use the attribute specified as the {product-title} group's name. .User-defined name mapping [source,yaml] ---- groupUIDNameMapping: ""cn=group1,ou=groups,dc=example,dc=com"": firstgroup ""cn=group2,ou=groups,dc=example,dc=com"": secondgroup ""cn=group3,ou=groups,dc=example,dc=com"": thirdgroup ---- [[running-ldap-sync]] == Running LDAP sync Once you have created a xref:configuring-ldap-sync[sync configuration file], then sync can begin. {product-title} allows administrators to perform a number of different sync types with the same server. [NOTE] ==== By default, all group synchronization or pruning operations are dry-run, so you must set the `--confirm` flag on the `oc adm groups sync` command in order to make changes to {product-title} group records. ==== To sync all groups from the LDAP server with {product-title}: ---- $ oc adm groups sync --sync-config=config.yaml --confirm ---- To sync all groups already in {product-title} that correspond to groups in the LDAP server specified in the configuration file: ---- $ oc adm groups sync --type=openshift --sync-config=config.yaml --confirm ---- To sync a subset of LDAP groups with {product-title}, you can use whitelist files, blacklist files, or both: [NOTE] ==== You can use any combination of blacklist files, whitelist files, or whitelist literals. Whitelist and blacklist files must contain one unique group identifier per line, and you can include whitelist literals directly in the command itself. These guidelines apply to groups found on LDAP servers as well as groups already present in {product-title}. ==== ---- $ oc adm groups sync --whitelist= \\ --sync-config=config.yaml \\ --confirm $ oc adm groups sync --blacklist= \\ --sync-config=config.yaml \\ --confirm $ oc adm groups sync \\ --sync-config=config.yaml \\ --confirm $ oc adm groups sync \\ --whitelist= \\ --blacklist= \\ --sync-config=config.yaml \\ --confirm $ oc adm groups sync --type=openshift \\ --whitelist= \\ --sync-config=config.yaml \\ --confirm ---- [[running-a-group-pruning-job]] == Running a group pruning job An administrator can also choose to remove groups from {product-title} records if the records on the LDAP server that created them are no longer present. The prune job will accept the same sync configuration file and white- or black-lists as used for the sync job. More information is available in xref:../admin_guide/pruning_resources.adoc#pruning-groups[Pruning groups] section. [[sync-examples]] == Sync examples This section contains examples for the xref:sync-ldap-rfc-2307[RFC 2307], xref:sync-ldap-active-directory[Active Directory], and xref:sync-ldap-augmented-active-directory[augmented Active Directory] schemas. All of the following examples synchronize a group named `admins` that has two members: `Jane` and `Jim`. Each example explains: * How the group and users are added to the LDAP server. * What the LDAP sync configuration file looks like. * What the resulting group record in {product-title} will be after synchronization. [NOTE] ==== These examples assume that all users are direct members of their respective groups. Specifically, no groups have other groups as members. See xref:sync-ldap-nested-example[Nested Membership Sync Example] for information on how to sync nested groups. ==== [[sync-ldap-rfc-2307]] === Syncing groups by using RFC 2307 schema In the RFC 2307 schema, both users (Jane and Jim) and groups exist on the LDAP server as first-class entries, and group membership is stored in attributes on the group. The following snippet of `ldif` defines the users and group for this schema: .LDAP entries that use RFC 2307 schema: *_rfc2307.ldif_* [source,ldif] ---- dn: ou=users,dc=example,dc=com objectClass: organizationalUnit ou: users dn: cn=Jane,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson cn: Jane sn: Smith displayName: Jane Smith mail: jane.smith@example.com dn: cn=Jim,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson cn: Jim sn: Adams displayName: Jim Adams mail: jim.adams@example.com dn: ou=groups,dc=example,dc=com objectClass: organizationalUnit ou: groups dn: cn=admins,ou=groups,dc=example,dc=com <1> objectClass: groupOfNames cn: admins owner: cn=admin,dc=example,dc=com description: System Administrators member: cn=Jane,ou=users,dc=example,dc=com <2> member: cn=Jim,ou=users,dc=example,dc=com ---- <1> The group is a first-class entry in the LDAP server. <2> Members of a group are listed with an identifying reference as attributes on the group. To sync this group, you must first create the configuration file. The RFC 2307 schema requires you to provide an LDAP query definition for both user and group entries, as well as the attributes with which to represent them in the internal {product-title} records. For clarity, the group you create in {product-title} should use attributes other than the distinguished name whenever possible for user- or administrator-facing fields. For example, identify the users of an {product-title} group by their e-mail, and use the name of the group as the common name. The following configuration file creates these relationships: [NOTE] ==== If using user-defined name mappings, your xref:rfc2307-with-user-defined-name-mappings[configuration file] will differ. ==== .LDAP sync configuration that uses RFC 2307 schema: *_rfc2307_config.yaml_* [source,yaml] ---- kind: LDAPSyncConfig apiVersion: v1 url: ldap://LDAP_SERVICE_IP:389 <1> insecure: false <2> rfc2307: groupsQuery: baseDN: ""ou=groups,dc=example,dc=com"" scope: sub derefAliases: never pageSize: 0 groupUIDAttribute: dn <3> groupNameAttributes: [ cn ] <4> groupMembershipAttributes: [ member ] <5> usersQuery: baseDN: ""ou=users,dc=example,dc=com"" scope: sub derefAliases: never pageSize: 0 userUIDAttribute: dn <6> userNameAttributes: [ mail ] <7> tolerateMemberNotFoundErrors: false tolerateMemberOutOfScopeErrors: false ---- <1> The IP address and host of the LDAP server where this group's record is stored. <2> When `true`, no TLS connection is made to the server. When `false`, secure LDAP (`ldaps://`) URLs connect using TLS, and insecure LDAP (`ldap://`) URLs are upgraded to TLS. <3> The attribute that uniquely identifies a group on the LDAP server. You cannot specify `groupsQuery` filters when using DN for groupUIDAttribute. For fine-grained filtering, use the xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelist / blacklist method]. <4> The attribute to use as the name of the group. <5> The attribute on the group that stores the membership information. <6> The attribute that uniquely identifies a user on the LDAP server. You cannot specify `usersQuery` filters when using DN for userUIDAttribute. For fine-grained filtering, use the xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelist / blacklist method]. <7> The attribute to use as the name of the user in the {product-title} group record. To run sync with the *_rfc2307_config.yaml_* file: ---- $ oc adm groups sync --sync-config=rfc2307_config.yaml --confirm ---- {product-title} creates the following group record as a result of the above sync operation: .{product-title} group created by using the *_rfc2307_config.yaml_* file [source,yaml] ---- apiVersion: user.openshift.io/v1 kind: Group metadata: annotations: openshift.io/ldap.sync-time: 2015-10-13T10:08:38-0400 <1> openshift.io/ldap.uid: cn=admins,ou=groups,dc=example,dc=com <2> openshift.io/ldap.url: LDAP_SERVER_IP:389 <3> creationTimestamp: name: admins <4> users: <5> - jane.smith@example.com - jim.adams@example.com ---- <1> The last time this {product-title} group was synchronized with the LDAP server, in ISO 6801 format. <2> The unique identifier for the group on the LDAP server. <3> The IP address and host of the LDAP server where this group's record is stored. <4> The name of the group as specified by the sync file. <5> The users that are members of the group, named as specified by the sync file. [[rfc2307-with-user-defined-name-mappings]] ==== RFC2307 with user-defined name mappings When syncing groups with user-defined name mappings, the configuration file changes to contain these mappings as shown below. .LDAP sync configuration that uses RFC 2307 schema with user-defined name mappings: *_rfc2307_config_user_defined.yaml_* [source,yaml] ---- kind: LDAPSyncConfig apiVersion: v1 groupUIDNameMapping: ""cn=admins,ou=groups,dc=example,dc=com"": Administrators <1> rfc2307: groupsQuery: baseDN: ""ou=groups,dc=example,dc=com"" scope: sub derefAliases: never pageSize: 0 groupUIDAttribute: dn <2> groupNameAttributes: [ cn ] <3> groupMembershipAttributes: [ member ] usersQuery: baseDN: ""ou=users,dc=example,dc=com"" scope: sub derefAliases: never pageSize: 0 userUIDAttribute: dn <4> userNameAttributes: [ mail ] tolerateMemberNotFoundErrors: false tolerateMemberOutOfScopeErrors: false ---- <1> The user-defined name mapping. <2> The unique identifier attribute that is used for the keys in the user-defined name mapping. You cannot specify `groupsQuery` filters when using DN for groupUIDAttribute. For fine-grained filtering, use the xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelist / blacklist method]. <3> The attribute to name {product-title} groups with if their unique identifier is not in the user-defined name mapping. <4> The attribute that uniquely identifies a user on the LDAP server. You cannot specify `usersQuery` filters when using DN for userUIDAttribute. For fine-grained filtering, use the xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelist / blacklist method]. To run sync with the *_rfc2307_config_user_defined.yaml_* file: ---- $ oc adm groups sync --sync-config=rfc2307_config_user_defined.yaml --confirm ---- {product-title} creates the following group record as a result of the above sync operation: .{product-title} group created by using the *_rfc2307_config_user_defined.yaml_* file [source,yaml] ---- apiVersion: user.openshift.io/v1 kind: Group metadata: annotations: openshift.io/ldap.sync-time: 2015-10-13T10:08:38-0400 openshift.io/ldap.uid: cn=admins,ou=groups,dc=example,dc=com openshift.io/ldap.url: LDAP_SERVER_IP:389 creationTimestamp: name: Administrators <1> users: - jane.smith@example.com - jim.adams@example.com ---- <1> The name of the group as specified by the user-defined name mapping. [[rfc2307-with-error-tolerances]] === Syncing groups by using RFC 2307 with user-defined error tolerances By default, if the groups being synced contain members whose entries are outside of the scope defined in the member query, the group sync fails with an error: ---- Error determining LDAP group membership for """": membership lookup for user """" in group """" failed because of ""search for entry with dn="""" would search outside of the base dn specified (dn="""")"". ---- This often indicates a mis-configured `baseDN` in the `usersQuery` field. However, in cases where the `baseDN` intentionally does not contain some of the members of the group, setting `tolerateMemberOutOfScopeErrors: true` allows the group sync to continue. Out of scope members will be ignored. Similarly, when the group sync process fails to locate a member for a group, it fails outright with errors: ---- Error determining LDAP group membership for """": membership lookup for user """" in group """" failed because of ""search for entry with base dn="""" refers to a non-existent entry"". Error determining LDAP group membership for """": membership lookup for user """" in group """" failed because of ""search for entry with base dn="""" and filter """" did not return any results"". ---- This often indicates a mis-configured `usersQuery` field. However, in cases where the group contains member entries that are known to be missing, setting `tolerateMemberNotFoundErrors: true` allows the group sync to continue. Problematic members will be ignored. [WARNING] ==== Enabling error tolerances for the LDAP group sync causes the sync process to ignore problematic member entries. If the LDAP group sync is not configured correctly, this could result in synced {product-title} groups missing members. ==== .LDAP entries that use RFC 2307 schema with problematic group membership: *_rfc2307_problematic_users.ldif_* [source,ldif] ---- dn: ou=users,dc=example,dc=com objectClass: organizationalUnit ou: users dn: cn=Jane,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson cn: Jane sn: Smith displayName: Jane Smith mail: jane.smith@example.com dn: cn=Jim,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson cn: Jim sn: Adams displayName: Jim Adams mail: jim.adams@example.com dn: ou=groups,dc=example,dc=com objectClass: organizationalUnit ou: groups dn: cn=admins,ou=groups,dc=example,dc=com objectClass: groupOfNames cn: admins owner: cn=admin,dc=example,dc=com description: System Administrators member: cn=Jane,ou=users,dc=example,dc=com member: cn=Jim,ou=users,dc=example,dc=com member: cn=INVALID,ou=users,dc=example,dc=com <1> member: cn=Jim,ou=OUTOFSCOPE,dc=example,dc=com <2> ---- <1> A member that does not exist on the LDAP server. <2> A member that may exist, but is not under the `baseDN` in the user query for the sync job. In order to tolerate the errors in the above example, the following additions to your sync configuration file must be made: .LDAP sync configuration that uses RFC 2307 schema tolerating errors: *_rfc2307_config_tolerating.yaml_* [source,yaml] ---- kind: LDAPSyncConfig apiVersion: v1 url: ldap://LDAP_SERVICE_IP:389 rfc2307: groupsQuery: baseDN: ""ou=groups,dc=example,dc=com"" scope: sub derefAliases: never groupUIDAttribute: dn groupNameAttributes: [ cn ] groupMembershipAttributes: [ member ] usersQuery: baseDN: ""ou=users,dc=example,dc=com"" scope: sub derefAliases: never userUIDAttribute: dn <3> userNameAttributes: [ mail ] tolerateMemberNotFoundErrors: true <1> tolerateMemberOutOfScopeErrors: true <2> ---- <1> When `true`, the sync job tolerates groups for which some members were not found, and members whose LDAP entries are not found are ignored. The default behavior for the sync job is to fail if a member of a group is not found. <2> When `true`, the sync job tolerates groups for which some members are outside the user scope given in the `usersQuery` base DN, and members outside the member query scope are ignored. The default behavior for the sync job is to fail if a member of a group is out of scope. <3> The attribute that uniquely identifies a user on the LDAP server. You cannot specify `usersQuery` filters when using DN for userUIDAttribute. For fine-grained filtering, use the xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelist / blacklist method]. To run sync with the *_rfc2307_config_tolerating.yaml_* file: ---- $ oc adm groups sync --sync-config=rfc2307_config_tolerating.yaml --confirm ---- {product-title} creates the following group record as a result of the above sync operation: .{product-title} group created by using the *_rfc2307_config.yaml_* file [source,yaml] ---- apiVersion: user.openshift.io/v1 kind: Group metadata: annotations: openshift.io/ldap.sync-time: 2015-10-13T10:08:38-0400 openshift.io/ldap.uid: cn=admins,ou=groups,dc=example,dc=com openshift.io/ldap.url: LDAP_SERVER_IP:389 creationTimestamp: name: admins users: <1> - jane.smith@example.com - jim.adams@example.com ---- <1> The users that are members of the group, as specified by the sync file. Members for which lookup encountered tolerated errors are absent. [[sync-ldap-active-directory]] === Syncing groups by using Active Directory In the Active Directory schema, both users (Jane and Jim) exist in the LDAP server as first-class entries, and group membership is stored in attributes on the user. The following snippet of `ldif` defines the users and group for this schema: .LDAP entries that use Active Directory schema: *_active_directory.ldif_* [source,ldif] ---- dn: ou=users,dc=example,dc=com objectClass: organizationalUnit ou: users dn: cn=Jane,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: testPerson cn: Jane sn: Smith displayName: Jane Smith mail: jane.smith@example.com memberOf: admins <1> dn: cn=Jim,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: testPerson cn: Jim sn: Adams displayName: Jim Adams mail: jim.adams@example.com memberOf: admins ---- <1> The user's group memberships are listed as attributes on the user, and the group does not exist as an entry on the server. The `memberOf` attribute does not have to be a literal attribute on the user; in some LDAP servers, it is created during search and returned to the client, but not committed to the database. To sync this group, you must first create the configuration file. The Active Directory schema requires you to provide an LDAP query definition for user entries, as well as the attributes to represent them with in the internal {product-title} group records. For clarity, the group you create in {product-title} should use attributes other than the distinguished name whenever possible for user- or administrator-facing fields. For example, identify the users of an {product-title} group by their e-mail, but define the name of the group by the name of the group on the LDAP server. The following configuration file creates these relationships: .LDAP sync configuration that uses Active Directory schema: *_active_directory_config.yaml_* [source,yaml] ---- kind: LDAPSyncConfig apiVersion: v1 url: ldap://LDAP_SERVICE_IP:389 activeDirectory: usersQuery: baseDN: ""ou=users,dc=example,dc=com"" scope: sub derefAliases: never filter: (objectclass=inetOrgPerson) pageSize: 0 userNameAttributes: [ mail ] <1> groupMembershipAttributes: [ memberOf ] <2> ---- <1> The attribute to use as the name of the user in the {product-title} group record. <2> The attribute on the user that stores the membership information. To run sync with the *_active_directory_config.yaml_* file: ---- $ oc adm groups sync --sync-config=active_directory_config.yaml --confirm ---- {product-title} creates the following group record as a result of the above sync operation: .{product-title} group created by using the *_active_directory_config.yaml_* file [source,yaml] ---- apiVersion: user.openshift.io/v1 kind: Group metadata: annotations: openshift.io/ldap.sync-time: 2015-10-13T10:08:38-0400 <1> openshift.io/ldap.uid: admins <2> openshift.io/ldap.url: LDAP_SERVER_IP:389 <3> creationTimestamp: name: admins <4> users: <5> - jane.smith@example.com - jim.adams@example.com ---- <1> The last time this {product-title} group was synchronized with the LDAP server, in ISO 6801 format. <2> The unique identifier for the group on the LDAP server. <3> The IP address and host of the LDAP server where this group's record is stored. <4> The name of the group as listed in the LDAP server. <5> The users that are members of the group, named as specified by the sync file. [[sync-ldap-augmented-active-directory]] === Syncing groups by using augmented Active Directory In the augmented Active Directory schema, both users (Jane and Jim) and groups exist in the LDAP server as first-class entries, and group membership is stored in attributes on the user. The following snippet of `ldif` defines the users and group for this schema: .LDAP entries that use augmented Active Directory schema: *_augmented_active_directory.ldif_* [source,ldif] ---- dn: ou=users,dc=example,dc=com objectClass: organizationalUnit ou: users dn: cn=Jane,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: testPerson cn: Jane sn: Smith displayName: Jane Smith mail: jane.smith@example.com memberOf: cn=admins,ou=groups,dc=example,dc=com <1> dn: cn=Jim,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: testPerson cn: Jim sn: Adams displayName: Jim Adams mail: jim.adams@example.com memberOf: cn=admins,ou=groups,dc=example,dc=com dn: ou=groups,dc=example,dc=com objectClass: organizationalUnit ou: groups dn: cn=admins,ou=groups,dc=example,dc=com <2> objectClass: groupOfNames cn: admins owner: cn=admin,dc=example,dc=com description: System Administrators member: cn=Jane,ou=users,dc=example,dc=com member: cn=Jim,ou=users,dc=example,dc=com ---- <1> The user's group memberships are listed as attributes on the user. <2> The group is a first-class entry on the LDAP server. To sync this group, you must first create the configuration file. The augmented Active Directory schema requires you to provide an LDAP query definition for both user entries and group entries, as well as the attributes with which to represent them in the internal {product-title} group records. For clarity, the group you create in {product-title} should use attributes other than the distinguished name whenever possible for user- or administrator-facing fields. For example, identify the users of an {product-title} group by their e-mail, and use the name of the group as the common name. The following configuration file creates these relationships. .LDAP sync configuration that uses augmented Active Directory schema: *_augmented_active_directory_config.yaml_* [source,yaml] ---- kind: LDAPSyncConfig apiVersion: v1 url: ldap://LDAP_SERVICE_IP:389 augmentedActiveDirectory: groupsQuery: baseDN: ""ou=groups,dc=example,dc=com"" scope: sub derefAliases: never pageSize: 0 groupUIDAttribute: dn <1> groupNameAttributes: [ cn ] <2> usersQuery: baseDN: ""ou=users,dc=example,dc=com"" scope: sub derefAliases: never filter: (objectclass=inetOrgPerson) pageSize: 0 userNameAttributes: [ mail ] <3> groupMembershipAttributes: [ memberOf ] <4> ---- <1> The attribute that uniquely identifies a group on the LDAP server. You cannot specify `groupsQuery` filters when using DN for groupUIDAttribute. For fine-grained filtering, use the xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelist / blacklist method]. <2> The attribute to use as the name of the group. <3> The attribute to use as the name of the user in the {product-title} group record. <4> The attribute on the user that stores the membership information. To run sync with the *_augmented_active_directory_config.yaml_* file: ---- $ oc adm groups sync --sync-config=augmented_active_directory_config.yaml --confirm ---- {product-title} creates the following group record as a result of the above sync operation: .OpenShift group created by using the *_augmented_active_directory_config.yaml_* file [source,yaml] ---- apiVersion: user.openshift.io/v1 kind: Group metadata: annotations: openshift.io/ldap.sync-time: 2015-10-13T10:08:38-0400 <1> openshift.io/ldap.uid: cn=admins,ou=groups,dc=example,dc=com <2> openshift.io/ldap.url: LDAP_SERVER_IP:389 <3> creationTimestamp: name: admins <4> users: <5> - jane.smith@example.com - jim.adams@example.com ---- <1> The last time this {product-title} group was synchronized with the LDAP server, in ISO 6801 format. <2> The unique identifier for the group on the LDAP server. <3> The IP address and host of the LDAP server where this group's record is stored. <4> The name of the group as specified by the sync file. <5> The users that are members of the group, named as specified by the sync file. [[sync-ldap-nested-example]] == Nested membership sync example Groups in {product-title} do not nest. The LDAP server must flatten group membership before the data can be consumed. Microsoft's Active Directory Server supports this feature via the link:https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[`LDAP_MATCHING_RULE_IN_CHAIN`] rule, which has the OID `1.2.840.113556.1.4.1941`. Furthermore, only explicitly xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelisted] groups can be synced when using this matching rule. This section has an example for the augmented Active Directory schema, which synchronizes a group named `admins` that has one user `Jane` and one group `otheradmins` as members. The `otheradmins` group has one user member: `Jim`. This example explains: * How the group and users are added to the LDAP server. * What the LDAP sync configuration file looks like. * What the resulting group record in {product-title} will be after synchronization. In the augmented Active Directory schema, both users (`Jane` and `Jim`) and groups exist in the LDAP server as first-class entries, and group membership is stored in attributes on the user or the group. The following snippet of `ldif` defines the users and groups for this schema: .LDAP entries that use augmented Active Directory schema with nested members: *_augmented_active_directory_nested.ldif_* [source,ldif] ---- dn: ou=users,dc=example,dc=com objectClass: organizationalUnit ou: users dn: cn=Jane,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: testPerson cn: Jane sn: Smith displayName: Jane Smith mail: jane.smith@example.com memberOf: cn=admins,ou=groups,dc=example,dc=com <1> dn: cn=Jim,ou=users,dc=example,dc=com objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: testPerson cn: Jim sn: Adams displayName: Jim Adams mail: jim.adams@example.com memberOf: cn=otheradmins,ou=groups,dc=example,dc=com <1> dn: ou=groups,dc=example,dc=com objectClass: organizationalUnit ou: groups dn: cn=admins,ou=groups,dc=example,dc=com <2> objectClass: group cn: admins owner: cn=admin,dc=example,dc=com description: System Administrators member: cn=Jane,ou=users,dc=example,dc=com member: cn=otheradmins,ou=groups,dc=example,dc=com dn: cn=otheradmins,ou=groups,dc=example,dc=com <2> objectClass: group cn: otheradmins owner: cn=admin,dc=example,dc=com description: Other System Administrators memberOf: cn=admins,ou=groups,dc=example,dc=com <1> <3> member: cn=Jim,ou=users,dc=example,dc=com ---- <1> The user's and group's memberships are listed as attributes on the object. <2> The groups are first-class entries on the LDAP server. <3> The `otheradmins` group is a member of the `admins` group. To sync nested groups with Active Directory, you must provide an LDAP query definition for both user entries and group entries, as well as the attributes with which to represent them in the internal {product-title} group records. Furthermore, certain changes are required in this configuration: - The `oc adm groups sync` command must explicitly xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelist] groups. - The user's `groupMembershipAttributes` must include `""memberOf:1.2.840.113556.1.4.1941:""` to comply with the https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[`LDAP_MATCHING_RULE_IN_CHAIN`] rule. - The `groupUIDAttribute` must be set to `dn`. - The `groupsQuery`: * Must not set `filter`. * Must set a valid `derefAliases`. * Should not set `baseDN` as that value is ignored. * Should not set `scope` as that value is ignored. For clarity, the group you create in {product-title} should use attributes other than the distinguished name whenever possible for user- or administrator-facing fields. For example, identify the users of an {product-title} group by their e-mail, and use the name of the group as the common name. The following configuration file creates these relationships: .LDAP sync configuration that uses augmented Active Directory schema with nested members: *_augmented_active_directory_config_nested.yaml_* [source,yaml] ---- kind: LDAPSyncConfig apiVersion: v1 url: ldap://LDAP_SERVICE_IP:389 augmentedActiveDirectory: groupsQuery: <1> derefAliases: never pageSize: 0 groupUIDAttribute: dn <2> groupNameAttributes: [ cn ] <3> usersQuery: baseDN: ""ou=users,dc=example,dc=com"" scope: sub derefAliases: never filter: (objectclass=inetOrgPerson) pageSize: 0 userNameAttributes: [ mail ] <4> groupMembershipAttributes: [ ""memberOf:1.2.840.113556.1.4.1941:"" ] <5> ---- <1> `groupsQuery` filters cannot be specified. The `groupsQuery` base DN and scope values are ignored. `groupsQuery` must set a valid `derefAliases`. <2> The attribute that uniquely identifies a group on the LDAP server. It must be set to `dn`. <3> The attribute to use as the name of the group. <4> The attribute to use as the name of the user in the {product-title} group record. `mail` or `sAMAccountName` are preferred choices in most installations. <5> The attribute on the user that stores the membership information. Note the use of https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[`LDAP_MATCHING_RULE_IN_CHAIN`]. To run sync with the *_augmented_active_directory_config_nested.yaml_* file: ---- $ oc adm groups sync \\ 'cn=admins,ou=groups,dc=example,dc=com' \\ --sync-config=augmented_active_directory_config_nested.yaml \\ --confirm ---- [NOTE] ==== You must explicitly xref:../install_config/syncing_groups_with_ldap.adoc#running-ldap-sync[whitelist] the `cn=admins,ou=groups,dc=example,dc=com` group. ==== {product-title} creates the following group record as a result of the above sync operation: .OpenShift group created by using the *_augmented_active_directory_config_nested.yaml_* file [source,yaml] ---- apiVersion: user.openshift.io/v1 kind: Group metadata: annotations: openshift.io/ldap.sync-time: 2015-10-13T10:08:38-0400 <1> openshift.io/ldap.uid: cn=admins,ou=groups,dc=example,dc=com <2> openshift.io/ldap.url: LDAP_SERVER_IP:389 <3> creationTimestamp: name: admins <4> users: <5> - jane.smith@example.com - jim.adams@example.com ---- <1> The last time this {product-title} group was synchronized with the LDAP server, in ISO 6801 format. <2> The unique identifier for the group on the LDAP server. <3> The IP address and host of the LDAP server where this group's record is stored. <4> The name of the group as specified by the sync file. <5> The users that are members of the group, named as specified by the sync file. Note that members of nested groups are included since the group membership was flattened by the Microsoft Active Directory Server. [[sync-ldap-configuration]] == LDAP sync configuration specification The object specification for the configuration file is below. Note that the different schema objects have different fields. For example, xref:sync-ldap-v1-activedirectoryconfig[v1.ActiveDirectoryConfig] has no `groupsQuery` field whereas xref:sync-ldap-v1-rfc2307config[v1.RFC2307Config] and xref:sync-ldap-v1-augmentedactivedirectoryconfig[v1.AugmentedActiveDirectoryConfig] both do. [IMPORTANT] ==== There is no support for binary attributes. All attribute data coming from the LDAP server must be in the format of a UTF-8 encoded string. For example, never use a binary attribute, such as `objectGUID`, as an ID attribute. You must use string attributes, such as `sAMAccountName` or `userPrincipalName`, instead. ==== [[sync-ldap-v1-ldapsyncconfig]] === v1.LDAPSyncConfig `LDAPSyncConfig` holds the necessary configuration options to define an LDAP group sync. [options=""header""] |=== |Name |Description |Schema |`kind` |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: link:https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#types-kinds[] |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: link:https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#resources[] |string |`url` |Host is the scheme, host and port of the LDAP server to connect to: `scheme://host:port` |string |`bindDN` |Optional DN to bind to the LDAP server with. |string |`bindPassword` |Optional password to bind with during the search phase. |xref:sync-ldap-v1-stringsource[v1.StringSource] |`insecure` |If `true`, indicates the connection should not use TLS. Cannot be set to true with a URL scheme of `ldaps://` If `false`, `ldaps://` URLs connect using TLS, and `ldap://` URLs are upgraded to a TLS connection using StartTLS as specified in link:https://tools.ietf.org/html/rfc2830[]. |boolean |`ca` |Optional trusted certificate authority bundle to use when making requests to the server. If empty, the default system roots are used. |string |`groupUIDNameMapping` |Optional direct mapping of LDAP group UIDs to {product-title} group names. |object |`rfc2307` |Holds the configuration for extracting data from an LDAP server set up in a fashion similar to RFC2307: first-class group and user entries, with group membership determined by a multi-valued attribute on the group entry listing its members. |xref:sync-ldap-v1-rfc2307config[v1.RFC2307Config] |`activeDirectory` |Holds the configuration for extracting data from an LDAP server set up in a fashion similar to that used in Active Directory: first-class user entries, with group membership determined by a multi-valued attribute on members listing groups they are a member of. |xref:sync-ldap-v1-activedirectoryconfig[v1.ActiveDirectoryConfig] |`augmentedActiveDirectory` |Holds the configuration for extracting data from an LDAP server set up in a fashion similar to that used in Active Directory as described above, with one addition: first-class group entries exist and are used to hold metadata but not group membership. |xref:sync-ldap-v1-augmentedactivedirectoryconfig[v1.AugmentedActiveDirectoryConfig] |=== [[sync-ldap-v1-stringsource]] === v1.StringSource `StringSource` allows specifying a string inline, or externally via environment variable or file. When it contains only a string value, it marshals to a simple JSON string. [options=""header""] |=== |Name |Description |Schema |`value` |Specifies the cleartext value, or an encrypted value if `keyFile` is specified. |string |`env` |Specifies an environment variable containing the cleartext value, or an encrypted value if the `keyFile` is specified. |string |`file` |References a file containing the cleartext value, or an encrypted value if a `keyFile` is specified. |string |`keyFile` |References a file containing the key to use to decrypt the value. |string |=== [[sync-ldap-v1-ldapquery]] === v1.LDAPQuery `LDAPQuery` holds the options necessary to build an LDAP query. [options=""header""] |=== |Name |Description |Schema |`baseDN` |DN of the branch of the directory where all searches should start from. |string |`scope` |The (optional) scope of the search. Can be `base` (only the base object), `one` (all objects on the base level), `sub` (the entire subtree). Defaults to `sub` if not set. |string |`derefAliases` |The (optional) behavior of the search with regards to alisases. Can be `never` (never dereference aliases), `search` (only dereference in searching), `base` (only dereference in finding the base object), `always` (always dereference). Defaults to `always` if not set. |string |`timeout` |Holds the limit of time in seconds that any request to the server can remain outstanding before the wait for a response is given up. If this is `0`, no client-side limit is imposed. |integer |`filter` |A valid LDAP search filter that retrieves all relevant entries from the LDAP server with the base DN. |string |`pageSize` |Maximum preferred page size, measured in LDAP entries. A page size of `0` means no paging will be done. |integer |=== [[sync-ldap-v1-rfc2307config]] === v1.RFC2307Config `RFC2307Config` holds the necessary configuration options to define how an LDAP group sync interacts with an LDAP server using the RFC2307 schema. [options=""header""] |=== |Name |Description |Schema |`groupsQuery` |Holds the template for an LDAP query that returns group entries. |xref:sync-ldap-v1-ldapquery[v1.LDAPQuery] |`groupUIDAttribute` |Defines which attribute on an LDAP group entry will be interpreted as its unique identifier. (`ldapGroupUID`) |string |`groupNameAttributes` |Defines which attributes on an LDAP group entry will be interpreted as its name to use for an {product-title} group. |string array |`groupMembershipAttributes` |Defines which attributes on an LDAP group entry will be interpreted as its members. The values contained in those attributes must be queryable by your `UserUIDAttribute`. |string array |`usersQuery` |Holds the template for an LDAP query that returns user entries. |xref:sync-ldap-v1-ldapquery[v1.LDAPQuery] |`userUIDAttribute` |Defines which attribute on an LDAP user entry will be interpreted as its unique identifier. It must correspond to values that will be found from the `GroupMembershipAttributes`. |string |`userNameAttributes` |Defines which attributes on an LDAP user entry will be used, in order, as its {product-title} user name. The first attribute with a non-empty value is used. This should match your `PreferredUsername` setting for your `LDAPPasswordIdentityProvider`. The attribute to use as the name of the user in the {product-title} group record. `mail` or `sAMAccountName` are preferred choices in most installations. |string array |`tolerateMemberNotFoundErrors` |Determines the behavior of the LDAP sync job when missing user entries are encountered. If `true`, an LDAP query for users that does not find any will be tolerated and an only and error will be logged. If `false`, the LDAP sync job will fail if a query for users doesn't find any. The default value is 'false'. Misconfigured LDAP sync jobs with this flag set to 'true' can cause group membership to be removed, so it is recommended to use this flag with caution. |boolean |`tolerateMemberOutOfScopeErrors` |Determines the behavior of the LDAP sync job when out-of-scope user entries are encountered. If `true`, an LDAP query for a user that falls outside of the base DN given for the all user query will be tolerated and only an error will be logged. If `false`, the LDAP sync job will fail if a user query would search outside of the base DN specified by the all user query. Misconfigured LDAP sync jobs with this flag set to `true` can result in groups missing users, so it is recommended to use this flag with caution. |boolean |=== [[sync-ldap-v1-activedirectoryconfig]] === v1.ActiveDirectoryConfig `ActiveDirectoryConfig` holds the necessary configuration options to define how an LDAP group sync interacts with an LDAP server using the Active Directory schema. [options=""header""] |=== |Name |Description |Schema |`usersQuery` |Holds the template for an LDAP query that returns user entries. |xref:sync-ldap-v1-ldapquery[v1.LDAPQuery] |`userNameAttributes` |Defines which attributes on an LDAP user entry will be interpreted as its {product-title} user name. The attribute to use as the name of the user in the {product-title} group record. `mail` or `sAMAccountName` are preferred choices in most installations. |string array |`groupMembershipAttributes` |Defines which attributes on an LDAP user entry will be interpreted as the groups it is a member of. |string array |=== [[sync-ldap-v1-augmentedactivedirectoryconfig]] === v1.AugmentedActiveDirectoryConfig `AugmentedActiveDirectoryConfig` holds the necessary configuration options to define how an LDAP group sync interacts with an LDAP server using the augmented Active Directory schema. [options=""header""] |=== |Name |Description |Schema |`usersQuery` |Holds the template for an LDAP query that returns user entries. |xref:sync-ldap-v1-ldapquery[v1.LDAPQuery] |`userNameAttributes` |Defines which attributes on an LDAP user entry will be interpreted as its {product-title} user name. The attribute to use as the name of the user in the {product-title} group record. `mail` or `sAMAccountName` are preferred choices in most installations. |string array |`groupMembershipAttributes` |Defines which attributes on an LDAP user entry will be interpreted as the groups it is a member of. |string array |`groupsQuery` |Holds the template for an LDAP query that returns group entries. |xref:sync-ldap-v1-ldapquery[v1.LDAPQuery] |`groupUIDAttribute` |Defines which attribute on an LDAP group entry will be interpreted as its unique identifier. (`ldapGroupUID`) |string |`groupNameAttributes` |Defines which attributes on an LDAP group entry will be interpreted as its name to use for an {product-title} group. |string array |=== ",12054,True,2602.1515708421757,median "ifdef::env-github[] NOTE: Release notes are best read in our documentation at https://www.elastic.co/guide/en/apm/agent/python/current/release-notes.html[elastic.co] endif::[] //// [[release-notes-x.x.x]] ==== x.x.x - YYYY/MM/DD [float] ===== Breaking changes [float] ===== Features * Cool new feature: {pull}2526[#2526] [float] ===== Bug fixes //// //=== Unreleased // Unreleased changes go here // When the next release happens, nest these changes under the ""Python Agent version 6.x"" heading //[float] //===== Features // // //[float] //===== Bug fixes [[release-notes-6.x]] === Python Agent version 6.x [[release-notes-6.7.2]] === 6.7.2 - 2021-12-07 [float] ===== Bug fixes * fix AttributeError in sync instrumentation of httpx {pull}1423[#1423] * add setting to disable span compression, default to disabled {pull}1429[#1429] [[release-notes-6.7.1]] === 6.7.1 - 2021-11-29 [float] ===== Bug fixes * fix an issue with Sanic exception tracking {pull}1414[#1414] * asyncpg: Limit SQL queries in context data to 10000 characters {pull}1416[#1416] [[release-notes-6.7.0]] === 6.7.0 - 2021-11-17 [float] ===== Features * Add support for Sanic framework {pull}1390[#1390] [float] ===== Bug fixes * fix compatibility issues with httpx 0.21 {pull}1403[#1403] * fix `span_compression_exact_match_max_duration` default value {pull}1407[#1407] [[release-notes-6.6.3]] ==== 6.6.3 - 2021-11-15 [float] ===== Bug fixes * fix an issue with `metrics_sets` configuration referencing the `TransactionMetricSet` removed in 6.6.2 {pull}1397[#1397] [[release-notes-6.6.2]] ==== 6.6.2 - 2021-11-10 [float] ===== Bug fixes * Fix an issue where compressed spans would count against `transaction_max_spans` {pull}1377[#1377] * Make sure HTTP connections are not re-used after a process fork {pull}1374[#1374] * Fix an issue with psycopg2 instrumentation when multiple hosts are defined {pull}1386[#1386] * Update the `User-Agent` header to the new https://github.com/elastic/apm/pull/514[spec] {pull}1378[#1378] * Improve status_code handling in AWS Lambda integration {pull}1382[#1382] * Fix `aiohttp` exception handling to allow for non-500 responses including `HTTPOk` {pull}1384[#1384] * Force transaction names to strings {pull}1389[#1389] [float] ===== Other * Remove unused `http.request.socket.encrypted` context field {pull}1332[#1332] * Remove unused transaction metrics (APM Server handles these metrics instead) {pull}1388[#1388] [[release-notes-6.6.1]] ==== 6.6.1 - 2021-11-02 [float] ===== Bug fixes * Fix some context fields and metadata handling in AWS Lambda support {pull}1368[#1368] [[release-notes-6.6.0]] ==== 6.6.0 - 2021-10-18 [float] ===== Features * Add experimental support for AWS lambda instrumentation {pull}1193[#1193] * Add support for span compression {pull}1321[#1321] * Auto-infer destination resources for easier instrumentation of new resources {pull}1359[#1359] * Add support for dropped span statistics {pull}1327[#1327] [float] ===== Bug fixes * Ensure that Prometheus histograms are encoded correctly for APM Server {pull}1354[#1354] * Remove problematic (and duplicate) `event.dataset` from logging integrations {pull}1365[#1365] * Fix for memcache instrumentation when configured with a unix socket {pull}1357[#1357] [[release-notes-6.5.0]] ==== 6.5.0 - 2021-10-04 [float] ===== Features * Add instrumentation for Azure Storage (blob/table/fileshare) and Azure Queue {pull}1316[#1316] [float] ===== Bug fixes * Improve span coverage for `asyncpg` {pull}1328[#1328] * aiohttp: Correctly pass custom client to tracing middleware {pull}1345[#1345] * Fixed an issue with httpx instrumentation {pull}1337[#1337] * Fixed an issue with Django 4.0 removing a private method {pull}1347[#1347] [[release-notes-6.4.0]] ==== 6.4.0 - 2021-08-31 [float] ===== Features * Rename the experimental `log_ecs_formatting` config to `log_ecs_reformatting` {pull}1300[#1300] * Add support for Prometheus histograms {pull}1165[#1165] [float] ===== Bug fixes * Fixed cookie sanitization when Cookie is capitalized {pull}1301[#1301] * Fix a bug with exception capturing for bad UUIDs {pull}1304[#1304] * Fix potential errors in json serialization {pull}1203[#1203] * Fix an issue with certain aioredis commands {pull}1308[#1308] [[release-notes-6.3.3]] ==== 6.3.3 - 2021-07-14 [float] ===== Bug fixes * ensure that the elasticsearch instrumentation handles DroppedSpans correctly {pull}1190[#1190] [[release-notes-6.3.2]] ==== 6.3.2 - 2021-07-07 [float] ===== Bug fixes * Fix handling of non-http scopes in Starlette/FastAPI middleware {pull}1187[#1187] [[release-notes-6.3.1]] ==== 6.3.1 - 2021/07/07 [float] ===== Bug fixes * Fix issue with Starlette/FastAPI hanging on startup {pull}1185[#1185] [[release-notes-6.3.0]] ==== 6.3.0 - 2021/07/06 [float] ===== Features * Add additional context information about elasticsearch client requests {pull}1108[#1108] * Add `use_certifi` config option to allow users to disable `certifi` {pull}1163[#1163] [float] ===== Bug fixes * Fix for Starlette 0.15.0 error collection {pull}1174[#1174] * Fix for Starlette static files {pull}1137[#1137] [[release-notes-6.2.3]] ==== 6.2.3 - 2021/06/28 [float] ===== Bug fixes * suppress the default_app_config attribute in Django 3.2+ {pull}1155[#1155] * bump log level for multiple set_client calls to WARNING {pull}1164[#1164] * fix issue with adding disttracing to SQS messages when dropping spans {pull}1170[#1170] [[release-notes-6.2.2]] ==== 6.2.2 - 2021/06/07 [float] ===== Bug fixes * Fix an attribute access bug introduced in 6.2.0 {pull}1149[#1149] [[release-notes-6.2.1]] ==== 6.2.1 - 2021/06/03 [float] ===== Bug fixes * catch and log exceptions in interval timer threads {pull}1145[#1145] [[release-notes-6.2.0]] ==== 6.2.0 - 2021/05/31 [float] ===== Features * Added support for aioredis 1.x {pull}1082[#2526] * Added support for aiomysql {pull}1107[#1107] * Added Redis pub/sub instrumentation {pull}1129[#1129] * Added specific instrumentation for AWS SQS {pull}1123[#1123] [float] ===== Bug fixes * ensure metrics are flushed before agent shutdown {pull}1139[#1139] * added safeguard for exceptions in processors {pull}1138[#1138] * ensure sockets are closed which were opened for cloud environment detection {pull}1134[#1134] [[release-notes-6.1.3]] ==== 6.1.3 - 2021/04/28 [float] ===== Bug fixes * added destination information to asyncpg instrumentation {pull}1115[#1115] * fixed issue with collecting request meta data with Django REST Framework {pull}1117[#1117] * fixed httpx instrumentation for newly released httpx 0.18.0 {pull}1118[#1118] [[release-notes-6.1.2]] ==== 6.1.2 - 2021/04/14 [float] ===== Bug fixes * fixed issue with empty transaction name for the root route with Django {pull}1095[#1095] * fixed on-the-fly initialisation of Flask apps {pull}1099[#1099] [[release-notes-6.1.1]] ==== v6.1.1 - 2021/04/08 [float] ===== Bug fixes * fixed a validation issue with the newly introduced instrumentation for S3, SNS and DynamoDB {pull}1090[#1090] [[release-notes-6.1.0]] ==== v6.1.0 - 2021/03/31 [float] ===== Features * Add global access to Client singleton object at `elasticapm.get_client()` {pull}1043[#1043] * Add `log_ecs_formatting` config option {pull}1058[#1058] {pull}1063[#1063] * Add instrumentation for httplib2 {pull}1031[#1031] * Add better instrumentation for some AWS services (S3, SNS, DynamoDB) {pull}1054[#1054] * Added beta support for collecting metrics from prometheus_client {pull}1083[#1083] [float] ===== Bug fixes * Fix for potential `capture_body: error` hang in Starlette/FastAPI {pull}1038[#1038] * Fix a rare error around processing stack frames {pull}1012[#1012] * Fix for Starlette/FastAPI to correctly capture request bodies as strings {pull}1042[#1041] * Fix transaction names for Starlette Mount routes {pull}1037[#1037] * Fix for elastic excepthook arguments {pull}1050[#1050] * Fix issue with remote configuration when resetting config values {pull}1068[#1068] * Use a label for the elasticapm Django app that is compatible with Django 3.2 validation {pull}1064[#1064] * Fix an issue with undefined routes in Starlette {pull}1076[#1076] [[release-notes-6.0.0]] ==== v6.0.0 - 2021/02/01 [float] ===== Breaking changes * Python 2.7 and 3.5 support has been deprecated. The Python agent now requires Python 3.6+ {pull}1021[#1021] * No longer collecting body for `elasticsearch-py` `update` and `delete_by_query` {pull}1013[#1013] * Align `sanitize_field_names` config with the https://github.com/elastic/apm/blob/3fa78e2a1eeea81c73c2e16e96dbf6b2e79f3c64/specs/agents/sanitization.md[cross-agent spec]. If you are using a non-default `sanitize_field_names`, surrounding each of your entries with stars (e.g. `*secret*`) will retain the old behavior. {pull}982[#982] * Remove credit card sanitization for field values. This improves performance, and the security value of this check was dubious anyway. {pull}982[#982] * Remove HTTP querystring sanitization. This improves performance, and is meant to standardize behavior across the agents, as defined in https://github.com/elastic/apm/pull/334. {pull}982[#982] * Remove `elasticapm.tag()` (deprecated since 5.0.0) {pull}1034[#1034] [float] ===== Bug fixes * Fix for GraphQL span spamming from scalar fields with required flag {pull}1015[#1015] [[release-notes-5.x]] === Python Agent version 5.x [[release-notes-5.10.1]] ==== v5.10.1 - 2021/01/20 [float] ===== Bug fixes * Fix for custom serializers in elasticsearch-py {pull}998[#998] * Fix large query truncation in psycopg2 {pull}994[#994] * Fix memory metrics reporting when `memory.usage_in_bytes` is unavailable {pull}987[#987] * Fix for Starlette/FastAPI integration to properly obey `enabled` config {pull}1000[#1000] [[release-notes-5.10.0]] ==== v5.10.0 - 2020/11/18 [float] ===== Features * Implement ""sample_rate"" property for transactions and spans, and propagate through tracestate {pull}891[#891] * Add support for callbacks on config changes {pull}912[#912] * Override `sys.excepthook` to catch all exceptions {pull}943[#943] * Implement `log_level` config (supports central config) {pull}946[#946] * Implement `transaction_ignore_urls` config (supports central config) {pull}923[#923] * Add public API to retrieve trace parent header {pull}956[#956] * Added support for cgroup memory metrics {pull}846[#846] [float] ===== Bug fixes * Fix to collect the whole query body in `elasticsearch-py` {pull}940[#940] * Fix for GraphQL transaction naming {pull}881[#881] * Ensure that query string max length is maintained after sanitization {pull}968[#968] * Adapted kubernetes kubepod regex for detecting kubernetes metadata {pull}958[#958] * Updated Starlette integration to use the route as transaction name if possible {pull}957[#957] [[release-notes-5.9.0]] ==== v5.9.0 - 2020/09/23 [float] ===== Features * Add instrumentation support for https://github.com/encode/httpx[`httpx`] and https://github.com/encode/httpcore[`httpcore`] {pull}898[#898] * Implement ""outcome"" property for transactions and spans {pull}899[#899] * Add support for `asyncpg` {pull}889[#889] [float] ===== Bug fixes * Fix validation of config to properly require `required` config items. {pull}927[#927] [[release-notes-5.8.1]] ==== v5.8.1 - 2020/07/13 [float] ===== Bug fixes * Updated CLOUD_PROVIDER config to allow for new options defined in https://github.com/elastic/apm/issues/289[#289] {pull}878[#878] * Fixed a bug in AWS metadata collection on docker containers in AWS Elastic Beanstalk {pull}884[#884] * Fixed a bug in local variable serialization that could occur in multi-threaded applications {pull}885[#885] [[release-notes-5.8.0]] ==== v5.8.0 - 2020/06/30 [float] ===== Features * Added graphql (graphene) support {pull}850[#850] * Collect cloud provider metadata {pull}826[#826] * Added `sanitize_field_names` config {pull}860[#860] [float] ===== Bug fixes * Fix header fetching for ASGI implementations {pull}856[#856] [[release-notes-5.7.0]] ==== v5.7.0 - 2020/06/11 [float] ===== Features * capture number of affected rows for INSERT/UPDATE/DELETE SQL queries {pull}614[#614] * Added instrumentation for AsyncElasticsearch {pull}843[#843] [float] ===== Bug fixes * Added error handling around frame processing in Django {pull}837[#837] * Limit SQL queries in context data to 10000 characters {pull}842[#842] * Omit the ""sync"" property on spans by default {pull}854[#854] * Update the pid/ppid in transport metadata when they change {pull}825[#825] * Added better error handling around closing the transport {pull}838[#838] * Fixed an issue with the django admin command not detecting misconfigured server urls {pull}855[#855] [[release-notes-5.6.0]] ==== v5.6.0 - 2020/05/06 [float] ===== New features * Added SERVICE_NODE_NAME config {pull}592[#592] * Added instrumentation support for https://github.com/pinterest/pymemcache[`pymemcache`] {pull}812[#812] * Added new configuration options `enabled` and `recording` {pull}790[#790] [float] ===== Bug fixes * Fixed an issue with metrics collection raising RuntimeErrors {pull}802[#802] * Fixed an issue with getting extended destination data from pymongo {pull}797[#797] * Fixed an issue with Tornado instrumentation when Tornado isn't the ""main"" framework {pull}813[#813] * Fixed an issue with streaming requests being consumed by the agent even if capture_body is disabled {pull}817[#817] [float] ===== Pending Deprecations * Python 2.7 suppot will be dropped in version 6.0 of the agent. [[release-notes-5.5.2]] ==== v5.5.2 - 2020/03/20 [float] ===== Bug fixes * Fixed an issue with Redis using unix domain sockets and destination information {pull}766[#766] [[release-notes-5.5.1]] ==== v5.5.1 - 2020/03/19 [float] ===== Bug fixes * Fixed Starlette middleware when capturing request body while the content-type header is absent {pull}763[#763] [[release-notes-5.5.0]] ==== v5.5.0 - 2020/03/19 [float] ===== Features * Added destination information to database/HTTP spans, used for service maps {pull}618[#618] [float] ===== Deprecations * *Python 3.4 is no longer supported.* [[release-notes-5.4.3]] ==== v5.4.3 - 2020/02/27 https://github.com/elastic/apm-agent-python/compare/v5.4.2\\...v5.4.3[Check the diff] [float] ===== Bug fixes * fixed a bug in our aiohttp.client support if used with a yarl URL {pull}733[#733] [[release-notes-5.4.2]] ==== v5.4.2 - 2020/02/18 https://github.com/elastic/apm-agent-python/compare/v5.4.1\\...v5.4.2[Check the diff] [float] ===== Bug fixes * fixed a bug in our celery implementation related to the threading refactor in 5.4.0 {pull}724[#724] [[release-notes-5.4.1]] ==== v5.4.1 - 2020/02/18 https://github.com/elastic/apm-agent-python/compare/v5.4.0\\...v5.4.1[Check the diff] [float] ===== Bug fixes * fixed an issue with a DEBUG log message raising an error in some cases {pull}722[#722] [[release-notes-5.4.0]] ==== v5.4.0 - 2020/02/17 https://github.com/elastic/apm-agent-python/compare/v5.3.3\\...v5.4.0[Check the diff] [float] ===== Deprecations This will be the last minor release to support the following versions: * Python 3.4 * Django 1.8, 1.9 and 1.10 * Flask < 1.0 In addition, as of this release we only supported capturing extended information on Elasticsearch queries when using keyword arguments with the elasticsearch-py API. This is in keeping with the https://elasticsearch-py.readthedocs.io/en/master/api.html#api-documentation[upstream policy] of positional arguments being unsupported. {pull}697[#697] [float] ===== New Features * Refactored spawning of background threads {pull}636[#636] * Added support for aiohttp client and server {pull}659[#659] * Added support for tornado web framework {pull}661[#661] * Added support for starlette/fastapi {pull}694[#694] * Added support for W3C `traceparent` and `tracestate` headers {pull}660[#660] * Added Django 3.0 and Flask 1.1 to the support matrix {pull}667[#667] * Added support for aiopg {pull}668[#668] * Use Span ID as parent ID in errors if an error happens inside a span {pull}669[#669] * Added experimental support for API Key authentication {pull}679[#679] [float] ===== Bug fixes * introduced workaround to avoid instrumenting twice in rare cases {pull}708[#708] [[release-notes-5.3.3]] ==== v5.3.3 - 2020/01/14 https://github.com/elastic/apm-agent-python/compare/v5.3.2\\...v5.3.3[Check the diff] [float] ===== Bug fixes * Fixed an issue with OpenTracing bridge and dropped spans {pull}687[#687] * Fixed bug that would make the agent ignore the `hostname` configuration setting {pull}689[#689] [[release-notes-5.3.2]] ==== v5.3.2 - 2019/11/25 https://github.com/elastic/apm-agent-python/compare/v5.3.1\\...v5.3.2[Check the diff] [float] ===== Bug fixes * Added support for IPv6 address format when parsing urls {pull}649[#649] [[release-notes-5.3.1]] ==== v5.3.1 - 2019/11/18 https://github.com/elastic/apm-agent-python/compare/v5.3.0\\...v5.3.1[Check the diff] [float] ===== New Features * Added support for shortening dicts in local variables {pull}638[#638] [[release-notes-5.3.0]] ==== v5.3.0 - 2019/11/14 https://github.com/elastic/apm-agent-python/compare/v5.2.3\\...v5.3.0[Check the diff] [float] ===== New Features * Added instrumentation for mysql-connector and pymysql {pull}603[#603] * Implemented stack_trace_limit configuration option {pull}623[#623] * Autoinsert tracing middleware in django settings {pull}625[#625] [float] ===== Bug fixes * Fixed issue with transactions not being captured when errors occur in Flask {pull}635[#635] [[release-notes-5.2.3]] ==== v5.2.3 - 2019/11/13 https://github.com/elastic/apm-agent-python/compare/v5.2.2\\...v5.2.3[Check the diff] [float] ===== Bug fixes * Ensure that metrics with value 0 are not collected if they have the `reset_on_collect` flag set {pull}615[#615] * Unwrap postgres cursor for newly introduced psycopg2 extensions {pull}621[#621] * Fix pod ID for kubernetes when using the systemd cgroup driver {pull}631[#631] [[release-notes-5.2.2]] ==== v5.2.2 - 2019/10/16 https://github.com/elastic/apm-agent-python/compare/v5.2.1\\...v5.2.2[Check the diff] [float] ===== Bug fixes * Fixed an issue where a `cpu_total` of `0` could cause an exception {pull}610[#610], {pull}611[#611] [[release-notes-5.2.1]] ==== v5.2.1 - 2019/10/09 https://github.com/elastic/apm-agent-python/compare/v5.2.0\\...v5.2.1[Check the diff] [float] ===== Bug fixes * Fixed an issue with DroppedSpans and logging integration {pull}602[#602] * Fixed an issue with processors not being applied to chained exceptions {pull}604[#604] [[release-notes-5.2.0]] ==== v5.2.0 - 2019/10/02 https://github.com/elastic/apm-agent-python/compare/v5.1.2\\...v5.2.0[Check the diff] [float] ===== New Features * Added automatic tagging of LogRecord objects with transaction, trace, and span IDs via a LogRecordFactory (Python 3.2+) {pull}520[#520], {pull}586[#586] * Added `logging` filter and record factory for adding transaction, trace, and span IDs {pull}520[#520], {pull}586[#586] * Added `structlog` processor for adding transaction, trace, and span IDs {pull}520[#520], {pull}586[#586] * Added new public API calls for getting transaction, trace, and span IDs {pull}520[#520], {pull}586[#586] * Added support for chained exceptions in Python 3 {pull}596[#596]. Note that chained exceptions will be captured and stored in Elasticsearch, but not yet visualized in the APM UI. The UI component will be released in an upcoming Kibana release (7.5 or later). * Added support for using `structlog` for agent logging {pull}591[#591] [float] ===== Bug fixes * Drop events immediately if a processor returns a falsy value {pull}585[#585] [[release-notes-5.1.2]] ==== v5.1.2 - 2019/09/04 https://github.com/elastic/apm-agent-python/compare/v5.1.1\\...v5.1.2[Check the diff] [float] ===== Bugfixes * Fixed an issue with http server_url and `'VERIFY_SERVER_CERT': False` {pull}570[#570], {pull}578[#578] * Fixed instrumenting of psycopg2 when using their context manager interface {pull}577[#577], {pull}580[#580] * Fixed zerorpc tests {pull}581[#581] * Fixed to correctly check if gevent has patched threading.local {pull}579[#579] [[release-notes-5.1.1]] ==== v5.1.1 - 2019/08/22 https://github.com/elastic/apm-agent-python/compare/v5.1.0\\...v5.1.1[Check the diff] [float] ===== Bug fixes * Fixed an issue with empty responses from APM Server's config endpoint {pull}562[#562], {pull}563[#563] * Fixed Windows tests by avoiding time.sleep in breakdown metrics tests {pull}537[#537], {pull}550[#550] * Fixed container ID matching to match CloudFoundry Garden container IDs {pull}523[#523], {pull}564[#564] * Fixed an issue in the urllib instrumentation if no port is set {pull}567[#567] [float] ===== Other * Added Python 3.8 RC to the test matrix {pull}565[#565] [[release-notes-5.1.0]] ==== v5.1.0 - 2019/08/14 https://github.com/elastic/apm-agent-python/compare/v5.0.0\\...v5.1.0[Check the diff] [float] ===== Security issues * This release fixes CVE-2019-7617 [float] ===== New Features * Added support for global labels which will be applied to every transaction/error/metric {pull}549[#549] * Added support for `NO_PROXY` environment variable {pull}458[#458], {pull}551[#551] [float] ===== Bugfixes * Fixed an issue with using callables in set_context with unsampled transactions {pull}541[#541], {pull}542[#542] * Limited the length of error.culprit to 1024 characters {pull}491[#491], {pull}543[#543] * Fixed an issue with the `instrument` config option {pull}546[#546], {pull}547[#547] * Limited the amount of distinct metrics to 1000 {pull}540[#540], {pull}544[#544] [[release-notes-5.0.0]] ==== v5.0.0 - 2019/07/31 https://github.com/elastic/apm-agent-python/compare/v4.2.2\\...v5.0.0[Check the diff] [float] ===== Breaking changes * Implemented type/subtype/action hierachy for spans. Ensure that you run at least APM Server 6.6 {pull}377[#377] * renamed tags to labels and changed API. The old API remains for backwards compatibility until 6.0 of the agent {pull}538[#538] [float] ===== Other changes * Added support for recording breakdown metrics {pull}535[#535] * Added support for central config management {pull}511[#511] * Added instrumentation for `urllib2` (Python 2) / `urllib.request` (Python 3) {pull}464[#464] * Added `disable_metrics` setting {pull}399[#399] * Updated elasticsearch instrumentation for 7.x {pull}482[#482], {pull}483[#483] * Fixed an issue with opentracing-python 2.1 {pull}471[#471] * Fixed an issue with certificate pinning {pull}497[#497] * Lowered log level of transport success messages {pull}527[#527], {pull}531[#531] [[release-notes-4.x]] === Python Agent version 4.x [[release-notes-4.2.2]] ==== v4.2.2 - 2019/04/10 https://github.com/elastic/apm-agent-python/compare/v4.2.1\\...v4.2.2[Check the diff] * Fixed an issue with Celery and the prefork worker pool {pull}444[#444] * Fixed an issue when running uwsgi without a master process {pull}446[#446] * Fixed an issue with gevent/eventlet on Python 3.7 {pull}451[#451], {pull}454[#454] * Introduced `IntervalTimer` and use it instead of `threading.Timer` {pull}452[#452] * Added license header check as pre-commit hook {pull}456[#456] [[release-notes-4.2.1]] ==== v4.2.1 - 2019/03/22 https://github.com/elastic/apm-agent-python/compare/v4.2.0\\...v4.2.1[Check the diff] * Fixed an issue with the certificate pinning feature introduced in 4.2.0 {pull}433[#433], {pull}434[#434] * Fixed incompatibility with eventlet introduced in 4.2.0 {pull}435[#435], {pull}436[#436] [[release-notes-4.2.0]] ==== v4.2.0 - 2019/03/20 https://github.com/elastic/apm-agent-python/compare/v4.1.0\\...v4.2.0[Check the diff] * Implemented a new transport queue, which should avoid certain deadlock scenarios {pull}411[#411] * Implemented server certificate pinning {pull}405[#405] * Moved context.url to context.http.url for requests/urllib3 spans {pull}393[#393], {pull}394[#394] * Added support for using route as transaction name in Django 2.2+ {pull}86[#86], {pull}396[#396] * Added some randomness to time between requests to APM Server {pull}426[#426] * Fixed an issue with custom user models in Django using non-string usernames {pull}397[#397], {pull}398[#398] * Fixed an issue with sending kubernetes metadata to the API {pull}401[#401], {pull}402[#402] * Fixed an issue with parsing /proc/stat in RHEL/centos 6 {pull}406[#406], {pull}407[#407] * Added copyright header to all files, and a CI check {pull}429[#429] [[release-notes-4.1.0]] ==== v4.1.0 - 2019/01/29 https://github.com/elastic/apm-agent-python/compare/v4.0.3\\...v4.1.0[Check the diff] * Added support for collecting system and process metrics {pull}361[#361] * Added an OpenTracing bridge {pull}388[#388] * Added `transaction.sampled` to errors {pull}371[#371] * Added `transaction.type` to errors {pull}391[#391] * Added parsing of `/proc/self/cgroup` to capture container meta data {pull}352[#352] * Added option to configure logging for Flask using a log level {pull}344[#344] * Added `capture_headers` config option {pull}392[#392] [[release-notes-4.0.3]] ==== v4.0.3 - 2018/12/24 https://github.com/elastic/apm-agent-python/compare/v4.0.2\\...v4.0.3[Check the diff] * Implemented de-dotting of tag names and context keys {pull}353[#353] * wrote a quickfix for the boto3/botocore instrumentation {pull}367[#367] * Fixed an issue with psycopg2 and encoded strings {pull}366[#366] [[release-notes-4.0.2]] ==== v4.0.2 - 2018/12/05 https://github.com/elastic/apm-agent-python/compare/v4.0.1\\...v4.0.2[Check the diff] * Fixed another issue in the new v2 transport {pull}351[#351] [[release-notes-4.0.1]] ==== v4.0.1 - 2018/11/16 https://github.com/elastic/apm-agent-python/compare/v4.0.0\\...v4.0.1[Check the diff] * Fixed an issue with instrumenting redis-py 3.0+ * Fixed a multithreading issue that occurs when using threaded workers {pull}335[#335] [[release-notes-4.0.0]] ==== v4.0.0 - 2018/11/14 https://github.com/elastic/apm-agent-python/compare/v3.0.2\\...v4.0.0[Check the diff] **BREAKING** Version 4 of the agent implements a new wire protocol for communicating with the APM Server. This format is only supported in *APM Server 6.5+*. Further breaking changes: * The undocumented `AsyncioHTTPTransport` has been removed. * The `flush_interval` and `max_queue_size` settings have been removed. * new settings introduced: `api_request_time` and `api_request_size`. * Some settings now require a unit for duration or size. See documentation on configuration for more information. * The option to provide a custom date for exceptions and messages has been removed. Other changes: * on Python 3.7, use https://docs.python.org/3/library/contextvars.html[contextvars] instead of threadlocals for storing current transaction and span. This is a necessary precursor for full asyncio support. {pull}291[#291] [[release-notes-3.x]] === Python Agent version 3.x [[release-notes-3.0.2]] ==== v3.0.2 - 2018/10/17 https://github.com/elastic/apm-agent-python/compare/v3.0.1\\...v3.0.2[Check the diff] * Fixed an issue with detecting names of wrapped functions that are partials {pull}294[#294] * Fixed a bug in Flask instrumentation that could appear together with FlaskAPI {pull}286[#286] [[release-notes-3.0.1]] ==== v3.0.1 - 2018/08/30 https://github.com/elastic/apm-agent-python/compare/v3.0.0\\...v3.0.1[Check the diff] * Added sanitization for `Set-Cookie` response headers {pull}264[#264] * Added instrumentation for the non-standard `Connection.execute()` method for SQLite3 {pull}271[#271] * Added ""authorization"" to list of sensitive keywords, to ensure that ""Authorization"" HTTP headers are properly sanitized {pull}275[#275] * Taught the Logbook handler how to handle the `stack=False` option {pull}278[#278] * Fixed a race condition with managing the timer-send thread {pull}279[#279] [[release-notes-3.0.0]] ==== v3.0.0 - 2018/07/20 https://github.com/elastic/apm-agent-python/compare/v2.2.1\\...v3.0.0[Check the diff] - adapted ""black"" code formatter for this repository {pull}262[#262] - **BREAKING**: dropped support for Python 3.3 {pull}242[#242] - **BREAKING**: changed order of precedence when evaluating configuration {pull}255[#255], {pull}261[#261] - **BREAKING**: changed default value of `span_frames_min_duration` setting from `-1` (always collect) to `5` (only collect for spans longer than 5 ms) {pull}243[#243] - added instrumentation for pymssql {pull}241[#241] - added instrumentation for pyodbc {pull}238[#238] [[release-notes-2.x]] === Python Agent version 2.x [[release-notes-2.2.1]] ==== v2.2.1 - 2018/06/13 https://github.com/elastic/apm-agent-python/compare/v2.2.0\\...v2.2.1[Check the diff] - fixed an issue with Django Channels {pull}232[#232], {pull}233[#233] [[release-notes-2.2.0]] ==== v2.2.0 - 2018/06/13 https://github.com/elastic/apm-agent-python/compare/v2.1.1\\...v2.2.0[Check the diff] - introduced consistent logger name scheme for all elasticapm internal log messages {pull}212[#212] - added instrumentation of cassandra-driver {pull}205[#205] - added instrumentation of elasticsearch-py {pull}191[#191] - added Flask 1.0 to the test matrix {pull}207[#207] - fixed an issue with our minimalistic SQL parser and ""fully qualified"" table names {pull}206[#206] - fixed issue with spans in Django’s `StreamingHTTPResponse` not being captured {pull}201[#201], {pull}202[#202] - fixed issue with spans with Flask’s streaming response not being captured {pull}201[#201], {pull}202[#202] **NOTE**: This will be the last release with support for Python 3.3. [[release-notes-2.1.1]] ==== v2.1.1 - 2018/04/09 https://github.com/elastic/apm-agent-python/compare/v2.1.0\\...v2.1.1[Check the diff] - fixed bug in Django management command that would be triggered on Django 1.10 or 1.11 while using the `MIDDLEWARE_CLASSES` setting {pull}186[#186], {pull}187[#187] - fix an encoding issue with log messages that are hit in rare cases {pull}188[#188], {pull}189[#189] [[release-notes-2.1.0]] ==== v2.1.0 - 2018/03/19 https://github.com/elastic/apm-agent-python/compare/v2.0.1\\...v2.1.0[Check the diff] - made skipping of initial `elasticapm` frames for span stack traces more generic {pull}167[#167] - added `context.process.ppid` field (supported in apm-server 6.3+) {pull}168[#168] - added option to disable stack frame collection for very short spans {pull}142[#142] - several bug fixes: - fix an issue in boto3 instrumentation with nonstandard endpoint URLs {pull}178[#178] - fix bug with OPTIONS requests and body capturing {pull}174[#174] - fix issue when message has `%` character, but no params {pull}175[#175] [[release-notes-2.0.1]] ==== v2.0.1 - 2018/02/15 https://github.com/elastic/apm-agent-python/compare/v2.0.0\\...v2.0.1[Check the diff] - fixed compatibility issue with aiohttp 3.0 {pull}157[#157] - Added truncation for fields that have a `maxLength` in the JSON Schema {pull}159[#159] [[release-notes-2.0.0]] ==== v2.0.0 - 2018/02/06 https://github.com/elastic/apm-agent-python/compare/v1.0.0\\...v2.0.0[Check the diff] - moved the library-frame detection from a processor to the stacktrace collection {pull}113[#113]. - added settings to enable/disable source code collection and local variables collection for errors and transactions {pull}117[#117] - added `service.environment` to provide an environment name (e.g. ""production"", ""staging"") {pull}123[#123] - added `transaction.id` to errors to better correlate errors with transactions {pull}122[#122] - added `transaction_sample_rate` to define a rate with which transactions are sampled {pull}116[#116] - added `error.handled` to indicate if an exception was handled or not {pull}124[#124]. - added `transaction_max_spans` setting to limit the amount of spans that are recorded per transaction {pull}127[#127] - added configuration options to limit captured local variables to a certain length {pull}130[#130] - added options for configuring the amount of context lines that are captured with each frame {pull}136[#136] - added support for tracing queries formatted as http://initd.org/psycopg/docs/sql.html[`psycopg2.sql.SQL`] objects {pull}148[#148] - switched to `time.perf_counter` as timing function on Python 3 {pull}138[#138] - added option to disable capturing of request body {pull}151[#151] - BREAKING: Several settings and APIs have been renamed (#111, #119, #143): - The decorator for custom instrumentation, `elasticapm.trace`, is now `elasticapm.capture_span` - The setting `traces_send_frequency` has been renamed to `flush_interval`. The name of the analogous environment variable changed from `ELASTIC_APM_TRACES_SEND_FREQ` to `ELASTIC_APM_FLUSH_INTERVAL` - The `app_name` setting has been renamed to `service_name`. The name of the analogous environment variable changed from `ELASTIC_APM_APP_NAME` to `ELASTIC_APM_SERVICE_NAME`. - `app_name` arguments to API calls in the whole code base changed to `service_name`. - The `app_version` setting has been renamed to `service_version`. The name of the analogous environment variable changed from `ELASTIC_APM_APP_VERSION` to `ELASTIC_APM_SERVICE_VERSION`. - `context.request.url.raw` has been renamed to `context.request.url.full` {pull}121[#121] - BREAKING: added `elasticapm.set_custom_context` in favor of the more generic `set_custom_data` function {pull}133[#133] - BREAKING: `include_patterns` and `exclude_patterns` now use shell globs instead of regular expressions, and are matched against the full path file path of the module, not against the module name {pull}137[#137] - BREAKING: renamed several configuration options to align better with other language agents {pull}145[#145]: - `disable_instrumentation` became `instrument` and inverted its meaning - `max_event_queue_length` became `max_queue_size` - `timeout` became `server_timeout` [[release-notes-1.x]] === Python Agent version 1.x [[release-notes-1.0.0]] ==== v1.0.0 - 2017/12/11 https://github.com/elastic/apm-agent-python/compare/v1.0.0.dev3\\...v1.0.0[Check the diff] - added `max-event-queue-length` setting. {pull}67[#67] - changed name that the agent reports itself with to the APM server from `elasticapm-python` to `python`. This aligns the Python agent with other languages. {pull}104[#104] - changed Celery integration to store the task state (e.g. `SUCCESS` or `FAILURE`) in `transaction.result` {pull}100[#100] - added setting to disable SSL certificate verification {pull}108[#108] - BREAKING: renamed `server` configuration variable to `server_url` to better align with other language agents {pull}105[#105] - BREAKING: removed the old and unused urllib2-based HTTP transport, and renamed the urllib3 transport {pull}107[#107] - BREAKING: several API changes to `capture_exception`, `capture_message`, and added documentation for these and other APIs {pull}112[#112] [[release-notes-1.0.0-dev3]] ==== v1.0.0.dev3 - 2017/11/13 https://github.com/elastic/apm-agent-python/compare/v1.0.0.dev2\\...v1.0.0.dev2[Check the diff] - added a background thread to process the transactions queue every 60 seconds (configurable) {pull}68[#68] - adapted trace context for SQL traces to new API {pull}77[#77] - ensured that transaction data is also passed through processors {pull}84[#84] - added `uninstrument` function to reverse instrumentation, and exposed both `instrument` and `uninstrument` as public API in the `elasticapm` namespace {pull}90[#90] - added normalization of HTTP status codes into classes for the `transaction.result` field. A HTTP status of `200` will be turned into `HTTP 2xx`. The unchanged status code is still available in `context.response.status_code`. {pull}85[#85] [[release-notes-1.0.0-dev2]] ==== v1.0.0.dev2 - 2017/09/29 https://github.com/elastic/apm-agent-python/compare/v1.0.0.dev1\\...v1.0.0.dev2[Check the diff] - added request context information for Flask {pull}58[#58] - added response context information for Flask {pull}65[#65] - BREAKING: changed the `SERVERS` list setting to a single `SERVER` string setting. With this change, we now only support sending events to a single server {pull}59[#59] - BREAKING: removed root trace. Due to historical reason, we used to create a ""root trace"" which was equivalent to the transaction. This is no longer necessary. #61 [[release-notes-1.0.0-dev1]] ==== v1.0.0.dev1 - 2017/09/18 https://github.com/elastic/apm-agent-python/compare/v1.0.0.dev0\\...v1.0.0.dev1[Check the diff] - unified configuration across supported frameworks {pull}33[#33] - added in-app frame detection {pull}36[#36] - added tagging functionality {pull}28[#28] - preliminary support for Django 2.0 {pull}26[#26] - initial set of documentation [[release-notes-1.0.0-dev0]] ==== v1.0.0.dev0 - 2017/08/17 First release of the Python agent for Elastic APM ",12176,True,2778.9583113563654,median "/* * Copyright (c) 2019, The OpenThread Authors. * 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. */ #if __ORDER_BIG_ENDIAN__ #define BYTE_ORDER_BIG_ENDIAN 1 #endif #define OTBR_LOG_TAG ""UBUS"" #include ""openwrt/ubus/otubus.hpp"" #include #include #include #include #include #include #include ""common/logging.hpp"" #include ""ncp/ncp_openthread.hpp"" namespace otbr { namespace ubus { static UbusServer *sUbusServerInstance = nullptr; static int sUbusEfd = -1; static void * sJsonUri = nullptr; static int sBufNum; const static int PANID_LENGTH = 10; const static int XPANID_LENGTH = 64; const static int NETWORKKEY_LENGTH = 64; UbusServer::UbusServer(Ncp::ControllerOpenThread *aController, std::mutex *aMutex) : mIfFinishScan(false) , mContext(nullptr) , mSockPath(nullptr) , mController(aController) , mNcpThreadMutex(aMutex) , mSecond(0) { memset(&mNetworkdataBuf, 0, sizeof(mNetworkdataBuf)); memset(&mBuf, 0, sizeof(mBuf)); blob_buf_init(&mBuf, 0); blob_buf_init(&mNetworkdataBuf, 0); } UbusServer &UbusServer::GetInstance(void) { return *sUbusServerInstance; } void UbusServer::Initialize(Ncp::ControllerOpenThread *aController, std::mutex *aMutex) { sUbusServerInstance = new UbusServer(aController, aMutex); } enum { SETNETWORK, SET_NETWORK_MAX, }; enum { PSKD, EUI64, ADD_JOINER_MAX, }; enum { NETWORKKEY, NETWORKNAME, EXTPANID, PANID, CHANNEL, PSKC, MGMTSET_MAX, }; static const struct blobmsg_policy setNetworknamePolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""networkname"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy setPanIdPolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""panid"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy setExtPanIdPolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""extpanid"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy setChannelPolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""channel"", .type = BLOBMSG_TYPE_INT32}, }; static const struct blobmsg_policy setPskcPolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""pskc"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy setNetworkkeyPolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""networkkey"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy setModePolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""mode"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy macfilterAddPolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""addr"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy macfilterRemovePolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""addr"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy macfilterSetStatePolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""state"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy removeJoinerPolicy[SET_NETWORK_MAX] = { [SETNETWORK] = {.name = ""eui64"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy addJoinerPolicy[ADD_JOINER_MAX] = { [PSKD] = {.name = ""pskd"", .type = BLOBMSG_TYPE_STRING}, [EUI64] = {.name = ""eui64"", .type = BLOBMSG_TYPE_STRING}, }; static const struct blobmsg_policy mgmtsetPolicy[MGMTSET_MAX] = { [NETWORKKEY] = {.name = ""networkkey"", .type = BLOBMSG_TYPE_STRING}, [NETWORKNAME] = {.name = ""networkname"", .type = BLOBMSG_TYPE_STRING}, [EXTPANID] = {.name = ""extpanid"", .type = BLOBMSG_TYPE_STRING}, [PANID] = {.name = ""panid"", .type = BLOBMSG_TYPE_STRING}, [CHANNEL] = {.name = ""channel"", .type = BLOBMSG_TYPE_STRING}, [PSKC] = {.name = ""pskc"", .type = BLOBMSG_TYPE_STRING}, }; static const struct ubus_method otbrMethods[] = { {""scan"", &UbusServer::UbusScanHandler, 0, 0, nullptr, 0}, {""channel"", &UbusServer::UbusChannelHandler, 0, 0, nullptr, 0}, {""setchannel"", &UbusServer::UbusSetChannelHandler, 0, 0, setChannelPolicy, ARRAY_SIZE(setChannelPolicy)}, {""networkname"", &UbusServer::UbusNetworknameHandler, 0, 0, nullptr, 0}, {""setnetworkname"", &UbusServer::UbusSetNetworknameHandler, 0, 0, setNetworknamePolicy, ARRAY_SIZE(setNetworknamePolicy)}, {""state"", &UbusServer::UbusStateHandler, 0, 0, nullptr, 0}, {""panid"", &UbusServer::UbusPanIdHandler, 0, 0, nullptr, 0}, {""setpanid"", &UbusServer::UbusSetPanIdHandler, 0, 0, setPanIdPolicy, ARRAY_SIZE(setPanIdPolicy)}, {""rloc16"", &UbusServer::UbusRloc16Handler, 0, 0, nullptr, 0}, {""extpanid"", &UbusServer::UbusExtPanIdHandler, 0, 0, nullptr, 0}, {""setextpanid"", &UbusServer::UbusSetExtPanIdHandler, 0, 0, setExtPanIdPolicy, ARRAY_SIZE(setExtPanIdPolicy)}, {""networkkey"", &UbusServer::UbusNetworkkeyHandler, 0, 0, nullptr, 0}, {""setnetworkkey"", &UbusServer::UbusSetNetworkkeyHandler, 0, 0, setNetworkkeyPolicy, ARRAY_SIZE(setNetworkkeyPolicy)}, {""pskc"", &UbusServer::UbusPskcHandler, 0, 0, nullptr, 0}, {""setpskc"", &UbusServer::UbusSetPskcHandler, 0, 0, setPskcPolicy, ARRAY_SIZE(setPskcPolicy)}, {""threadstart"", &UbusServer::UbusThreadStartHandler, 0, 0, nullptr, 0}, {""threadstop"", &UbusServer::UbusThreadStopHandler, 0, 0, nullptr, 0}, {""neighbor"", &UbusServer::UbusNeighborHandler, 0, 0, nullptr, 0}, {""parent"", &UbusServer::UbusParentHandler, 0, 0, nullptr, 0}, {""mode"", &UbusServer::UbusModeHandler, 0, 0, nullptr, 0}, {""setmode"", &UbusServer::UbusSetModeHandler, 0, 0, setModePolicy, ARRAY_SIZE(setModePolicy)}, {""partitionid"", &UbusServer::UbusPartitionIdHandler, 0, 0, nullptr, 0}, {""leave"", &UbusServer::UbusLeaveHandler, 0, 0, nullptr, 0}, {""leaderdata"", &UbusServer::UbusLeaderdataHandler, 0, 0, nullptr, 0}, {""networkdata"", &UbusServer::UbusNetworkdataHandler, 0, 0, nullptr, 0}, {""commissionerstart"", &UbusServer::UbusCommissionerStartHandler, 0, 0, nullptr, 0}, {""joinernum"", &UbusServer::UbusJoinerNumHandler, 0, 0, nullptr, 0}, {""joinerremove"", &UbusServer::UbusJoinerRemoveHandler, 0, 0, nullptr, 0}, {""macfiltersetstate"", &UbusServer::UbusMacfilterSetStateHandler, 0, 0, macfilterSetStatePolicy, ARRAY_SIZE(macfilterSetStatePolicy)}, {""macfilteradd"", &UbusServer::UbusMacfilterAddHandler, 0, 0, macfilterAddPolicy, ARRAY_SIZE(macfilterAddPolicy)}, {""macfilterremove"", &UbusServer::UbusMacfilterRemoveHandler, 0, 0, macfilterRemovePolicy, ARRAY_SIZE(macfilterRemovePolicy)}, {""macfilterclear"", &UbusServer::UbusMacfilterClearHandler, 0, 0, nullptr, 0}, {""macfilterstate"", &UbusServer::UbusMacfilterStateHandler, 0, 0, nullptr, 0}, {""macfilteraddr"", &UbusServer::UbusMacfilterAddrHandler, 0, 0, nullptr, 0}, {""joineradd"", &UbusServer::UbusJoinerAddHandler, 0, 0, addJoinerPolicy, ARRAY_SIZE(addJoinerPolicy)}, {""mgmtset"", &UbusServer::UbusMgmtsetHandler, 0, 0, mgmtsetPolicy, ARRAY_SIZE(mgmtsetPolicy)}, }; static struct ubus_object_type otbrObjType = {""otbr_prog"", 0, otbrMethods, ARRAY_SIZE(otbrMethods)}; static struct ubus_object otbr = { avl : {}, name : ""otbr"", id : 0, path : nullptr, type : &otbrObjType, subscribe_cb : nullptr, has_subscribers : false, methods : otbrMethods, n_methods : ARRAY_SIZE(otbrMethods), }; void UbusServer::ProcessScan(void) { otError error = OT_ERROR_NONE; uint32_t scanChannels = 0; uint16_t scanDuration = 0; mNcpThreadMutex->lock(); SuccessOrExit(error = otLinkActiveScan(mController->GetInstance(), scanChannels, scanDuration, &UbusServer::HandleActiveScanResult, this)); exit: mNcpThreadMutex->unlock(); return; } void UbusServer::HandleActiveScanResult(otActiveScanResult *aResult, void *aContext) { static_cast(aContext)->HandleActiveScanResultDetail(aResult); } void UbusServer::OutputBytes(const uint8_t *aBytes, uint8_t aLength, char *aOutput) { char byte2char[5] = """"; for (int i = 0; i < aLength; i++) { sprintf(byte2char, ""%02x"", aBytes[i]); strcat(aOutput, byte2char); } } void UbusServer::AppendResult(otError aError, struct ubus_context *aContext, struct ubus_request_data *aRequest) { blobmsg_add_u16(&mBuf, ""Error"", aError); ubus_send_reply(aContext, aRequest, mBuf.head); } void UbusServer::HandleActiveScanResultDetail(otActiveScanResult *aResult) { void *jsonList = nullptr; char panidstring[PANID_LENGTH]; char xpanidstring[XPANID_LENGTH] = """"; if (aResult == nullptr) { blobmsg_close_array(&mBuf, sJsonUri); mIfFinishScan = true; goto exit; } jsonList = blobmsg_open_table(&mBuf, nullptr); blobmsg_add_string(&mBuf, ""NetworkName"", aResult->mNetworkName.m8); OutputBytes(aResult->mExtendedPanId.m8, OT_EXT_PAN_ID_SIZE, xpanidstring); blobmsg_add_string(&mBuf, ""ExtendedPanId"", xpanidstring); sprintf(panidstring, ""0x%04x"", aResult->mPanId); blobmsg_add_string(&mBuf, ""PanId"", panidstring); blobmsg_add_u32(&mBuf, ""Channel"", aResult->mChannel); blobmsg_add_u32(&mBuf, ""Rssi"", aResult->mRssi); blobmsg_add_u32(&mBuf, ""Lqi"", aResult->mLqi); blobmsg_close_table(&mBuf, jsonList); exit: return; } int UbusServer::UbusScanHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusScanHandlerDetail(aContext, aObj, aRequest, aMethod, aMsg); } int UbusServer::UbusScanHandlerDetail(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; uint64_t eventNum; ssize_t retval; blob_buf_init(&mBuf, 0); sJsonUri = blobmsg_open_array(&mBuf, ""scan_list""); mIfFinishScan = 0; sUbusServerInstance->ProcessScan(); eventNum = 1; retval = write(sUbusEfd, &eventNum, sizeof(uint64_t)); if (retval != sizeof(uint64_t)) { error = OT_ERROR_FAILED; goto exit; } while (!mIfFinishScan) { sleep(1); } exit: AppendResult(error, aContext, aRequest); return 0; } int UbusServer::UbusChannelHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""channel""); } int UbusServer::UbusSetChannelHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""channel""); } int UbusServer::UbusJoinerNumHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""joinernum""); } int UbusServer::UbusNetworknameHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""networkname""); } int UbusServer::UbusSetNetworknameHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""networkname""); } int UbusServer::UbusStateHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""state""); } int UbusServer::UbusRloc16Handler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""rloc16""); } int UbusServer::UbusPanIdHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""panid""); } int UbusServer::UbusSetPanIdHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""panid""); } int UbusServer::UbusExtPanIdHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""extpanid""); } int UbusServer::UbusSetExtPanIdHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""extpanid""); } int UbusServer::UbusPskcHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""pskc""); } int UbusServer::UbusSetPskcHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""pskc""); } int UbusServer::UbusNetworkkeyHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""networkkey""); } int UbusServer::UbusSetNetworkkeyHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""networkkey""); } int UbusServer::UbusThreadStartHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusThreadHandler(aContext, aObj, aRequest, aMethod, aMsg, ""start""); } int UbusServer::UbusThreadStopHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusThreadHandler(aContext, aObj, aRequest, aMethod, aMsg, ""stop""); } int UbusServer::UbusParentHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusParentHandlerDetail(aContext, aObj, aRequest, aMethod, aMsg); } int UbusServer::UbusNeighborHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusNeighborHandlerDetail(aContext, aObj, aRequest, aMethod, aMsg); } int UbusServer::UbusModeHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""mode""); } int UbusServer::UbusSetModeHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""mode""); } int UbusServer::UbusPartitionIdHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""partitionid""); } int UbusServer::UbusLeaveHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusLeaveHandlerDetail(aContext, aObj, aRequest, aMethod, aMsg); } int UbusServer::UbusLeaderdataHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""leaderdata""); } int UbusServer::UbusNetworkdataHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""networkdata""); } int UbusServer::UbusCommissionerStartHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusCommissioner(aContext, aObj, aRequest, aMethod, aMsg, ""start""); } int UbusServer::UbusJoinerRemoveHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusCommissioner(aContext, aObj, aRequest, aMethod, aMsg, ""joinerremove""); } int UbusServer::UbusMgmtsetHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusMgmtset(aContext, aObj, aRequest, aMethod, aMsg); } int UbusServer::UbusJoinerAddHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusCommissioner(aContext, aObj, aRequest, aMethod, aMsg, ""joineradd""); } int UbusServer::UbusMacfilterAddrHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""macfilteraddr""); } int UbusServer::UbusMacfilterStateHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusGetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""macfilterstate""); } int UbusServer::UbusMacfilterAddHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""macfilteradd""); } int UbusServer::UbusMacfilterRemoveHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""macfilterremove""); } int UbusServer::UbusMacfilterSetStateHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""macfiltersetstate""); } int UbusServer::UbusMacfilterClearHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { return GetInstance().UbusSetInformation(aContext, aObj, aRequest, aMethod, aMsg, ""macfilterclear""); } int UbusServer::UbusLeaveHandlerDetail(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; uint64_t eventNum; ssize_t retval; mNcpThreadMutex->lock(); otInstanceFactoryReset(mController->GetInstance()); eventNum = 1; retval = write(sUbusEfd, &eventNum, sizeof(uint64_t)); if (retval != sizeof(uint64_t)) { error = OT_ERROR_FAILED; goto exit; } blob_buf_init(&mBuf, 0); exit: mNcpThreadMutex->unlock(); AppendResult(error, aContext, aRequest); return 0; } int UbusServer::UbusThreadHandler(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg, const char * aAction) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; blob_buf_init(&mBuf, 0); if (!strcmp(aAction, ""start"")) { mNcpThreadMutex->lock(); SuccessOrExit(error = otIp6SetEnabled(mController->GetInstance(), true)); SuccessOrExit(error = otThreadSetEnabled(mController->GetInstance(), true)); } else if (!strcmp(aAction, ""stop"")) { mNcpThreadMutex->lock(); SuccessOrExit(error = otThreadSetEnabled(mController->GetInstance(), false)); SuccessOrExit(error = otIp6SetEnabled(mController->GetInstance(), false)); } exit: mNcpThreadMutex->unlock(); AppendResult(error, aContext, aRequest); return 0; } int UbusServer::UbusParentHandlerDetail(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; otRouterInfo parentInfo; char extAddress[XPANID_LENGTH] = """"; char transfer[XPANID_LENGTH] = """"; void * jsonList = nullptr; void * jsonArray = nullptr; blob_buf_init(&mBuf, 0); mNcpThreadMutex->lock(); SuccessOrExit(error = otThreadGetParentInfo(mController->GetInstance(), &parentInfo)); jsonArray = blobmsg_open_array(&mBuf, ""parent_list""); jsonList = blobmsg_open_table(&mBuf, ""parent""); blobmsg_add_string(&mBuf, ""Role"", ""R""); sprintf(transfer, ""0x%04x"", parentInfo.mRloc16); blobmsg_add_string(&mBuf, ""Rloc16"", transfer); sprintf(transfer, ""%3d"", parentInfo.mAge); blobmsg_add_string(&mBuf, ""Age"", transfer); OutputBytes(parentInfo.mExtAddress.m8, sizeof(parentInfo.mExtAddress.m8), extAddress); blobmsg_add_string(&mBuf, ""ExtAddress"", extAddress); blobmsg_add_u16(&mBuf, ""LinkQualityIn"", parentInfo.mLinkQualityIn); blobmsg_close_table(&mBuf, jsonList); blobmsg_close_array(&mBuf, jsonArray); exit: mNcpThreadMutex->unlock(); AppendResult(error, aContext, aRequest); return error; } int UbusServer::UbusNeighborHandlerDetail(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; otNeighborInfo neighborInfo; otNeighborInfoIterator iterator = OT_NEIGHBOR_INFO_ITERATOR_INIT; char transfer[XPANID_LENGTH] = """"; void * jsonList = nullptr; char mode[5] = """"; char extAddress[XPANID_LENGTH] = """"; blob_buf_init(&mBuf, 0); sJsonUri = blobmsg_open_array(&mBuf, ""neighbor_list""); mNcpThreadMutex->lock(); while (otThreadGetNextNeighborInfo(mController->GetInstance(), &iterator, &neighborInfo) == OT_ERROR_NONE) { jsonList = blobmsg_open_table(&mBuf, nullptr); blobmsg_add_string(&mBuf, ""Role"", neighborInfo.mIsChild ? ""C"" : ""R""); sprintf(transfer, ""0x%04x"", neighborInfo.mRloc16); blobmsg_add_string(&mBuf, ""Rloc16"", transfer); sprintf(transfer, ""%3d"", neighborInfo.mAge); blobmsg_add_string(&mBuf, ""Age"", transfer); sprintf(transfer, ""%8d"", neighborInfo.mAverageRssi); blobmsg_add_string(&mBuf, ""AvgRssi"", transfer); sprintf(transfer, ""%9d"", neighborInfo.mLastRssi); blobmsg_add_string(&mBuf, ""LastRssi"", transfer); if (neighborInfo.mRxOnWhenIdle) { strcat(mode, ""r""); } if (neighborInfo.mFullThreadDevice) { strcat(mode, ""d""); } if (neighborInfo.mFullNetworkData) { strcat(mode, ""n""); } blobmsg_add_string(&mBuf, ""Mode"", mode); OutputBytes(neighborInfo.mExtAddress.m8, sizeof(neighborInfo.mExtAddress.m8), extAddress); blobmsg_add_string(&mBuf, ""ExtAddress"", extAddress); blobmsg_add_u16(&mBuf, ""LinkQualityIn"", neighborInfo.mLinkQualityIn); blobmsg_close_table(&mBuf, jsonList); memset(mode, 0, sizeof(mode)); memset(extAddress, 0, sizeof(extAddress)); } blobmsg_close_array(&mBuf, sJsonUri); mNcpThreadMutex->unlock(); AppendResult(error, aContext, aRequest); return 0; } int UbusServer::UbusMgmtset(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; struct blob_attr * tb[MGMTSET_MAX]; otOperationalDataset dataset; uint8_t tlvs[128]; long value; int length = 0; SuccessOrExit(error = otDatasetGetActive(mController->GetInstance(), &dataset)); blobmsg_parse(mgmtsetPolicy, MGMTSET_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[NETWORKKEY] != nullptr) { dataset.mComponents.mIsNetworkKeyPresent = true; VerifyOrExit((length = Hex2Bin(blobmsg_get_string(tb[NETWORKKEY]), dataset.mNetworkKey.m8, sizeof(dataset.mNetworkKey.m8))) == OT_NETWORK_KEY_SIZE, error = OT_ERROR_PARSE); length = 0; } if (tb[NETWORKNAME] != nullptr) { dataset.mComponents.mIsNetworkNamePresent = true; VerifyOrExit((length = static_cast(strlen(blobmsg_get_string(tb[NETWORKNAME])))) <= OT_NETWORK_NAME_MAX_SIZE, error = OT_ERROR_PARSE); memset(&dataset.mNetworkName, 0, sizeof(dataset.mNetworkName)); memcpy(dataset.mNetworkName.m8, blobmsg_get_string(tb[NETWORKNAME]), static_cast(length)); length = 0; } if (tb[EXTPANID] != nullptr) { dataset.mComponents.mIsExtendedPanIdPresent = true; VerifyOrExit(Hex2Bin(blobmsg_get_string(tb[EXTPANID]), dataset.mExtendedPanId.m8, sizeof(dataset.mExtendedPanId.m8)) >= 0, error = OT_ERROR_PARSE); } if (tb[PANID] != nullptr) { dataset.mComponents.mIsPanIdPresent = true; SuccessOrExit(error = ParseLong(blobmsg_get_string(tb[PANID]), value)); dataset.mPanId = static_cast(value); } if (tb[CHANNEL] != nullptr) { dataset.mComponents.mIsChannelPresent = true; SuccessOrExit(error = ParseLong(blobmsg_get_string(tb[CHANNEL]), value)); dataset.mChannel = static_cast(value); } if (tb[PSKC] != nullptr) { dataset.mComponents.mIsPskcPresent = true; VerifyOrExit((length = Hex2Bin(blobmsg_get_string(tb[PSKC]), dataset.mPskc.m8, sizeof(dataset.mPskc.m8))) == OT_PSKC_MAX_SIZE, error = OT_ERROR_PARSE); length = 0; } dataset.mActiveTimestamp.mSeconds++; if (otCommissionerGetState(mController->GetInstance()) == OT_COMMISSIONER_STATE_DISABLED) { otCommissionerStop(mController->GetInstance()); } SuccessOrExit(error = otDatasetSendMgmtActiveSet(mController->GetInstance(), &dataset, tlvs, static_cast(length), /* aCallback */ nullptr, /* aContext */ nullptr)); exit: AppendResult(error, aContext, aRequest); return 0; } int UbusServer::UbusCommissioner(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg, const char * aAction) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; mNcpThreadMutex->lock(); if (!strcmp(aAction, ""start"")) { if (otCommissionerGetState(mController->GetInstance()) == OT_COMMISSIONER_STATE_DISABLED) { error = otCommissionerStart(mController->GetInstance(), &UbusServer::HandleStateChanged, &UbusServer::HandleJoinerEvent, this); } } else if (!strcmp(aAction, ""joineradd"")) { struct blob_attr * tb[ADD_JOINER_MAX]; otExtAddress addr; const otExtAddress *addrPtr = nullptr; char * pskd = nullptr; blobmsg_parse(addJoinerPolicy, ADD_JOINER_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[PSKD] != nullptr) { pskd = blobmsg_get_string(tb[PSKD]); } if (tb[EUI64] != nullptr) { if (!strcmp(blobmsg_get_string(tb[EUI64]), ""*"")) { addrPtr = nullptr; memset(&addr, 0, sizeof(addr)); } else { VerifyOrExit(Hex2Bin(blobmsg_get_string(tb[EUI64]), addr.m8, sizeof(addr)) == sizeof(addr), error = OT_ERROR_PARSE); addrPtr = &addr; } } unsigned long timeout = kDefaultJoinerTimeout; SuccessOrExit( error = otCommissionerAddJoiner(mController->GetInstance(), addrPtr, pskd, static_cast(timeout))); } else if (!strcmp(aAction, ""joinerremove"")) { struct blob_attr * tb[SET_NETWORK_MAX]; otExtAddress addr; const otExtAddress *addrPtr = nullptr; blobmsg_parse(removeJoinerPolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { if (strcmp(blobmsg_get_string(tb[SETNETWORK]), ""*"") == 0) { addrPtr = nullptr; } else { VerifyOrExit(Hex2Bin(blobmsg_get_string(tb[SETNETWORK]), addr.m8, sizeof(addr)) == sizeof(addr), error = OT_ERROR_PARSE); addrPtr = &addr; } } SuccessOrExit(error = otCommissionerRemoveJoiner(mController->GetInstance(), addrPtr)); } exit: mNcpThreadMutex->unlock(); blob_buf_init(&mBuf, 0); AppendResult(error, aContext, aRequest); return 0; } void UbusServer::HandleStateChanged(otCommissionerState aState, void *aContext) { static_cast(aContext)->HandleStateChanged(aState); } void UbusServer::HandleStateChanged(otCommissionerState aState) { switch (aState) { case OT_COMMISSIONER_STATE_DISABLED: otbrLogInfo(""Commissioner state disabled""); break; case OT_COMMISSIONER_STATE_ACTIVE: otbrLogInfo(""Commissioner state active""); break; case OT_COMMISSIONER_STATE_PETITION: otbrLogInfo(""Commissioner state petition""); break; } } void UbusServer::HandleJoinerEvent(otCommissionerJoinerEvent aEvent, const otJoinerInfo * aJoinerInfo, const otExtAddress * aJoinerId, void * aContext) { static_cast(aContext)->HandleJoinerEvent(aEvent, aJoinerInfo, aJoinerId); } void UbusServer::HandleJoinerEvent(otCommissionerJoinerEvent aEvent, const otJoinerInfo * aJoinerInfo, const otExtAddress * aJoinerId) { OT_UNUSED_VARIABLE(aJoinerInfo); OT_UNUSED_VARIABLE(aJoinerId); switch (aEvent) { case OT_COMMISSIONER_JOINER_START: otbrLogInfo(""Joiner start""); break; case OT_COMMISSIONER_JOINER_CONNECTED: otbrLogInfo(""Joiner connected""); break; case OT_COMMISSIONER_JOINER_FINALIZE: otbrLogInfo(""Joiner finalize""); break; case OT_COMMISSIONER_JOINER_END: otbrLogInfo(""Joiner end""); break; case OT_COMMISSIONER_JOINER_REMOVED: otbrLogInfo(""Joiner remove""); break; } } int UbusServer::UbusGetInformation(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg, const char * aAction) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; blob_buf_init(&mBuf, 0); mNcpThreadMutex->lock(); if (!strcmp(aAction, ""networkname"")) blobmsg_add_string(&mBuf, ""NetworkName"", otThreadGetNetworkName(mController->GetInstance())); else if (!strcmp(aAction, ""state"")) { char state[10]; GetState(mController->GetInstance(), state); blobmsg_add_string(&mBuf, ""State"", state); } else if (!strcmp(aAction, ""channel"")) blobmsg_add_u32(&mBuf, ""Channel"", otLinkGetChannel(mController->GetInstance())); else if (!strcmp(aAction, ""panid"")) { char panIdString[PANID_LENGTH]; sprintf(panIdString, ""0x%04x"", otLinkGetPanId(mController->GetInstance())); blobmsg_add_string(&mBuf, ""PanId"", panIdString); } else if (!strcmp(aAction, ""rloc16"")) { char rloc[PANID_LENGTH]; sprintf(rloc, ""0x%04x"", otThreadGetRloc16(mController->GetInstance())); blobmsg_add_string(&mBuf, ""rloc16"", rloc); } else if (!strcmp(aAction, ""networkkey"")) { char outputKey[NETWORKKEY_LENGTH] = """"; otNetworkKey key; otThreadGetNetworkKey(mController->GetInstance(), &key); OutputBytes(key.m8, OT_NETWORK_KEY_SIZE, outputKey); blobmsg_add_string(&mBuf, ""Networkkey"", outputKey); } else if (!strcmp(aAction, ""pskc"")) { char outputPskc[NETWORKKEY_LENGTH] = """"; otPskc pskc; otThreadGetPskc(mController->GetInstance(), &pskc); OutputBytes(pskc.m8, OT_PSKC_MAX_SIZE, outputPskc); blobmsg_add_string(&mBuf, ""pskc"", outputPskc); } else if (!strcmp(aAction, ""extpanid"")) { char outputExtPanId[XPANID_LENGTH] = """"; const uint8_t *extPanId = reinterpret_cast(otThreadGetExtendedPanId(mController->GetInstance())); OutputBytes(extPanId, OT_EXT_PAN_ID_SIZE, outputExtPanId); blobmsg_add_string(&mBuf, ""ExtPanId"", outputExtPanId); } else if (!strcmp(aAction, ""mode"")) { otLinkModeConfig linkMode; char mode[5] = """"; memset(&linkMode, 0, sizeof(otLinkModeConfig)); linkMode = otThreadGetLinkMode(mController->GetInstance()); if (linkMode.mRxOnWhenIdle) { strcat(mode, ""r""); } if (linkMode.mDeviceType) { strcat(mode, ""d""); } if (linkMode.mNetworkData) { strcat(mode, ""n""); } blobmsg_add_string(&mBuf, ""Mode"", mode); } else if (!strcmp(aAction, ""partitionid"")) { blobmsg_add_u32(&mBuf, ""Partitionid"", otThreadGetPartitionId(mController->GetInstance())); } else if (!strcmp(aAction, ""leaderdata"")) { otLeaderData leaderData; SuccessOrExit(error = otThreadGetLeaderData(mController->GetInstance(), &leaderData)); sJsonUri = blobmsg_open_table(&mBuf, ""leaderdata""); blobmsg_add_u32(&mBuf, ""PartitionId"", leaderData.mPartitionId); blobmsg_add_u32(&mBuf, ""Weighting"", leaderData.mWeighting); blobmsg_add_u32(&mBuf, ""DataVersion"", leaderData.mDataVersion); blobmsg_add_u32(&mBuf, ""StableDataVersion"", leaderData.mStableDataVersion); blobmsg_add_u32(&mBuf, ""LeaderRouterId"", leaderData.mLeaderRouterId); blobmsg_close_table(&mBuf, sJsonUri); } else if (!strcmp(aAction, ""networkdata"")) { ubus_send_reply(aContext, aRequest, mNetworkdataBuf.head); if (time(nullptr) - mSecond > 10) { struct otIp6Address address; uint8_t tlvTypes[OT_NETWORK_DIAGNOSTIC_TYPELIST_MAX_ENTRIES]; uint8_t count = 0; char multicastAddr[10] = ""ff03::2""; blob_buf_init(&mNetworkdataBuf, 0); SuccessOrExit(error = otIp6AddressFromString(multicastAddr, &address)); tlvTypes[count++] = static_cast(OT_NETWORK_DIAGNOSTIC_TLV_ROUTE); tlvTypes[count++] = static_cast(OT_NETWORK_DIAGNOSTIC_TLV_CHILD_TABLE); sBufNum = 0; otThreadSendDiagnosticGet(mController->GetInstance(), &address, tlvTypes, count, &UbusServer::HandleDiagnosticGetResponse, this); mSecond = time(nullptr); } goto exit; } else if (!strcmp(aAction, ""joinernum"")) { void * jsonTable = nullptr; void * jsonArray = nullptr; otJoinerInfo joinerInfo; uint16_t iterator = 0; int joinerNum = 0; char eui64[EXTPANID] = """"; blob_buf_init(&mBuf, 0); jsonArray = blobmsg_open_array(&mBuf, ""joinerList""); while (otCommissionerGetNextJoinerInfo(mController->GetInstance(), &iterator, &joinerInfo) == OT_ERROR_NONE) { memset(eui64, 0, sizeof(eui64)); jsonTable = blobmsg_open_table(&mBuf, nullptr); blobmsg_add_string(&mBuf, ""pskd"", joinerInfo.mPskd.m8); switch (joinerInfo.mType) { case OT_JOINER_INFO_TYPE_ANY: blobmsg_add_u16(&mBuf, ""isAny"", 1); break; case OT_JOINER_INFO_TYPE_EUI64: blobmsg_add_u16(&mBuf, ""isAny"", 0); OutputBytes(joinerInfo.mSharedId.mEui64.m8, sizeof(joinerInfo.mSharedId.mEui64.m8), eui64); blobmsg_add_string(&mBuf, ""eui64"", eui64); break; case OT_JOINER_INFO_TYPE_DISCERNER: blobmsg_add_u16(&mBuf, ""isAny"", 0); blobmsg_add_u64(&mBuf, ""discernerValue"", joinerInfo.mSharedId.mDiscerner.mValue); blobmsg_add_u16(&mBuf, ""discernerLength"", joinerInfo.mSharedId.mDiscerner.mLength); break; } blobmsg_close_table(&mBuf, jsonTable); joinerNum++; } blobmsg_close_array(&mBuf, jsonArray); blobmsg_add_u32(&mBuf, ""joinernum"", joinerNum); } else if (!strcmp(aAction, ""macfilterstate"")) { otMacFilterAddressMode mode = otLinkFilterGetAddressMode(mController->GetInstance()); blob_buf_init(&mBuf, 0); if (mode == OT_MAC_FILTER_ADDRESS_MODE_DISABLED) { blobmsg_add_string(&mBuf, ""state"", ""disable""); } else if (mode == OT_MAC_FILTER_ADDRESS_MODE_ALLOWLIST) { blobmsg_add_string(&mBuf, ""state"", ""allowlist""); } else if (mode == OT_MAC_FILTER_ADDRESS_MODE_DENYLIST) { blobmsg_add_string(&mBuf, ""state"", ""denylist""); } else { blobmsg_add_string(&mBuf, ""state"", ""error""); } } else if (!strcmp(aAction, ""macfilteraddr"")) { otMacFilterEntry entry; otMacFilterIterator iterator = OT_MAC_FILTER_ITERATOR_INIT; blob_buf_init(&mBuf, 0); sJsonUri = blobmsg_open_array(&mBuf, ""addrlist""); while (otLinkFilterGetNextAddress(mController->GetInstance(), &iterator, &entry) == OT_ERROR_NONE) { char extAddress[XPANID_LENGTH] = """"; OutputBytes(entry.mExtAddress.m8, sizeof(entry.mExtAddress.m8), extAddress); blobmsg_add_string(&mBuf, ""addr"", extAddress); } blobmsg_close_array(&mBuf, sJsonUri); } else { perror(""invalid argument in get information ubus\\n""); } AppendResult(error, aContext, aRequest); exit: mNcpThreadMutex->unlock(); return 0; } void UbusServer::HandleDiagnosticGetResponse(otError aError, otMessage * aMessage, const otMessageInfo *aMessageInfo, void * aContext) { static_cast(aContext)->HandleDiagnosticGetResponse(aError, aMessage, aMessageInfo); } static bool IsRoutingLocator(const otIp6Address *aAddress) { enum { kAloc16Mask = 0xfc, ///< The mask for Aloc16. kRloc16ReservedBitMask = 0x02, ///< The mask for the reserved bit of Rloc16. }; return (aAddress->mFields.m32[2] == htonl(0x000000ff) && aAddress->mFields.m16[6] == htons(0xfe00) && aAddress->mFields.m8[14] < kAloc16Mask && (aAddress->mFields.m8[14] & kRloc16ReservedBitMask) == 0); } void UbusServer::HandleDiagnosticGetResponse(otError aError, otMessage *aMessage, const otMessageInfo *aMessageInfo) { uint16_t rloc16; uint16_t sockRloc16 = 0; void * jsonArray = nullptr; void * jsonItem = nullptr; char xrloc[10]; otNetworkDiagTlv diagTlv; otNetworkDiagIterator iterator = OT_NETWORK_DIAGNOSTIC_ITERATOR_INIT; SuccessOrExit(aError); char networkdata[20]; sprintf(networkdata, ""networkdata%d"", sBufNum); sJsonUri = blobmsg_open_table(&mNetworkdataBuf, networkdata); sBufNum++; if (IsRoutingLocator(&aMessageInfo->mSockAddr)) { sockRloc16 = ntohs(aMessageInfo->mPeerAddr.mFields.m16[7]); sprintf(xrloc, ""0x%04x"", sockRloc16); blobmsg_add_string(&mNetworkdataBuf, ""rloc"", xrloc); } while (otThreadGetNextDiagnosticTlv(aMessage, &iterator, &diagTlv) == OT_ERROR_NONE) { switch (diagTlv.mType) { case OT_NETWORK_DIAGNOSTIC_TLV_ROUTE: { const otNetworkDiagRoute &route = diagTlv.mData.mRoute; jsonArray = blobmsg_open_array(&mNetworkdataBuf, ""routedata""); for (uint16_t i = 0; i < route.mRouteCount; ++i) { uint8_t in, out; in = route.mRouteData[i].mLinkQualityIn; out = route.mRouteData[i].mLinkQualityOut; if (in != 0 && out != 0) { jsonItem = blobmsg_open_table(&mNetworkdataBuf, ""router""); rloc16 = route.mRouteData[i].mRouterId << 10; blobmsg_add_u32(&mNetworkdataBuf, ""routerid"", route.mRouteData[i].mRouterId); sprintf(xrloc, ""0x%04x"", rloc16); blobmsg_add_string(&mNetworkdataBuf, ""rloc"", xrloc); blobmsg_close_table(&mNetworkdataBuf, jsonItem); } } blobmsg_close_array(&mNetworkdataBuf, jsonArray); break; } case OT_NETWORK_DIAGNOSTIC_TLV_CHILD_TABLE: { jsonArray = blobmsg_open_array(&mNetworkdataBuf, ""childdata""); for (uint16_t i = 0; i < diagTlv.mData.mChildTable.mCount; ++i) { enum { kModeRxOnWhenIdle = 1 << 3, ///< If the device has its receiver on when not transmitting. kModeFullThreadDevice = 1 << 1, ///< If the device is an FTD. kModeFullNetworkData = 1 << 0, ///< If the device requires the full Network Data. }; const otNetworkDiagChildEntry &entry = diagTlv.mData.mChildTable.mTable[i]; uint8_t mode = 0; jsonItem = blobmsg_open_table(&mNetworkdataBuf, ""child""); sprintf(xrloc, ""0x%04x"", (sockRloc16 | entry.mChildId)); blobmsg_add_string(&mNetworkdataBuf, ""rloc"", xrloc); mode = (entry.mMode.mRxOnWhenIdle ? kModeRxOnWhenIdle : 0) | (entry.mMode.mDeviceType ? kModeFullThreadDevice : 0) | (entry.mMode.mNetworkData ? kModeFullNetworkData : 0); blobmsg_add_u16(&mNetworkdataBuf, ""mode"", mode); blobmsg_close_table(&mNetworkdataBuf, jsonItem); } blobmsg_close_array(&mNetworkdataBuf, jsonArray); break; } default: // Ignore other network diagnostics data. break; } } blobmsg_close_table(&mNetworkdataBuf, sJsonUri); exit: if (aError != OT_ERROR_NONE) { otbrLogWarning(""Failed to receive diagnostic response: %s"", otThreadErrorToString(aError)); } } int UbusServer::UbusSetInformation(struct ubus_context * aContext, struct ubus_object * aObj, struct ubus_request_data *aRequest, const char * aMethod, struct blob_attr * aMsg, const char * aAction) { OT_UNUSED_VARIABLE(aObj); OT_UNUSED_VARIABLE(aMethod); OT_UNUSED_VARIABLE(aMsg); otError error = OT_ERROR_NONE; blob_buf_init(&mBuf, 0); mNcpThreadMutex->lock(); if (!strcmp(aAction, ""networkname"")) { struct blob_attr *tb[SET_NETWORK_MAX]; blobmsg_parse(setNetworknamePolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { char *newName = blobmsg_get_string(tb[SETNETWORK]); SuccessOrExit(error = otThreadSetNetworkName(mController->GetInstance(), newName)); } } else if (!strcmp(aAction, ""channel"")) { struct blob_attr *tb[SET_NETWORK_MAX]; blobmsg_parse(setChannelPolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { uint32_t channel = blobmsg_get_u32(tb[SETNETWORK]); SuccessOrExit(error = otLinkSetChannel(mController->GetInstance(), static_cast(channel))); } } else if (!strcmp(aAction, ""panid"")) { struct blob_attr *tb[SET_NETWORK_MAX]; blobmsg_parse(setPanIdPolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { long value; char *panid = blobmsg_get_string(tb[SETNETWORK]); SuccessOrExit(error = ParseLong(panid, value)); error = otLinkSetPanId(mController->GetInstance(), static_cast(value)); } } else if (!strcmp(aAction, ""networkkey"")) { struct blob_attr *tb[SET_NETWORK_MAX]; blobmsg_parse(setNetworkkeyPolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { otNetworkKey key; char * networkkey = blobmsg_get_string(tb[SETNETWORK]); VerifyOrExit(Hex2Bin(networkkey, key.m8, sizeof(key.m8)) == OT_NETWORK_KEY_SIZE, error = OT_ERROR_PARSE); SuccessOrExit(error = otThreadSetNetworkKey(mController->GetInstance(), &key)); } } else if (!strcmp(aAction, ""pskc"")) { struct blob_attr *tb[SET_NETWORK_MAX]; blobmsg_parse(setPskcPolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { otPskc pskc; VerifyOrExit(Hex2Bin(blobmsg_get_string(tb[SETNETWORK]), pskc.m8, sizeof(pskc)) == OT_PSKC_MAX_SIZE, error = OT_ERROR_PARSE); SuccessOrExit(error = otThreadSetPskc(mController->GetInstance(), &pskc)); } } else if (!strcmp(aAction, ""extpanid"")) { struct blob_attr *tb[SET_NETWORK_MAX]; blobmsg_parse(setExtPanIdPolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { otExtendedPanId extPanId; char * input = blobmsg_get_string(tb[SETNETWORK]); VerifyOrExit(Hex2Bin(input, extPanId.m8, sizeof(extPanId)) >= 0, error = OT_ERROR_PARSE); error = otThreadSetExtendedPanId(mController->GetInstance(), &extPanId); } } else if (!strcmp(aAction, ""mode"")) { otLinkModeConfig linkMode; struct blob_attr *tb[SET_NETWORK_MAX]; blobmsg_parse(setModePolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { char *inputMode = blobmsg_get_string(tb[SETNETWORK]); for (char *ch = inputMode; *ch != '\\0'; ch++) { switch (*ch) { case 'r': linkMode.mRxOnWhenIdle = 1; break; case 'd': linkMode.mDeviceType = 1; break; case 'n': linkMode.mNetworkData = 1; break; default: ExitNow(error = OT_ERROR_PARSE); } } SuccessOrExit(error = otThreadSetLinkMode(mController->GetInstance(), linkMode)); } } else if (!strcmp(aAction, ""macfilteradd"")) { struct blob_attr *tb[SET_NETWORK_MAX]; otExtAddress extAddr; blobmsg_parse(macfilterAddPolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { char *addr = blobmsg_get_string(tb[SETNETWORK]); VerifyOrExit(Hex2Bin(addr, extAddr.m8, OT_EXT_ADDRESS_SIZE) == OT_EXT_ADDRESS_SIZE, error = OT_ERROR_PARSE); error = otLinkFilterAddAddress(mController->GetInstance(), &extAddr); VerifyOrExit(error == OT_ERROR_NONE || error == OT_ERROR_ALREADY); } } else if (!strcmp(aAction, ""macfilterremove"")) { struct blob_attr *tb[SET_NETWORK_MAX]; otExtAddress extAddr; blobmsg_parse(macfilterRemovePolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { char *addr = blobmsg_get_string(tb[SETNETWORK]); VerifyOrExit(Hex2Bin(addr, extAddr.m8, OT_EXT_ADDRESS_SIZE) == OT_EXT_ADDRESS_SIZE, error = OT_ERROR_PARSE); otLinkFilterRemoveAddress(mController->GetInstance(), &extAddr); } } else if (!strcmp(aAction, ""macfiltersetstate"")) { struct blob_attr *tb[SET_NETWORK_MAX]; blobmsg_parse(macfilterSetStatePolicy, SET_NETWORK_MAX, tb, blob_data(aMsg), blob_len(aMsg)); if (tb[SETNETWORK] != nullptr) { char *state = blobmsg_get_string(tb[SETNETWORK]); if (strcmp(state, ""disable"") == 0) { otLinkFilterSetAddressMode(mController->GetInstance(), OT_MAC_FILTER_ADDRESS_MODE_DISABLED); } else if (strcmp(state, ""allowlist"") == 0) { otLinkFilterSetAddressMode(mController->GetInstance(), OT_MAC_FILTER_ADDRESS_MODE_ALLOWLIST); } else if (strcmp(state, ""denylist"") == 0) { otLinkFilterSetAddressMode(mController->GetInstance(), OT_MAC_FILTER_ADDRESS_MODE_DENYLIST); } } } else if (!strcmp(aAction, ""macfilterclear"")) { otLinkFilterClearAddresses(mController->GetInstance()); } else { perror(""invalid argument in get information ubus\\n""); } exit: mNcpThreadMutex->unlock(); AppendResult(error, aContext, aRequest); return 0; } void UbusServer::GetState(otInstance *aInstance, char *aState) { switch (otThreadGetDeviceRole(aInstance)) { case OT_DEVICE_ROLE_DISABLED: strcpy(aState, ""disabled""); break; case OT_DEVICE_ROLE_DETACHED: strcpy(aState, ""detached""); break; case OT_DEVICE_ROLE_CHILD: strcpy(aState, ""child""); break; case OT_DEVICE_ROLE_ROUTER: strcpy(aState, ""router""); break; case OT_DEVICE_ROLE_LEADER: strcpy(aState, ""leader""); break; default: strcpy(aState, ""invalid aState""); break; } } void UbusServer::UbusAddFd() { // ubus library function ubus_add_uloop(mContext); #ifdef FD_CLOEXEC fcntl(mContext->sock.fd, F_SETFD, fcntl(mContext->sock.fd, F_GETFD) | FD_CLOEXEC); #endif } void UbusServer::UbusReconnTimer(struct uloop_timeout *aTimeout) { GetInstance().UbusReconnTimerDetail(aTimeout); } void UbusServer::UbusReconnTimerDetail(struct uloop_timeout *aTimeout) { OT_UNUSED_VARIABLE(aTimeout); static struct uloop_timeout retry = { list : {}, pending : false, cb : UbusReconnTimer, time : {}, }; int time = 2; if (ubus_reconnect(mContext, mSockPath) != 0) { uloop_timeout_set(&retry, time * 1000); return; } UbusAddFd(); } void UbusServer::UbusConnectionLost(struct ubus_context *aContext) { OT_UNUSED_VARIABLE(aContext); UbusReconnTimer(nullptr); } int UbusServer::DisplayUbusInit(const char *aPath) { uloop_init(); signal(SIGPIPE, SIG_IGN); mSockPath = aPath; mContext = ubus_connect(aPath); if (!mContext) { otbrLogErr(""Ubus connect failed""); return -1; } otbrLogInfo(""Connected as %08x\\n"", mContext->local_id); mContext->connection_lost = UbusConnectionLost; /* file description */ UbusAddFd(); /* Add a object */ if (ubus_add_object(mContext, &otbr) != 0) { otbrLogErr(""Ubus add obj failed""); return -1; } return 0; } void UbusServer::DisplayUbusDone(void) { if (mContext) { ubus_free(mContext); mContext = nullptr; } } void UbusServer::InstallUbusObject(void) { char *path = nullptr; if (-1 == DisplayUbusInit(path)) { otbrLogErr(""Ubus connect failed""); return; } otbrLogInfo(""Uloop run""); uloop_run(); DisplayUbusDone(); uloop_done(); } otError UbusServer::ParseLong(char *aString, long &aLong) { char *endptr; aLong = strtol(aString, &endptr, 0); return (*endptr == '\\0') ? OT_ERROR_NONE : OT_ERROR_PARSE; } int UbusServer::Hex2Bin(const char *aHex, uint8_t *aBin, uint16_t aBinLength) { size_t hexLength = strlen(aHex); const char *hexEnd = aHex + hexLength; uint8_t * cur = aBin; uint8_t numChars = hexLength & 1; uint8_t byte = 0; int rval; VerifyOrExit((hexLength + 1) / 2 <= aBinLength, rval = -1); while (aHex < hexEnd) { if ('A' <= *aHex && *aHex <= 'F') { byte |= 10 + (*aHex - 'A'); } else if ('a' <= *aHex && *aHex <= 'f') { byte |= 10 + (*aHex - 'a'); } else if ('0' <= *aHex && *aHex <= '9') { byte |= *aHex - '0'; } else { ExitNow(rval = -1); } aHex++; numChars++; if (numChars >= 2) { numChars = 0; *cur++ = byte; byte = 0; } else { byte <<= 4; } } rval = static_cast(cur - aBin); exit: return rval; } void UBusAgent::Init(void) { otbr::ubus::sUbusEfd = eventfd(0, 0); otbr::ubus::UbusServer::Initialize(&mNcp, &mThreadMutex); if (otbr::ubus::sUbusEfd == -1) { perror(""Failed to create eventfd for ubus""); exit(EXIT_FAILURE); } std::thread(UbusServerRun).detach(); } void UBusAgent::Update(MainloopContext &aMainloop) { VerifyOrExit(otbr::ubus::sUbusEfd != -1); FD_SET(otbr::ubus::sUbusEfd, &aMainloop.mReadFdSet); if (aMainloop.mMaxFd < otbr::ubus::sUbusEfd) { aMainloop.mMaxFd = otbr::ubus::sUbusEfd; } exit: mThreadMutex.unlock(); return; } void UBusAgent::Process(const MainloopContext &aMainloop) { ssize_t retval; uint64_t num; mThreadMutex.lock(); VerifyOrExit(otbr::ubus::sUbusEfd != -1); if (FD_ISSET(otbr::ubus::sUbusEfd, &aMainloop.mReadFdSet)) { retval = read(otbr::ubus::sUbusEfd, &num, sizeof(uint64_t)); if (retval != sizeof(uint64_t)) { perror(""read ubus eventfd failed\\n""); exit(EXIT_FAILURE); } } exit: return; } } // namespace ubus } // namespace otbr ",16243,True,3221.421071043207,median "// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include #include #include #include ""gtest/gtest.h"" #include ""test/common/quantization_test_utils.h"" #include ""test/common/tensor_op_test_utils.h"" #include ""test/common/cuda_op_test_utils.h"" #include ""test/providers/provider_test_utils.h"" #include ""core/util/qmath.h"" #include ""core/quantization/quantization.h"" namespace onnxruntime { namespace test { enum class EP : char { CPU, CUDA }; // input: [batch_size, sequence_length, hidden_size] // weights: [hidden_size, 3 * hidden_size] // bias: [3 * hidden_size] // mask_index: [batch_size] // output: [batch_size, sequence_length, hidden_size] template void RunQAttention(const std::vector& input_data, const std::vector& weights_data, const std::vector& bias_data, const std::vector& mask_index_data, const std::vector& output_data, quantization::Params& input_quant_params, quantization::Params& weight_quant_params, int batch_size, int sequence_length, int hidden_size, int number_of_heads, bool is_unidirectional = false, bool use_float16 = false, int input_hidden_size = 0) { input_hidden_size = (input_hidden_size == 0) ? hidden_size : input_hidden_size; OpTester tester(""QAttention"", 1, onnxruntime::kMSDomain); tester.AddAttribute(""num_heads"", static_cast(number_of_heads)); if (is_unidirectional) { tester.AddAttribute(""unidirectional"", 1); } std::vector input_dims = {batch_size, sequence_length, input_hidden_size}; std::vector weights_dims = {input_hidden_size, static_cast(3 * hidden_size)}; std::vector bias_dims = {static_cast(3 * hidden_size)}; std::vector mask_index_dims = {batch_size}; std::vector output_dims = {batch_size, sequence_length, hidden_size}; if (input_quant_params.scale != 0.0f) { tester.AddInput(""input"", input_dims, QuantizeTestVector(input_data, input_quant_params)); tester.AddInput(""weight"", weights_dims, QuantizeTestVector(weights_data, weight_quant_params)); } else { bool force_symmetric = false; if constexpr (ep == EP::CUDA) { force_symmetric = true; } tester.AddInput( ""input"", input_dims, QuantizeLinearTestVector(input_data, input_quant_params, force_symmetric)); tester.AddInput( ""weight"", weights_dims, QuantizeLinearTestVector(weights_data, weight_quant_params, force_symmetric)); } if (use_float16) { tester.AddInput(""bias"", bias_dims, ToFloat16(bias_data)); tester.AddInput(""input_scale"", {1}, ToFloat16({input_quant_params.scale})); tester.AddInput(""weight_scale"", {1}, ToFloat16({weight_quant_params.scale})); tester.AddOutput(""output"", output_dims, ToFloat16(output_data)); } else { tester.AddInput(""bias"", bias_dims, bias_data); tester.AddInput(""input_scale"", {1}, {input_quant_params.scale}); tester.AddInput(""weight_scale"", {1}, {weight_quant_params.scale}); tester.AddOutput(""output"", output_dims, output_data); } if (mask_index_data.size() > 0) { tester.AddInput(""mask_index"", mask_index_dims, mask_index_data); } else { // mask index is optional. tester.AddOptionalInputEdge(); } tester.AddInput(""input_zero_point"", {1}, {input_quant_params.zero_point}); tester.AddInput(""weight_zero_point"", {1}, {weight_quant_params.zero_point}); if constexpr (ep == EP::CUDA) { std::vector> execution_providers; execution_providers.push_back(DefaultCudaExecutionProvider()); tester.Run(OpTester::ExpectResult::kExpectSuccess, """", {kTensorrtExecutionProvider}, nullptr, &execution_providers); } else { std::vector> execution_providers; execution_providers.push_back(DefaultCpuExecutionProvider()); tester.Run(OpTester::ExpectResult::kExpectSuccess, """", {kTensorrtExecutionProvider}, nullptr, &execution_providers); } } static void RunQAttentionCUDA( const std::vector& input_data, const std::vector& weights_data, const std::vector& bias_data, const std::vector& mask_index_data, const std::vector& output_data, int batch_size, int sequence_length, int hidden_size, int number_of_heads, bool use_special_quantize_parameter = true, bool is_unidirectional = false, bool use_float16 = false, int input_hidden_size = 0) { int min_cuda_architecture = 530; bool enable_cuda = HasCudaEnvironment(min_cuda_architecture); if (enable_cuda) { quantization::Params input_quant_params = {0.0f, 0}; quantization::Params weights_quant_params = {0.0f, 0}; if (use_special_quantize_parameter) { input_quant_params.scale = 0.1f; weights_quant_params.scale = 0.1f; } RunQAttention( input_data, weights_data, bias_data, mask_index_data, output_data, input_quant_params, weights_quant_params, batch_size, sequence_length, hidden_size, number_of_heads, is_unidirectional, use_float16, input_hidden_size); } } static void RunQAttentionU8U8( const std::vector& input_data, const std::vector& weights_data, const std::vector& bias_data, const std::vector& mask_index_data, const std::vector& output_data, int batch_size, int sequence_length, int hidden_size, int number_of_heads, bool use_special_quantize_parameter = true, bool is_unidirectional = false, int input_hidden_size = 0) { quantization::Params input_quant_params = {0.0f, 0}; quantization::Params weights_quant_params = {0.0f, 0}; if (use_special_quantize_parameter) { input_quant_params.scale = 0.1f; weights_quant_params.scale = 0.1f; input_quant_params.zero_point = 128; weights_quant_params.zero_point = 128; } RunQAttention( input_data, weights_data, bias_data, mask_index_data, output_data, input_quant_params, weights_quant_params, batch_size, sequence_length, hidden_size, number_of_heads, is_unidirectional, false, input_hidden_size); } static void RunQAttentionU8S8( const std::vector& input_data, const std::vector& weights_data, const std::vector& bias_data, const std::vector& mask_index_data, const std::vector& output_data, int batch_size, int sequence_length, int hidden_size, int number_of_heads, bool use_special_quantize_parameter = true, bool is_unidirectional = false, int input_hidden_size = 0) { quantization::Params input_quant_params(/*scale=*/0.0f, /*zero_point=*/0); quantization::Params weights_quant_params(/*scale=*/0.0f, /*zero_point=*/0); if (use_special_quantize_parameter) { input_quant_params.scale = 0.1f; weights_quant_params.scale = 0.1f; input_quant_params.zero_point = 128; weights_quant_params.zero_point = 1; } RunQAttention( input_data, weights_data, bias_data, mask_index_data, output_data, input_quant_params, weights_quant_params, batch_size, sequence_length, hidden_size, number_of_heads, is_unidirectional, false, input_hidden_size); } static void RunQAttentionAll( const std::vector& input_data, const std::vector& weight_data, const std::vector& bias_data, const std::vector& mask_index_data, const std::vector& output_data, int batch_size, int sequence_length, int hidden_size, int number_of_heads, bool use_special_quantize_parameter = true, bool is_unidirectional = false, bool use_float16 = false, int input_hidden_size = 0) { RunQAttentionU8U8(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads, use_special_quantize_parameter, is_unidirectional, input_hidden_size); RunQAttentionU8S8(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads, use_special_quantize_parameter, is_unidirectional, input_hidden_size); RunQAttentionCUDA(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads, use_special_quantize_parameter, is_unidirectional, use_float16, input_hidden_size); } TEST(QAttentionTest, QAttentionBatch1) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.8f, -0.5f, 0.0f, 1.f, 0.5f, 0.2f, 0.3f, -0.6f}; std::vector weight_data = { 0.1f, -0.2f, 0.3f, 1.0f, 1.1f, 0.3f, 0.5f, 0.2f, 0.3f, -0.6f, 1.5f, 2.0f, 0.5f, 0.1f, 0.4f, 1.6f, 1.0f, 2.0f, 0.4f, 0.8f, 0.9f, 0.1f, -1.3f, 0.7f, 0.3f, 0.2f, 4.0f, 2.2f, 1.6f, 1.1f, 0.7f, 0.2f, 0.4f, 1.0f, 1.2f, 0.5f, 0.2f, 0.1f, 0.4f, 1.6f, 2.4f, 3.3f, 2.1f, 4.2f, 8.4f, 0.0f, 2.1f, 3.2f}; std::vector bias_data = { -0.5f, 0.6f, 1.2f, 2.1f, 0.5f, 0.7f, 0.2f, 1.2f, 0.5f, 0.4f, 0.3f, 1.2f}; std::vector mask_index_data = {2L}; std::vector output_data = { 3.1495983600616455f, 0.10843668878078461f, 4.25f, 5.6499996185302734f, 3.9696791172027588f, 0.073143675923347473f, 4.2499995231628418f, 5.6499991416931152f}; RunQAttentionAll(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads); } TEST(QAttentionTest, QAttentionBatch1_Float16) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.8f, -0.5f, 0.0f, 1.f, 0.5f, 0.2f, 0.3f, -0.6f}; std::vector weight_data = { 0.1f, -0.2f, 0.3f, 1.0f, 1.1f, 0.3f, 0.5f, 0.2f, 0.3f, -0.6f, 1.5f, 2.0f, 0.5f, 0.1f, 0.4f, 1.6f, 1.0f, 2.0f, 0.4f, 0.8f, 0.9f, 0.1f, -1.3f, 0.7f, 0.3f, 0.2f, 4.0f, 2.2f, 1.6f, 1.1f, 0.7f, 0.2f, 0.4f, 1.0f, 1.2f, 0.5f, 0.2f, 0.1f, 0.4f, 1.6f, 2.4f, 3.3f, 2.1f, 4.2f, 8.4f, 0.0f, 2.1f, 3.2f}; std::vector bias_data = { -0.5f, 0.6f, 1.2f, 2.1f, 0.5f, 0.7f, 0.2f, 1.2f, 0.5f, 0.4f, 0.3f, 1.2f}; std::vector mask_index_data = {2L}; std::vector output_data = { 3.15039f, 0.1082763671875f, 4.24609375f, 5.6484375f, 3.96679f, 0.072998046875f, 4.24609f, 5.6484375f}; RunQAttentionCUDA(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads, true /*use_special_quantize_parameter*/, false /*is_unidirectional*/, true /*use_float16*/); } TEST(QAttentionTest, QAttentionBatch2) { int batch_size = 2; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.8f, -0.5f, 0.0f, 1.f, 0.5f, 0.2f, 0.3f, -0.6f, 0.8f, -0.5f, 0.0f, 1.f, 0.5f, 0.2f, 0.3f, -0.6f}; std::vector weight_data = { 0.1f, -0.2f, 0.3f, 1.0f, 1.1f, 0.3f, 0.5f, 0.2f, 0.3f, -0.6f, 1.5f, 2.0f, 0.5f, 0.1f, 0.4f, 1.6f, 1.0f, 2.0f, 0.4f, 0.8f, 0.9f, 0.1f, -1.3f, 0.7f, 0.3f, 0.2f, 4.0f, 2.2f, 1.6f, 1.1f, 0.7f, 0.2f, 0.4f, 1.0f, 1.2f, 0.5f, 0.2f, 0.1f, 0.4f, 1.6f, 2.4f, 3.3f, 2.1f, 4.2f, 8.4f, 0.0f, 2.1f, 3.2f}; std::vector bias_data = { -0.5f, 0.6f, 1.2f, 2.1f, 0.5f, 0.7f, 0.2f, 1.2f, 0.5f, 0.4f, 0.3f, 1.2f}; std::vector mask_index_data = {2L, 2L}; std::vector output_data = { 3.1495983600616455f, 0.10843668878078461f, 4.25f, 5.6499996185302734f, 3.9696791172027588f, 0.073143675923347473f, 4.2499995231628418f, 5.6499991416931152f, 3.1495983600616455f, 0.10843668878078461f, 4.25f, 5.6499996185302734f, 3.9696791172027588f, 0.073143675923347473f, 4.2499995231628418f, 5.6499991416931152f}; RunQAttentionAll(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads); } TEST(QAttentionTest, QAttentionMaskPartialSequence) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.8f, -0.5f, 0.0f, 1.f, 0.5f, 0.2f, 0.3f, -0.6f}; std::vector weight_data = { 0.1f, -0.2f, 0.3f, 1.0f, 1.1f, 0.3f, 0.5f, 0.2f, 0.3f, -0.6f, 1.5f, 2.0f, 0.5f, 0.1f, 0.4f, 1.6f, 1.0f, 2.0f, 0.4f, 0.8f, 0.9f, 0.1f, -1.3f, 0.7f, 0.3f, 0.2f, 4.0f, 2.2f, 1.6f, 1.1f, 0.7f, 0.2f, 0.4f, 1.0f, 1.2f, 0.5f, 0.2f, 0.1f, 0.4f, 1.6f, 2.4f, 3.3f, 2.1f, 4.2f, 8.4f, 0.0f, 2.1f, 3.2f}; std::vector bias_data = { -0.5f, 0.6f, 1.2f, 2.1f, 0.5f, 0.7f, 0.2f, 1.2f, 0.5f, 0.4f, 0.3f, 1.2f}; // Test mask_index < sequence_length std::vector mask_index_data = {1L}; std::vector output_data = { 8.6899995803833008f, -0.13000002503395081f, 4.25f, 5.6499996185302734f, 8.6899995803833008f, -0.13000002503395081f, 4.2499995231628418f, 5.6499991416931152f}; RunQAttentionAll(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads); } TEST(QAttentionTest, QAttentionMaskExceedSequence) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.8f, -0.5f, 0.0f, 1.f, 0.5f, 0.2f, 0.3f, -0.6f}; std::vector weight_data = { 0.1f, -0.2f, 0.3f, 1.0f, 1.1f, 0.3f, 0.5f, 0.2f, 0.3f, -0.6f, 1.5f, 2.0f, 0.5f, 0.1f, 0.4f, 1.6f, 1.0f, 2.0f, 0.4f, 0.8f, 0.9f, 0.1f, -1.3f, 0.7f, 0.3f, 0.2f, 4.0f, 2.2f, 1.6f, 1.1f, 0.7f, 0.2f, 0.4f, 1.0f, 1.2f, 0.5f, 0.2f, 0.1f, 0.4f, 1.6f, 2.4f, 3.3f, 2.1f, 4.2f, 8.4f, 0.0f, 2.1f, 3.2f}; std::vector bias_data = { -0.5f, 0.6f, 1.2f, 2.1f, 0.5f, 0.7f, 0.2f, 1.2f, 0.5f, 0.4f, 0.3f, 1.2f}; // Test mask_index > sequence_length std::vector mask_index_data = {3L}; std::vector output_data = { 3.1495983600616455f, 0.10843668878078461f, 4.25f, 5.6499996185302734f, 3.9696791172027588f, 0.073143675923347473f, 4.2499995231628418f, 5.6499991416931152f}; RunQAttentionAll(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads); } TEST(QAttentionTest, QAttentionNoMaskIndex) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.8f, -0.5f, 0.0f, 1.f, 0.5f, 0.2f, 0.3f, -0.6f}; std::vector weight_data = { 0.1f, -0.2f, 0.3f, 1.0f, 1.1f, 0.3f, 0.5f, 0.2f, 0.3f, -0.6f, 1.5f, 2.0f, 0.5f, 0.1f, 0.4f, 1.6f, 1.0f, 2.0f, 0.4f, 0.8f, 0.9f, 0.1f, -1.3f, 0.7f, 0.3f, 0.2f, 4.0f, 2.2f, 1.6f, 1.1f, 0.7f, 0.2f, 0.4f, 1.0f, 1.2f, 0.5f, 0.2f, 0.1f, 0.4f, 1.6f, 2.4f, 3.3f, 2.1f, 4.2f, 8.4f, 0.0f, 2.1f, 3.2f}; std::vector bias_data = { -0.5f, 0.6f, 1.2f, 2.1f, 0.5f, 0.7f, 0.2f, 1.2f, 0.5f, 0.4f, 0.3f, 1.2f}; // No mask_index std::vector mask_index_data = {}; std::vector output_data = { 3.1495983600616455f, 0.10843668878078461f, 4.25f, 5.6499996185302734f, 3.9696791172027588f, 0.073143675923347473f, 4.2499995231628418f, 5.6499991416931152f}; RunQAttentionAll(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads); } TEST(QAttentionTest, QAttentionUnidirectional_U8U8) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.91099896f, -0.18294459f, -0.36594841f, 0.28410032f, -0.12125026f, -0.66160089f, 0.38809127f, -0.22455512f}; std::vector weight_data = { -0.2659236192703247f, 0.2789675071835518f, 0.7280516624450684f, 0.50951678305864334f, 0.20417947322130203f, -0.4751841351389885f, 0.43815530836582184f, 0.6015353370457888f, -0.11496957391500473f, -0.1773347705602646f, 0.30928605794906616f, 0.5648412741720676f, 0.8960387855768204f, -0.27270448207855225f, 0.14847396314144135f, -0.17960812151432037f, 0.1788954995572567f, 0.9993876516819f, 0.3943513706326485f, -0.2484400011599064f, -0.12958766520023346f, 0.220433309674263f, 0.1720484346151352f, 0.22024005651474f, 0.59368450194597244f, 0.1710093915462494f, -0.3967452347278595f, -0.1591450721025467f, 0.1446179747581482f, -0.20505407452583313f, 0.12749597430229187f, 0.32139700651168823f, 0.139958456158638f, -0.10619817674160004f, 0.4528557509183884f, 0.45598603785037994f, -0.7152545265853405f, 0.109454445540905f, -0.1582530289888382f, -0.2646341919898987f, 0.920850858092308f, 0.701494812965393f, -0.19062495231628418f, -0.24360455572605133f, -0.9368397295475006f, 0.7878211885690689f, 0.2973634898662567f, 0.11210034042596817f}; std::vector bias_data = { -0.0540979839861393f, -0.06444740295410156f, 0.03112877532839775f, -0.08288222551345825f, 0.07840359210968018f, 0.039143580943346024f, -0.45591455698013306f, -0.11876055598258972f, 0.3670335114002228f, 0.028461361303925514f, -0.08913630992174149f, 0.28048714995384216f}; // No mask_index std::vector mask_index_data = {}; std::vector output_data = { -0.027716159820556641f, 0.091021925210952759f, 0.080938525497913361f, 0.61913836002349854f, 0.36089283227920532f, -0.11653690040111542f, -0.030121456831693649f, 0.40923327207565308f}; RunQAttentionU8U8(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads, false /*use_special_quantize_parameter*/, true /*is_unidirectional*/); } TEST(QAttentionTest, QAttentionUnidirectional_U8S8) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.91099896f, -0.18294459f, -0.36594841f, 0.28410032f, -0.12125026f, -0.66160089f, 0.38809127f, -0.22455512f}; std::vector weight_data = { -0.2659236192703247f, 0.2789675071835518f, 0.7280516624450684f, 0.50951678305864334f, 0.20417947322130203f, -0.4751841351389885f, 0.43815530836582184f, 0.6015353370457888f, -0.11496957391500473f, -0.1773347705602646f, 0.30928605794906616f, 0.5648412741720676f, 0.8960387855768204f, -0.27270448207855225f, 0.14847396314144135f, -0.17960812151432037f, 0.1788954995572567f, 0.9993876516819f, 0.3943513706326485f, -0.2484400011599064f, -0.12958766520023346f, 0.220433309674263f, 0.1720484346151352f, 0.22024005651474f, 0.59368450194597244f, 0.1710093915462494f, -0.3967452347278595f, -0.1591450721025467f, 0.1446179747581482f, -0.20505407452583313f, 0.12749597430229187f, 0.32139700651168823f, 0.139958456158638f, -0.10619817674160004f, 0.4528557509183884f, 0.45598603785037994f, -0.7152545265853405f, 0.109454445540905f, -0.1582530289888382f, -0.2646341919898987f, 0.920850858092308f, 0.701494812965393f, -0.19062495231628418f, -0.24360455572605133f, -0.9368397295475006f, 0.7878211885690689f, 0.2973634898662567f, 0.11210034042596817f}; std::vector bias_data = { -0.0540979839861393f, -0.06444740295410156f, 0.03112877532839775f, -0.08288222551345825f, 0.07840359210968018f, 0.039143580943346024f, -0.45591455698013306f, -0.11876055598258972f, 0.3670335114002228f, 0.028461361303925514f, -0.08913630992174149f, 0.28048714995384216f}; // No mask_index std::vector mask_index_data = {}; std::vector output_data = { -0.029270321130752563f, 0.089105717837810516f, 0.084381766617298126f, 0.62047165632247925f, 0.36089283227920532f, -0.11732138693332672f, -0.029981952160596848f, 0.40998253226280212f}; RunQAttentionU8S8(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads, false /*use_special_quantize_parameter*/, true /*is_unidirectional*/); } TEST(QAttentionTest, QAttentionUnidirectional_CUDA) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.91099896f, -0.18294459f, -0.36594841f, 0.28410032f, -0.12125026f, -0.66160089f, 0.38809127f, -0.22455512f}; std::vector weight_data = { -0.2659236192703247f, 0.2789675071835518f, 0.7280516624450684f, 0.50951678305864334f, 0.20417947322130203f, -0.4751841351389885f, 0.43815530836582184f, 0.6015353370457888f, -0.11496957391500473f, -0.1773347705602646f, 0.30928605794906616f, 0.5648412741720676f, 0.8960387855768204f, -0.27270448207855225f, 0.14847396314144135f, -0.17960812151432037f, 0.1788954995572567f, 0.9993876516819f, 0.3943513706326485f, -0.2484400011599064f, -0.12958766520023346f, 0.220433309674263f, 0.1720484346151352f, 0.22024005651474f, 0.59368450194597244f, 0.1710093915462494f, -0.3967452347278595f, -0.1591450721025467f, 0.1446179747581482f, -0.20505407452583313f, 0.12749597430229187f, 0.32139700651168823f, 0.139958456158638f, -0.10619817674160004f, 0.4528557509183884f, 0.45598603785037994f, -0.7152545265853405f, 0.109454445540905f, -0.1582530289888382f, -0.2646341919898987f, 0.920850858092308f, 0.701494812965393f, -0.19062495231628418f, -0.24360455572605133f, -0.9368397295475006f, 0.7878211885690689f, 0.2973634898662567f, 0.11210034042596817f}; std::vector bias_data = { -0.0540979839861393f, -0.06444740295410156f, 0.03112877532839775f, -0.08288222551345825f, 0.07840359210968018f, 0.039143580943346024f, -0.45591455698013306f, -0.11876055598258972f, 0.3670335114002228f, 0.028461361303925514f, -0.08913630992174149f, 0.28048714995384216f}; // No mask_index std::vector mask_index_data = {}; std::vector output_data = { -0.037525445222854614f, 0.089105717837810516f, 0.076988570392131805f, 0.62047165632247925f, 0.36089283227920532f, -0.11732138693332672f, -0.029981952160596848f, 0.40998253226280212f}; RunQAttentionCUDA(input_data, weight_data, bias_data, mask_index_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads, false /*use_special_quantize_parameter*/, true /*is_unidirectional*/); } template void TestQuantizedAttentionPastState(int64_t batch, int64_t seq_len, int64_t past_seq_len, int64_t hidden_size, int64_t head_number, int64_t head_size, const std::string& reference_model, bool is_weight_constant, bool per_column = false) { // create rand inputs RandomValueGenerator random{}; constexpr InputT input_min = std::numeric_limits::min(); constexpr InputT input_max = std::numeric_limits::max(); constexpr int32_t input_range = input_max - input_min; int64_t weight_scale_zp_size = per_column ? 3 * hidden_size : 1; InputT input_mean = (input_min + input_max) / 2 + 1; std::vector input_zero_point{input_mean}; std::vector input_dims{batch, seq_len, hidden_size}; std::vector input_data = random.Gaussian(input_dims, input_mean, static_cast(input_range / 6), input_min, input_max); constexpr WeightT weight_min = std::numeric_limits::min(); constexpr WeightT weight_max = std::numeric_limits::max(); constexpr int32_t weight_range = weight_max - weight_min; std::vector weight_zero_point(weight_scale_zp_size); for (auto& zp : weight_zero_point) { zp = static_cast(random.Uniform(std::array{1}, weight_min, weight_max)[0]); } WeightT weight_mean = (weight_min + weight_max) / 2 + 1; std::vector weight_dims{hidden_size, 3 * hidden_size}; std::vector weight_data = random.Gaussian(weight_dims, weight_mean, static_cast(weight_range / 6), weight_min, weight_max); std::vector bias_dims{3 * hidden_size}; std::vector bias_data = random.Gaussian(bias_dims, 0.0f, 0.3f); std::vector input_scale{0.005f}; std::vector weight_scale(random.Uniform({weight_scale_zp_size}, -0.01f, 0.01f)); std::vector past_dims{2, batch, head_number, past_seq_len, head_size}; std::vector past_data = random.Gaussian(past_dims, 0.0f, 0.3f); OpTester test(""QAttention"", 1, onnxruntime::kMSDomain); test.AddAttribute(""num_heads"", head_number); test.AddAttribute(""unidirectional"", 1); test.AddInput(""input"", input_dims, input_data); test.AddInput(""weight"", weight_dims, weight_data, is_weight_constant); test.AddInput(""bias"", bias_dims, bias_data); test.AddInput(""input_scale"", {1}, input_scale); test.AddInput(""weight_scale"", {weight_scale_zp_size}, weight_scale); test.AddOptionalInputEdge(); test.AddInput(""input_zero_point"", {1}, input_zero_point); test.AddInput(""weight_zero_point"", {weight_scale_zp_size}, weight_zero_point); test.AddInput(""past"", past_dims, past_data); test.AddReferenceOutputs(reference_model); test.Run(); } TEST(QAttentionTest, QAttentionPastState_u8u8) { TestQuantizedAttentionPastState(2, 5, 15, 768, 12, 64, ""testdata/attention_past_state.u8u8.onnx"", false /*is_weight_constant*/); TestQuantizedAttentionPastState(2, 5, 15, 768, 12, 64, ""testdata/attention_past_state.u8u8.onnx"", true /*is_weight_constant*/); TestQuantizedAttentionPastState(2, 5, 15, 768, 12, 64, ""testdata/attention_past_state.u8u8.onnx"", false /*is_weight_constant*/, true /*per_column*/); TestQuantizedAttentionPastState(2, 5, 15, 768, 12, 64, ""testdata/attention_past_state.u8u8.onnx"", true /*is_weight_constant*/, true /*per_column*/); } TEST(QAttentionTest, QAttentionPastState_u8s8) { TestQuantizedAttentionPastState(2, 5, 15, 768, 12, 64, ""testdata/attention_past_state.u8s8.onnx"", false /*is_weight_constant*/); TestQuantizedAttentionPastState(2, 5, 15, 768, 12, 64, ""testdata/attention_past_state.u8s8.onnx"", true /*is_weight_constant*/); TestQuantizedAttentionPastState(2, 5, 15, 768, 12, 64, ""testdata/attention_past_state.u8s8.onnx"", false /*is_weight_constant*/, true /*per_column*/); TestQuantizedAttentionPastState(2, 5, 15, 768, 12, 64, ""testdata/attention_past_state.u8s8.onnx"", true /*is_weight_constant*/, true /*per_column*/); } TEST(QAttentionTest, QAttentionPrunedModel) { int batch_size = 2; int sequence_length = 2; // test input_hidden_size > hidden_size int input_hidden_size = 6; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.5f, 0.2f, 0.3f, -0.6f, 0.0f, 1.0f, 0.8f, -0.5f, 0.0f, 1.f, 2.0f, 3.0f, 0.8f, -0.5f, 0.0f, 1.f, 4.0f, 5.0f, 0.5f, 0.2f, 0.3f, -0.6f, 6.0f, 7.0f}; std::vector weight_data = { 0.1f, -0.2f, 0.3f, 1.0f, 1.1f, 0.3f, 0.5f, 0.2f, 0.3f, -0.6f, 1.5f, 2.0f, 0.5f, 0.1f, 0.4f, 1.6f, 1.0f, 2.0f, 0.4f, 0.8f, 0.9f, 0.1f, -1.3f, 0.7f, 0.3f, 0.2f, 4.0f, 2.2f, 1.6f, 1.1f, 0.7f, 0.2f, 0.4f, 1.0f, 1.2f, 0.5f, 0.2f, 0.1f, 0.4f, 1.6f, 2.4f, 3.3f, 2.1f, 4.2f, 8.4f, 0.0f, 2.1f, 3.2f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f, 1.1f, 1.2f, 1.2f, 1.1f, 1.0f, 0.9f, 0.8f, 0.7f, 0.6f, 0.5f, 0.4f, 0.3f, 0.2f, 0.1f}; std::vector bias_data = { -0.5f, 0.6f, 1.2f, 2.1f, 0.5f, 0.7f, 0.2f, 1.2f, 0.5f, 0.4f, 0.3f, 1.2f}; std::vector mask_data = {}; std::vector output_data = { 11.689527f, 2.769937f, 7.05f, 8.35f, 11.69f, 2.77f, 7.05f, 8.35f, 14.276558f, 5.374159f, 9.65f, 10.95f, 14.289073f, 5.370287f, 9.65f, 10.95f}; bool use_special_quantize_parameter = true; bool is_unidirectional = false; bool use_float16 = false; RunQAttentionAll(input_data, weight_data, bias_data, mask_data, output_data, batch_size, sequence_length, hidden_size, number_of_heads, use_special_quantize_parameter, is_unidirectional, use_float16, input_hidden_size); } #ifndef ENABLE_TRAINING // Prepacking is enabled only on non-training builds TEST(QAttentionTest, SharedPrepackedWeights) { int batch_size = 1; int sequence_length = 2; int hidden_size = 4; int number_of_heads = 2; std::vector input_data = { 0.8f, -0.5f, 0.0f, 1.f, 0.5f, 0.2f, 0.3f, -0.6f}; std::vector weight_data = { 0.1f, -0.2f, 0.3f, 1.0f, 1.1f, 0.3f, 0.5f, 0.2f, 0.3f, -0.6f, 1.5f, 2.0f, 0.5f, 0.1f, 0.4f, 1.6f, 1.0f, 2.0f, 0.4f, 0.8f, 0.9f, 0.1f, -1.3f, 0.7f, 0.3f, 0.2f, 4.0f, 2.2f, 1.6f, 1.1f, 0.7f, 0.2f, 0.4f, 1.0f, 1.2f, 0.5f, 0.2f, 0.1f, 0.4f, 1.6f, 2.4f, 3.3f, 2.1f, 4.2f, 8.4f, 0.0f, 2.1f, 3.2f}; std::vector bias_data = { -0.5f, 0.6f, 1.2f, 2.1f, 0.5f, 0.7f, 0.2f, 1.2f, 0.5f, 0.4f, 0.3f, 1.2f}; std::vector mask_index_data = {2L}; std::vector output_data = { 3.1495983600616455f, 0.10843668878078461f, 4.25f, 5.6499996185302734f, 3.9696791172027588f, 0.073143675923347473f, 4.2499995231628418f, 5.6499991416931152f}; std::vector input_dims = {batch_size, sequence_length, hidden_size}; std::vector weights_dims = {hidden_size, 3 * hidden_size}; std::vector bias_dims = {3 * hidden_size}; std::vector mask_index_dims = {batch_size}; std::vector output_dims = {batch_size, sequence_length, hidden_size}; OpTester tester(""QAttention"", 1, onnxruntime::kMSDomain); tester.AddAttribute(""num_heads"", static_cast(number_of_heads)); tester.AddInput( ""input"", input_dims, QuantizeTestVector( input_data, quantization::Params(/*scale=*/0.1f, /*zero_point=*/128))); auto weight_data_converted_to_int = QuantizeTestVector( weight_data, quantization::Params(/*scale=*/0.1f, /*zero_point=*/128)); tester.AddInput(""weight"", weights_dims, weight_data_converted_to_int, /*is_initializer=*/true); // Trigger pre-packing tester.AddInput(""bias"", bias_dims, bias_data); tester.AddInput(""input_scale"", {1}, {0.1f}); tester.AddInput(""weight_scale"", {1}, {0.1f}); tester.AddOutput(""output"", output_dims, output_data); tester.AddInput(""mask_index"", mask_index_dims, mask_index_data); tester.AddInput(""input_zero_point"", {1}, {128}); tester.AddInput(""weight_zero_point"", {1}, {128}); OrtValue weight; Tensor::InitOrtValue(DataTypeImpl::GetType(), TensorShape(weights_dims), weight_data_converted_to_int.data(), OrtMemoryInfo(CPU, OrtAllocatorType::OrtDeviceAllocator), weight); SessionOptions so; // Set up weight as a shared initializer to be shared between sessions ASSERT_EQ(so.AddInitializer(""weight"", &weight), Status::OK()); // We want all sessions running using this OpTester to be able to share pre-packed weights if applicable tester.EnableSharingOfPrePackedWeightsAcrossSessions(); // Pre-packing is limited just to the CPU EP for now and we will only test the CPU EP // and we want to ensure that it is available in this build auto cpu_ep = []() -> std::vector> { std::vector> execution_providers; execution_providers.push_back(DefaultCpuExecutionProvider()); return execution_providers; }; size_t number_of_pre_packed_weights_counter_session_1 = 0; size_t number_of_shared_pre_packed_weights_counter = 0; // Session 1 { auto ep_vec = cpu_ep(); tester.Run(so, OpTester::ExpectResult::kExpectSuccess, """", {}, nullptr, &ep_vec, {}, &number_of_pre_packed_weights_counter_session_1, &number_of_shared_pre_packed_weights_counter); // Assert that no pre-packed weights have been shared thus far ASSERT_EQ(number_of_shared_pre_packed_weights_counter, static_cast(0)); } auto number_of_elements_in_shared_prepacked_buffers_container = tester.GetNumPrePackedWeightsShared(); // Assert that the number of elements in the shared container // is the same as the number of weights that have been pre-packed ASSERT_EQ(number_of_pre_packed_weights_counter_session_1, number_of_elements_in_shared_prepacked_buffers_container); // On some platforms/architectures MLAS may choose to not do any pre-packing and the number of elements // that have been pre-packed will be zero in which case we do not continue with the testing // of ""sharing"" of pre-packed weights as there are no pre-packed weights to be shared at all. if (number_of_pre_packed_weights_counter_session_1 == 0) return; // Session 2 { size_t number_of_pre_packed_weights_counter_session_2 = 0; auto ep_vec = cpu_ep(); tester.Run(so, OpTester::ExpectResult::kExpectSuccess, """", {}, nullptr, &ep_vec, {}, &number_of_pre_packed_weights_counter_session_2, &number_of_shared_pre_packed_weights_counter); // Assert that the same number of weights were pre-packed in both sessions ASSERT_EQ(number_of_pre_packed_weights_counter_session_1, number_of_pre_packed_weights_counter_session_2); // Assert that the number of pre-packed weights that were shared equals // the number of pre-packed weights in the second session ASSERT_EQ(number_of_pre_packed_weights_counter_session_2, static_cast(number_of_shared_pre_packed_weights_counter)); } } #endif } // namespace test } // namespace onnxruntime ",16278,True,3743.0894445213908,median "// Copyright 2008-present Contributors to the OpenImageIO project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/OpenImageIO/oiio #include #include #ifndef _WIN32 # include #endif #include #include ""imageviewer.h"" #include ""ivgl.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""ivutils.h"" namespace { inline bool IsSpecSrgb(const ImageSpec& spec) { return Strutil::iequals(spec.get_string_attribute(""oiio:ColorSpace""), ""sRGB""); } } // namespace // clang-format off static const char *s_file_filters = """" ""Image Files (*.bmp *.cin *.dcm *.dds *.dpx *.fits *.gif *.hdr *.ico *.iff "" ""*.jpg *.jpe *.jpeg *.jif *.jfif *.jfi *.jp2 *.j2k *.exr *.png *.pbm *.pgm "" ""*.ppm *.psd *.ptex *.rla *.sgi *.rgb *.rgba *.bw *.int *.inta *.pic *.tga "" ""*.tpic *.tif *.tiff *.tx *.env *.sm *.vsm *.vdb *.webp *.zfile);;"" ""BMP (*.bmp);;"" ""Cineon (*.cin);;"" ""Direct Draw Surface (*.dds);;"" ""DICOM (*.dcm);;"" ""DPX (*.dpx);;"" ""FITS (*.fits);;"" ""GIF (*.gif);;"" ""HDR/RGBE (*.hdr);;"" ""Icon (*.ico);;"" ""IFF (*.iff);;"" ""JPEG (*.jpg *.jpe *.jpeg *.jif *.jfif *.jfi);;"" ""JPEG-2000 (*.jp2 *.j2k);;"" ""OpenEXR (*.exr);;"" ""OpenVDB (*.vdb);;"" ""PhotoShop (*.psd);;"" ""Portable Network Graphics (*.png);;"" ""PNM / Netpbm (*.pbm *.pgm *.ppm);;"" ""Ptex (*.ptex);;"" ""RLA (*.rla);;"" ""SGI (*.sgi *.rgb *.rgba *.bw *.int *.inta);;"" ""Softimage PIC (*.pic);;"" ""Targa (*.tga *.tpic);;"" ""TIFF (*.tif *.tiff *.tx *.env *.sm *.vsm);;"" ""Webp (*.webp);;"" ""Zfile (*.zfile);;"" ""All Files (*)""; // clang-format on ImageViewer::ImageViewer() : infoWindow(NULL) , preferenceWindow(NULL) , darkPaletteBox(NULL) , m_current_image(-1) , m_current_channel(0) , m_color_mode(RGBA) , m_last_image(-1) , m_zoom(1) , m_fullscreen(false) , m_default_gamma(1) , m_darkPalette(false) { readSettings(false); float gam = Strutil::stof(Sysutil::getenv(""GAMMA"")); if (gam >= 0.1 && gam <= 5) m_default_gamma = gam; // FIXME -- would be nice to have a more nuanced approach to display // color space, in particular knowing whether the display is sRGB. // Also, some time in the future we may want a real 3D LUT for // ""film look"", etc. if (darkPalette()) m_palette = QPalette(Qt::darkGray); // darkGray? else m_palette = QPalette(); QApplication::setPalette(m_palette); // FIXME -- why not work? this->setPalette(m_palette); slideTimer = new QTimer(); slideDuration_ms = 5000; slide_loop = true; glwin = new IvGL(this, *this); glwin->setPalette(m_palette); glwin->resize(m_default_width, m_default_height); setCentralWidget(glwin); createActions(); createMenus(); createToolBars(); createStatusBar(); readSettings(); setWindowTitle(tr(""Image Viewer"")); resize(m_default_width, m_default_height); // setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored); } ImageViewer::~ImageViewer() { for (auto i : m_images) delete i; } void ImageViewer::closeEvent(QCloseEvent*) { writeSettings(); } void ImageViewer::createActions() { openAct = new QAction(tr(""&Open...""), this); openAct->setShortcut(tr(""Ctrl+O"")); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); for (auto& i : openRecentAct) { i = new QAction(this); i->setVisible(false); connect(i, SIGNAL(triggered()), this, SLOT(openRecentFile())); } reloadAct = new QAction(tr(""&Reload image""), this); reloadAct->setShortcut(tr(""Ctrl+R"")); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); closeImgAct = new QAction(tr(""&Close Image""), this); closeImgAct->setShortcut(tr(""Ctrl+W"")); connect(closeImgAct, SIGNAL(triggered()), this, SLOT(closeImg())); saveAsAct = new QAction(tr(""&Save As...""), this); saveAsAct->setShortcut(tr(""Ctrl+S"")); connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); saveWindowAsAct = new QAction(tr(""Save Window As...""), this); connect(saveWindowAsAct, SIGNAL(triggered()), this, SLOT(saveWindowAs())); saveSelectionAsAct = new QAction(tr(""Save Selection As...""), this); connect(saveSelectionAsAct, SIGNAL(triggered()), this, SLOT(saveSelectionAs())); printAct = new QAction(tr(""&Print...""), this); printAct->setShortcut(tr(""Ctrl+P"")); printAct->setEnabled(false); connect(printAct, SIGNAL(triggered()), this, SLOT(print())); deleteCurrentImageAct = new QAction(tr(""&Delete from disk""), this); deleteCurrentImageAct->setShortcut(tr(""Delete"")); connect(deleteCurrentImageAct, SIGNAL(triggered()), this, SLOT(deleteCurrentImage())); editPreferencesAct = new QAction(tr(""&Preferences...""), this); editPreferencesAct->setShortcut(tr(""Ctrl+,"")); editPreferencesAct->setEnabled(true); connect(editPreferencesAct, SIGNAL(triggered()), this, SLOT(editPreferences())); exitAct = new QAction(tr(""E&xit""), this); exitAct->setShortcut(tr(""Ctrl+Q"")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); exposurePlusOneTenthStopAct = new QAction(tr(""Exposure +1/10 stop""), this); exposurePlusOneTenthStopAct->setShortcut(tr(""]"")); connect(exposurePlusOneTenthStopAct, SIGNAL(triggered()), this, SLOT(exposurePlusOneTenthStop())); exposurePlusOneHalfStopAct = new QAction(tr(""Exposure +1/2 stop""), this); exposurePlusOneHalfStopAct->setShortcut(tr(""}"")); connect(exposurePlusOneHalfStopAct, SIGNAL(triggered()), this, SLOT(exposurePlusOneHalfStop())); exposureMinusOneTenthStopAct = new QAction(tr(""Exposure -1/10 stop""), this); exposureMinusOneTenthStopAct->setShortcut(tr(""["")); connect(exposureMinusOneTenthStopAct, SIGNAL(triggered()), this, SLOT(exposureMinusOneTenthStop())); exposureMinusOneHalfStopAct = new QAction(tr(""Exposure -1/2 stop""), this); exposureMinusOneHalfStopAct->setShortcut(tr(""{"")); connect(exposureMinusOneHalfStopAct, SIGNAL(triggered()), this, SLOT(exposureMinusOneHalfStop())); gammaPlusAct = new QAction(tr(""Gamma +0.1""), this); gammaPlusAct->setShortcut(tr("")"")); connect(gammaPlusAct, SIGNAL(triggered()), this, SLOT(gammaPlus())); gammaMinusAct = new QAction(tr(""Gamma -0.1""), this); gammaMinusAct->setShortcut(tr(""("")); connect(gammaMinusAct, SIGNAL(triggered()), this, SLOT(gammaMinus())); viewChannelFullAct = new QAction(tr(""Full Color""), this); viewChannelFullAct->setShortcut(tr(""c"")); viewChannelFullAct->setCheckable(true); viewChannelFullAct->setChecked(true); connect(viewChannelFullAct, SIGNAL(triggered()), this, SLOT(viewChannelFull())); viewChannelRedAct = new QAction(tr(""Red""), this); viewChannelRedAct->setShortcut(tr(""r"")); viewChannelRedAct->setCheckable(true); connect(viewChannelRedAct, SIGNAL(triggered()), this, SLOT(viewChannelRed())); viewChannelGreenAct = new QAction(tr(""Green""), this); viewChannelGreenAct->setShortcut(tr(""g"")); viewChannelGreenAct->setCheckable(true); connect(viewChannelGreenAct, SIGNAL(triggered()), this, SLOT(viewChannelGreen())); viewChannelBlueAct = new QAction(tr(""Blue""), this); viewChannelBlueAct->setShortcut(tr(""b"")); viewChannelBlueAct->setCheckable(true); connect(viewChannelBlueAct, SIGNAL(triggered()), this, SLOT(viewChannelBlue())); viewChannelAlphaAct = new QAction(tr(""Alpha""), this); viewChannelAlphaAct->setShortcut(tr(""a"")); viewChannelAlphaAct->setCheckable(true); connect(viewChannelAlphaAct, SIGNAL(triggered()), this, SLOT(viewChannelAlpha())); viewColorLumAct = new QAction(tr(""Luminance""), this); viewColorLumAct->setShortcut(tr(""l"")); viewColorLumAct->setCheckable(true); connect(viewColorLumAct, SIGNAL(triggered()), this, SLOT(viewChannelLuminance())); viewColorRGBAAct = new QAction(tr(""RGBA""), this); //viewColorRGBAAct->setShortcut (tr(""Ctrl+c"")); viewColorRGBAAct->setCheckable(true); viewColorRGBAAct->setChecked(true); connect(viewColorRGBAAct, SIGNAL(triggered()), this, SLOT(viewColorRGBA())); viewColorRGBAct = new QAction(tr(""RGB""), this); //viewColorRGBAct->setShortcut (tr(""Ctrl+a"")); viewColorRGBAct->setCheckable(true); connect(viewColorRGBAct, SIGNAL(triggered()), this, SLOT(viewColorRGB())); viewColor1ChAct = new QAction(tr(""Single channel""), this); viewColor1ChAct->setShortcut(tr(""1"")); viewColor1ChAct->setCheckable(true); connect(viewColor1ChAct, SIGNAL(triggered()), this, SLOT(viewColor1Ch())); viewColorHeatmapAct = new QAction(tr(""Single channel (Heatmap)""), this); viewColorHeatmapAct->setShortcut(tr(""h"")); viewColorHeatmapAct->setCheckable(true); connect(viewColorHeatmapAct, SIGNAL(triggered()), this, SLOT(viewColorHeatmap())); viewChannelPrevAct = new QAction(tr(""Prev Channel""), this); viewChannelPrevAct->setShortcut(tr("","")); connect(viewChannelPrevAct, SIGNAL(triggered()), this, SLOT(viewChannelPrev())); viewChannelNextAct = new QAction(tr(""Next Channel""), this); viewChannelNextAct->setShortcut(tr(""."")); connect(viewChannelNextAct, SIGNAL(triggered()), this, SLOT(viewChannelNext())); viewSubimagePrevAct = new QAction(tr(""Prev Subimage""), this); viewSubimagePrevAct->setShortcut(tr(""<"")); connect(viewSubimagePrevAct, SIGNAL(triggered()), this, SLOT(viewSubimagePrev())); viewSubimageNextAct = new QAction(tr(""Next Subimage""), this); viewSubimageNextAct->setShortcut(tr("">"")); connect(viewSubimageNextAct, SIGNAL(triggered()), this, SLOT(viewSubimageNext())); zoomInAct = new QAction(tr(""Zoom &In""), this); zoomInAct->setShortcut(tr(""Ctrl++"")); connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn())); zoomOutAct = new QAction(tr(""Zoom &Out""), this); zoomOutAct->setShortcut(tr(""Ctrl+-"")); connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut())); normalSizeAct = new QAction(tr(""&Normal Size (1:1)""), this); normalSizeAct->setShortcut(tr(""Ctrl+0"")); connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize())); fitWindowToImageAct = new QAction(tr(""&Fit Window to Image""), this); fitWindowToImageAct->setShortcut(tr(""f"")); connect(fitWindowToImageAct, SIGNAL(triggered()), this, SLOT(fitWindowToImage())); fitImageToWindowAct = new QAction(tr(""Fit Image to Window""), this); // fitImageToWindowAct->setEnabled(false); fitImageToWindowAct->setCheckable(true); fitImageToWindowAct->setShortcut(tr(""Alt+f"")); connect(fitImageToWindowAct, SIGNAL(triggered()), this, SLOT(fitImageToWindow())); fullScreenAct = new QAction(tr(""Full screen""), this); // fullScreenAct->setEnabled(false); // fullScreenAct->setCheckable(true); fullScreenAct->setShortcut(tr(""Ctrl+f"")); connect(fullScreenAct, SIGNAL(triggered()), this, SLOT(fullScreenToggle())); aboutAct = new QAction(tr(""&About""), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); prevImageAct = new QAction(tr(""Previous Image""), this); prevImageAct->setShortcut(tr(""PgUp"")); // prevImageAct->setEnabled(true); connect(prevImageAct, SIGNAL(triggered()), this, SLOT(prevImage())); nextImageAct = new QAction(tr(""Next Image""), this); nextImageAct->setShortcut(tr(""PgDown"")); // nextImageAct->setEnabled(true); connect(nextImageAct, SIGNAL(triggered()), this, SLOT(nextImage())); toggleImageAct = new QAction(tr(""Toggle image""), this); toggleImageAct->setShortcut(tr(""T"")); // toggleImageAct->setEnabled(true); connect(toggleImageAct, SIGNAL(triggered()), this, SLOT(toggleImage())); slideShowAct = new QAction(tr(""Start Slide Show""), this); connect(slideShowAct, SIGNAL(triggered()), this, SLOT(slideShow())); slideLoopAct = new QAction(tr(""Loop slide show""), this); slideLoopAct->setCheckable(true); slideLoopAct->setChecked(true); connect(slideLoopAct, SIGNAL(triggered()), this, SLOT(slideLoop())); slideNoLoopAct = new QAction(tr(""Stop at end""), this); slideNoLoopAct->setCheckable(true); connect(slideNoLoopAct, SIGNAL(triggered()), this, SLOT(slideNoLoop())); sortByNameAct = new QAction(tr(""By Name""), this); connect(sortByNameAct, SIGNAL(triggered()), this, SLOT(sortByName())); sortByPathAct = new QAction(tr(""By File Path""), this); connect(sortByPathAct, SIGNAL(triggered()), this, SLOT(sortByPath())); sortByImageDateAct = new QAction(tr(""By Image Date""), this); connect(sortByImageDateAct, SIGNAL(triggered()), this, SLOT(sortByImageDate())); sortByFileDateAct = new QAction(tr(""By File Date""), this); connect(sortByFileDateAct, SIGNAL(triggered()), this, SLOT(sortByFileDate())); sortReverseAct = new QAction(tr(""Reverse current order""), this); connect(sortReverseAct, SIGNAL(triggered()), this, SLOT(sortReverse())); showInfoWindowAct = new QAction(tr(""&Image info...""), this); showInfoWindowAct->setShortcut(tr(""Ctrl+I"")); // showInfoWindowAct->setEnabled(true); connect(showInfoWindowAct, SIGNAL(triggered()), this, SLOT(showInfoWindow())); showPixelviewWindowAct = new QAction(tr(""&Pixel closeup view...""), this); showPixelviewWindowAct->setCheckable(true); showPixelviewWindowAct->setShortcut(tr(""P"")); connect(showPixelviewWindowAct, SIGNAL(triggered()), this, SLOT(showPixelviewWindow())); pixelviewFollowsMouseBox = new QCheckBox(tr(""Pixel view follows mouse"")); pixelviewFollowsMouseBox->setChecked(false); linearInterpolationBox = new QCheckBox(tr(""Linear interpolation"")); linearInterpolationBox->setChecked(true); darkPaletteBox = new QCheckBox(tr(""Dark palette"")); darkPaletteBox->setChecked(true); autoMipmap = new QCheckBox(tr(""Generate mipmaps (requires restart)"")); autoMipmap->setChecked(false); maxMemoryICLabel = new QLabel( tr(""Image Cache max memory (requires restart)"")); maxMemoryIC = new QSpinBox(); if (sizeof(void*) == 4) maxMemoryIC->setRange(128, 2048); //2GB is enough for 32 bit machines else maxMemoryIC->setRange(128, 8192); //8GB probably ok for 64 bit maxMemoryIC->setSingleStep(64); maxMemoryIC->setSuffix("" MB""); slideShowDurationLabel = new QLabel(tr(""Slide Show delay"")); slideShowDuration = new QSpinBox(); slideShowDuration->setRange(1, 3600); slideShowDuration->setSingleStep(1); slideShowDuration->setSuffix("" s""); slideShowDuration->setAccelerated(true); connect(slideShowDuration, SIGNAL(valueChanged(int)), this, SLOT(setSlideShowDuration(int))); } void ImageViewer::createMenus() { openRecentMenu = new QMenu(tr(""Open recent...""), this); for (auto& i : openRecentAct) openRecentMenu->addAction(i); fileMenu = new QMenu(tr(""&File""), this); fileMenu->addAction(openAct); fileMenu->addMenu(openRecentMenu); fileMenu->addAction(reloadAct); fileMenu->addAction(closeImgAct); fileMenu->addSeparator(); fileMenu->addAction(saveAsAct); fileMenu->addAction(saveWindowAsAct); fileMenu->addAction(saveSelectionAsAct); fileMenu->addSeparator(); fileMenu->addAction(printAct); fileMenu->addAction(deleteCurrentImageAct); fileMenu->addSeparator(); fileMenu->addAction(editPreferencesAct); fileMenu->addAction(exitAct); menuBar()->addMenu(fileMenu); // Copy // Paste // Clear selection // radio: prioritize selection, crop selection expgamMenu = new QMenu(tr(""Exposure/gamma"")); // submenu expgamMenu->addAction(exposureMinusOneHalfStopAct); expgamMenu->addAction(exposureMinusOneTenthStopAct); expgamMenu->addAction(exposurePlusOneHalfStopAct); expgamMenu->addAction(exposurePlusOneTenthStopAct); expgamMenu->addAction(gammaMinusAct); expgamMenu->addAction(gammaPlusAct); // imageMenu = new QMenu(tr(""&Image""), this); // menuBar()->addMenu (imageMenu); slideMenu = new QMenu(tr(""Slide Show"")); slideMenu->addAction(slideShowAct); slideMenu->addAction(slideLoopAct); slideMenu->addAction(slideNoLoopAct); sortMenu = new QMenu(tr(""Sort"")); sortMenu->addAction(sortByNameAct); sortMenu->addAction(sortByPathAct); sortMenu->addAction(sortByImageDateAct); sortMenu->addAction(sortByFileDateAct); sortMenu->addAction(sortReverseAct); channelMenu = new QMenu(tr(""Channels"")); // Color mode: true, random, falsegrgbacCrgR channelMenu->addAction(viewChannelFullAct); channelMenu->addAction(viewChannelRedAct); channelMenu->addAction(viewChannelGreenAct); channelMenu->addAction(viewChannelBlueAct); channelMenu->addAction(viewChannelAlphaAct); channelMenu->addAction(viewChannelPrevAct); channelMenu->addAction(viewChannelNextAct); colormodeMenu = new QMenu(tr(""Color mode"")); colormodeMenu->addAction(viewColorRGBAAct); colormodeMenu->addAction(viewColorRGBAct); colormodeMenu->addAction(viewColor1ChAct); colormodeMenu->addAction(viewColorLumAct); colormodeMenu->addAction(viewColorHeatmapAct); viewMenu = new QMenu(tr(""&View""), this); viewMenu->addAction(prevImageAct); viewMenu->addAction(nextImageAct); viewMenu->addAction(toggleImageAct); viewMenu->addSeparator(); viewMenu->addAction(zoomInAct); viewMenu->addAction(zoomOutAct); viewMenu->addAction(normalSizeAct); viewMenu->addAction(fitWindowToImageAct); viewMenu->addAction(fitImageToWindowAct); viewMenu->addAction(fullScreenAct); viewMenu->addSeparator(); viewMenu->addAction(viewSubimagePrevAct); viewMenu->addAction(viewSubimageNextAct); viewMenu->addMenu(channelMenu); viewMenu->addMenu(colormodeMenu); viewMenu->addMenu(expgamMenu); menuBar()->addMenu(viewMenu); // Full screen mode // prev subimage <, next subimage > // fg/bg image... toolsMenu = new QMenu(tr(""&Tools""), this); // Mode: select, zoom, pan, wipe toolsMenu->addAction(showInfoWindowAct); toolsMenu->addAction(showPixelviewWindowAct); toolsMenu->addMenu(slideMenu); toolsMenu->addMenu(sortMenu); // Menus, toolbars, & status // Annotate // [check] overwrite render // connect renderer // kill renderer // store render // Playback: forward, reverse, faster, slower, loop/pingpong menuBar()->addMenu(toolsMenu); helpMenu = new QMenu(tr(""&Help""), this); helpMenu->addAction(aboutAct); menuBar()->addMenu(helpMenu); // Bring up user's guide } void ImageViewer::createToolBars() { #if 0 fileToolBar = addToolBar(tr(""File"")); fileToolBar->addAction(newAct); fileToolBar->addAction(openAct); fileToolBar->addAction(saveAct); editToolBar = addToolBar(tr(""Edit"")); editToolBar->addAction(cutAct); editToolBar->addAction(copyAct); editToolBar->addAction(pasteAct); #endif } void ImageViewer::createStatusBar() { statusImgInfo = new QLabel; statusBar()->addWidget(statusImgInfo); statusViewInfo = new QLabel; statusBar()->addWidget(statusViewInfo); statusProgress = new QProgressBar; statusProgress->setRange(0, 100); statusProgress->reset(); statusBar()->addWidget(statusProgress); mouseModeComboBox = new QComboBox; mouseModeComboBox->addItem(tr(""Zoom"")); mouseModeComboBox->addItem(tr(""Pan"")); mouseModeComboBox->addItem(tr(""Wipe"")); mouseModeComboBox->addItem(tr(""Select"")); mouseModeComboBox->addItem(tr(""Annotate"")); // Note: the order of the above MUST match the order of enum MouseMode statusBar()->addWidget(mouseModeComboBox); mouseModeComboBox->hide(); } void ImageViewer::readSettings(bool ui_is_set_up) { QSettings settings(""OpenImageIO"", ""iv""); m_darkPalette = settings.value(""darkPalette"").toBool(); if (!ui_is_set_up) return; pixelviewFollowsMouseBox->setChecked( settings.value(""pixelviewFollowsMouse"").toBool()); linearInterpolationBox->setChecked( settings.value(""linearInterpolation"").toBool()); darkPaletteBox->setChecked(settings.value(""darkPalette"").toBool()); QStringList recent = settings.value(""RecentFiles"").toStringList(); for (auto&& s : recent) addRecentFile(s.toStdString()); updateRecentFilesMenu(); // only safe because it's called after menu setup autoMipmap->setChecked(settings.value(""autoMipmap"", false).toBool()); if (sizeof(void*) == 4) // 32 bit or 64? maxMemoryIC->setValue(settings.value(""maxMemoryIC"", 512).toInt()); else maxMemoryIC->setValue(settings.value(""maxMemoryIC"", 2048).toInt()); slideShowDuration->setValue( settings.value(""slideShowDuration"", 10).toInt()); ImageCache* imagecache = ImageCache::create(true); imagecache->attribute(""automip"", autoMipmap->isChecked()); imagecache->attribute(""max_memory_MB"", (float)maxMemoryIC->value()); } void ImageViewer::writeSettings() { QSettings settings(""OpenImageIO"", ""iv""); settings.setValue(""pixelviewFollowsMouse"", pixelviewFollowsMouseBox->isChecked()); settings.setValue(""linearInterpolation"", linearInterpolationBox->isChecked()); settings.setValue(""darkPalette"", darkPaletteBox->isChecked()); settings.setValue(""autoMipmap"", autoMipmap->isChecked()); settings.setValue(""maxMemoryIC"", maxMemoryIC->value()); settings.setValue(""slideShowDuration"", slideShowDuration->value()); QStringList recent; for (auto&& s : m_recent_files) recent.push_front(QString(s.c_str())); settings.setValue(""RecentFiles"", recent); } bool image_progress_callback(void* opaque, float done) { ImageViewer* viewer = (ImageViewer*)opaque; viewer->statusProgress->setValue((int)(done * 100)); QApplication::processEvents(); return false; } void ImageViewer::open() { static QString openPath = QDir::currentPath(); QFileDialog dialog(NULL, tr(""Open File(s)""), openPath, tr(s_file_filters)); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setFileMode(QFileDialog::ExistingFiles); if (!dialog.exec()) return; openPath = dialog.directory().path(); QStringList names = dialog.selectedFiles(); int old_lastimage = m_images.size() - 1; for (auto& name : names) { std::string filename = name.toUtf8().data(); if (filename.empty()) continue; add_image(filename); // int n = m_images.size()-1; // IvImage *newimage = m_images[n]; // newimage->read_iv (0, false, image_progress_callback, this); } if (old_lastimage >= 0) { // Otherwise, add_image already did this for us. current_image(old_lastimage + 1); fitWindowToImage(true, true); } } void ImageViewer::openRecentFile() { QAction* action = qobject_cast(sender()); if (action) { std::string filename = action->data().toString().toStdString(); // If it's an image we already have loaded, just switch to it // (and reload) rather than loading a second copy. for (size_t i = 0; i < m_images.size(); ++i) { if (m_images[i]->name() == filename) { current_image(i); reload(); return; } } // It's not an image we already have loaded add_image(filename); if (m_images.size() > 1) { // Otherwise, add_image already did this for us. current_image(m_images.size() - 1); fitWindowToImage(true, true); } } } void ImageViewer::addRecentFile(const std::string& name) { removeRecentFile(name); m_recent_files.insert(m_recent_files.begin(), name); if (m_recent_files.size() > MaxRecentFiles) m_recent_files.resize(MaxRecentFiles); } void ImageViewer::removeRecentFile(const std::string& name) { for (size_t i = 0; i < m_recent_files.size(); ++i) { if (m_recent_files[i] == name) { m_recent_files.erase(m_recent_files.begin() + i); --i; } } } void ImageViewer::updateRecentFilesMenu() { for (size_t i = 0; i < MaxRecentFiles; ++i) { if (i < m_recent_files.size()) { std::string name = Filesystem::filename(m_recent_files[i]); openRecentAct[i]->setText(QString::fromStdString(name)); openRecentAct[i]->setData(m_recent_files[i].c_str()); openRecentAct[i]->setVisible(true); } else { openRecentAct[i]->setVisible(false); } } } void ImageViewer::reload() { if (m_images.empty()) return; IvImage* newimage = m_images[m_current_image]; newimage->invalidate(); //glwin->trigger_redraw (); displayCurrentImage(); } void ImageViewer::add_image(const std::string& filename) { if (filename.empty()) return; IvImage* newimage = nullptr; if (rawcolor()) { ImageSpec config; config.attribute(""oiio:RawColor"", 1); newimage = new IvImage(filename, &config); } else { newimage = new IvImage(filename); } newimage->gamma(m_default_gamma); m_images.push_back(newimage); addRecentFile(filename); updateRecentFilesMenu(); #if 0 if (getspec) { if (! newimage->init_spec (filename)) { QMessageBox::information (this, tr(""iv Image Viewer""), tr(""%1"").arg(newimage->geterror().c_str())); } else { std::cerr << ""Added image "" << filename << "": "" << newimage->spec().width << "" x "" << newimage->spec().height << ""\\n""; } return; } #endif if (m_images.size() == 1) { // If this is the first image, resize to fit it displayCurrentImage(); fitWindowToImage(true, true); } } void ImageViewer::saveAs() { IvImage* img = cur(); if (!img) return; QString name; name = QFileDialog::getSaveFileName(this, tr(""Save Image""), QString(img->uname().c_str()), tr(s_file_filters)); if (name.isEmpty()) return; bool ok = img->write(name.toStdString(), TypeUnknown, """", image_progress_callback, this); if (!ok) { std::cerr << ""Save failed: "" << img->geterror() << ""\\n""; } } void ImageViewer::saveWindowAs() { IvImage* img = cur(); if (!img) return; QString name; name = QFileDialog::getSaveFileName(this, tr(""Save Window""), QString(img->uname().c_str())); if (name.isEmpty()) return; img->write(name.toStdString(), TypeUnknown, """", image_progress_callback, this); } void ImageViewer::saveSelectionAs() { IvImage* img = cur(); if (!img) return; QString name; name = QFileDialog::getSaveFileName(this, tr(""Save Selection""), QString(img->uname().c_str())); if (name.isEmpty()) return; img->write(name.toStdString(), TypeUnknown, """", image_progress_callback, this); } void ImageViewer::updateTitle() { IvImage* img = cur(); if (!img) { setWindowTitle(tr(""iv Image Viewer (no image loaded)"")); return; } std::string message; message = Strutil::sprintf(""%s - iv Image Viewer"", img->name()); setWindowTitle(QString::fromLocal8Bit(message.c_str())); } void ImageViewer::updateStatusBar() { const ImageSpec* spec = curspec(); if (!spec) { statusImgInfo->setText(tr(""No image loaded"")); statusViewInfo->setText(tr("""")); return; } std::string message; message = Strutil::sprintf(""(%d/%d) : "", m_current_image + 1, (int)m_images.size()); message += cur()->shortinfo(); statusImgInfo->setText(message.c_str()); message.clear(); switch (m_color_mode) { case RGBA: message = Strutil::sprintf(""RGBA (%d-%d)"", m_current_channel, m_current_channel + 3); break; case RGB: message = Strutil::sprintf(""RGB (%d-%d)"", m_current_channel, m_current_channel + 2); break; case LUMINANCE: message = Strutil::sprintf(""Lum (%d-%d)"", m_current_channel, m_current_channel + 2); break; case HEATMAP: message = ""Heat ""; case SINGLE_CHANNEL: if ((int)spec->channelnames.size() > m_current_channel && spec->channelnames[m_current_channel].size()) message += spec->channelnames[m_current_channel]; else if (m_color_mode == HEATMAP) { message += Strutil::sprintf(""%d"", m_current_channel); } else { message = Strutil::sprintf(""chan %d"", m_current_channel); } break; } message += Strutil::sprintf("" %g:%g exp %+.1f gam %.2f"", zoom() >= 1 ? zoom() : 1.0f, zoom() >= 1 ? 1.0f : 1.0f / zoom(), cur()->exposure(), cur()->gamma()); if (cur()->nsubimages() > 1) { if (cur()->auto_subimage()) { message += Strutil::sprintf("" subimg AUTO (%d/%d)"", cur()->subimage() + 1, cur()->nsubimages()); } else { message += Strutil::sprintf("" subimg %d/%d"", cur()->subimage() + 1, cur()->nsubimages()); } } if (cur()->nmiplevels() > 1) { message += Strutil::sprintf("" MIP %d/%d"", cur()->miplevel() + 1, cur()->nmiplevels()); } statusViewInfo->setText(message.c_str()); // tr(""iv status"")); } bool ImageViewer::loadCurrentImage(int subimage, int miplevel) { if (m_current_image < 0 || m_current_image >= (int)m_images.size()) { m_current_image = 0; } IvImage* img = cur(); if (img) { // We need the spec available to compare the image format with // opengl's capabilities. if (!img->init_spec(img->name(), subimage, miplevel)) { statusImgInfo->setText( tr(""Could not display image: %1."").arg(img->uname().c_str())); statusViewInfo->setText(tr("""")); return false; } // Used to check whether we'll need to do adjustments in the // CPU. If true, images should be loaded as UINT8. bool allow_transforms = false; bool srgb_transform = false; // By default, we try to load into OpenGL with the same format, TypeDesc read_format = TypeDesc::UNKNOWN; const ImageSpec& image_spec = img->spec(); if (image_spec.format.basetype == TypeDesc::DOUBLE) { // AFAIK, OpenGL doesn't support 64-bit floats as pixel size. read_format = TypeDesc::FLOAT; } if (glwin->is_glsl_capable()) { if (image_spec.format.basetype == TypeDesc::HALF && !glwin->is_half_capable()) { //std::cerr << ""Loading HALF-FLOAT as FLOAT\\n""; read_format = TypeDesc::FLOAT; } if (IsSpecSrgb(image_spec) && !glwin->is_srgb_capable()) { // If the image is in sRGB, but OpenGL can't load sRGB textures then // we'll need to do the transformation on the CPU after loading the // image. We (so far) can only do this with UINT8 images, so make // sure that it gets loaded in this format. //std::cerr << ""Loading as UINT8 to do sRGB\\n""; read_format = TypeDesc::UINT8; srgb_transform = true; allow_transforms = true; } } else { //std::cerr << ""Loading as UINT8\\n""; read_format = TypeDesc::UINT8; allow_transforms = true; if (IsSpecSrgb(image_spec) && !glwin->is_srgb_capable()) srgb_transform = true; } // FIXME: This actually won't work since the ImageCacheFile has already // been created when we did the init_spec. // Check whether IvGL recommends generating mipmaps for this image. //ImageCache *imagecache = ImageCache::create (true); //if (glwin->is_too_big (img) && autoMipmap->isChecked ()) { // imagecache->attribute (""automip"", 1); //} else { // imagecache->attribute (""automip"", 0); //} // Read the image from disk or from the ImageCache if available. if (img->read_iv(subimage, miplevel, false, read_format, image_progress_callback, this, allow_transforms)) { // The image was read successfully. // Check if we've got to do sRGB to linear (ie, when not supported // by OpenGL). // Do the first pixel transform to fill-in the secondary image // buffer. if (allow_transforms) { img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); } return true; } else { statusImgInfo->setText( tr(""Could not display image: %1."").arg(img->uname().c_str())); statusViewInfo->setText(tr("""")); return false; } } return false; } void ImageViewer::displayCurrentImage(bool update) { if (m_current_image < 0 || m_current_image >= (int)m_images.size()) m_current_image = 0; IvImage* img = cur(); if (img) { if (!img->image_valid()) { bool load_result = false; statusViewInfo->hide(); statusProgress->show(); load_result = loadCurrentImage(std::max(0, img->subimage()), std::max(0, img->miplevel())); statusProgress->hide(); statusViewInfo->show(); if (load_result) { update = true; } else { return; } } } else { m_current_image = m_last_image = -1; ((QOpenGLWidget*)(glwin))->update(); } if (update) { glwin->update(); } float z = zoom(); if (fitImageToWindowAct->isChecked()) z = zoom_needed_to_fit(glwin->width(), glwin->height()); zoom(z); // glwin->trigger_redraw (); updateTitle(); updateStatusBar(); if (infoWindow) infoWindow->update(img); // printAct->setEnabled(true); // fitImageToWindowAct->setEnabled(true); // fullScreenAct->setEnabled(true); updateActions(); } void ImageViewer::deleteCurrentImage() { IvImage* img = cur(); if (img) { const char* filename = img->uname().c_str(); QString message(""Are you sure you want to remove ""); message = message + QString(filename) + QString("" file from disk?""); QMessageBox::StandardButton button; button = QMessageBox::question(this, """", message, QMessageBox::Yes | QMessageBox::No); if (button == QMessageBox::Yes) { closeImg(); int r = remove(filename); if (r) QMessageBox::information(this, """", ""Unable to delete file""); } } } void ImageViewer::current_image(int newimage) { #ifndef NDEBUG Timer swap_image_time; swap_image_time.start(); #endif if (m_images.empty() || newimage < 0 || newimage >= (int)m_images.size()) m_current_image = 0; if (m_current_image != newimage) { m_last_image = (m_current_image >= 0) ? m_current_image : newimage; m_current_image = newimage; displayCurrentImage(); } else { displayCurrentImage(false); } #ifndef NDEBUG swap_image_time.stop(); std::cerr << ""Current Image change elapsed time: "" << swap_image_time() << "" seconds \\n""; #endif } void ImageViewer::prevImage() { if (m_images.empty()) return; if (m_current_image == 0) current_image((int)m_images.size() - 1); else current_image(current_image() - 1); } void ImageViewer::nextImage() { if (m_images.empty()) return; if (m_current_image >= (int)m_images.size() - 1) current_image(0); else current_image(current_image() + 1); } void ImageViewer::toggleImage() { current_image(m_last_image); } void ImageViewer::exposureMinusOneTenthStop() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->exposure(img->exposure() - 0.1); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::exposureMinusOneHalfStop() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->exposure(img->exposure() - 0.5); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::exposurePlusOneTenthStop() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->exposure(img->exposure() + 0.1); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::exposurePlusOneHalfStop() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->exposure(img->exposure() + 0.5); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::gammaMinus() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->gamma(img->gamma() - 0.05); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::gammaPlus() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->gamma(img->gamma() + 0.05); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::slide(long /*t*/, bool b) { slideLoopAct->setChecked(b == true); slideNoLoopAct->setChecked(b == false); } void ImageViewer::viewChannel(int c, COLOR_MODE colormode) { #ifndef NDEBUG Timer change_channel_time; change_channel_time.start(); #endif if (m_current_channel != c || colormode != m_color_mode) { bool update = true; if (!glwin->is_glsl_capable()) { IvImage* img = cur(); if (img) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)colormode, c); } } else { // FIXME: There are even more chances to avoid updating the textures // if we can keep trac of which channels are in the texture. if (m_current_channel == c) { if (m_color_mode == SINGLE_CHANNEL || m_color_mode == HEATMAP) { if (colormode == HEATMAP || colormode == SINGLE_CHANNEL) update = false; } else if (m_color_mode == RGB || m_color_mode == LUMINANCE) { if (colormode == RGB || colormode == LUMINANCE) update = false; } } } m_current_channel = c; m_color_mode = colormode; displayCurrentImage(update); viewChannelFullAct->setChecked(c == 0 && m_color_mode == RGBA); viewChannelRedAct->setChecked(c == 0 && m_color_mode == SINGLE_CHANNEL); viewChannelGreenAct->setChecked(c == 1 && m_color_mode == SINGLE_CHANNEL); viewChannelBlueAct->setChecked(c == 2 && m_color_mode == SINGLE_CHANNEL); viewChannelAlphaAct->setChecked(c == 3 && m_color_mode == SINGLE_CHANNEL); viewColorLumAct->setChecked(m_color_mode == LUMINANCE); viewColorRGBAAct->setChecked(m_color_mode == RGBA); viewColorRGBAct->setChecked(m_color_mode == RGB); viewColor1ChAct->setChecked(m_color_mode == SINGLE_CHANNEL); viewColorHeatmapAct->setChecked(m_color_mode == HEATMAP); } #ifndef NDEBUG change_channel_time.stop(); std::cerr << ""Change channel elapsed time: "" << change_channel_time() << "" seconds \\n""; #endif } void ImageViewer::slideImages() { if (m_images.empty()) return; if (m_current_image >= (int)m_images.size() - 1) { if (slide_loop == true) current_image(0); else { slideTimer->stop(); disconnect(slideTimer, 0, 0, 0); } } else current_image(current_image() + 1); } void ImageViewer::slideShow() { fullScreenToggle(); connect(slideTimer, SIGNAL(timeout()), this, SLOT(slideImages())); slideTimer->start(slideDuration_ms); updateActions(); } void ImageViewer::slideLoop() { slide_loop = true; slide(slideDuration_ms, slide_loop); } void ImageViewer::slideNoLoop() { slide_loop = false; slide(slideDuration_ms, slide_loop); } void ImageViewer::setSlideShowDuration(int seconds) { slideDuration_ms = seconds * 1000; } static bool compName(IvImage* first, IvImage* second) { std::string firstFile = Filesystem::filename(first->name()); std::string secondFile = Filesystem::filename(second->name()); return (firstFile.compare(secondFile) < 0); } void ImageViewer::sortByName() { int numImg = m_images.size(); if (numImg < 2) return; std::sort(m_images.begin(), m_images.end(), &compName); current_image(0); displayCurrentImage(); // updateActions(); } static bool compPath(IvImage* first, IvImage* second) { std::string firstFile = first->name(); std::string secondFile = second->name(); return (firstFile.compare(secondFile) < 0); } void ImageViewer::sortByPath() { int numImg = m_images.size(); if (numImg < 2) return; std::sort(m_images.begin(), m_images.end(), &compPath); current_image(0); displayCurrentImage(); // updateActions(); } static bool DateTime_to_time_t(string_view datetime, time_t& timet) { int year, month, day, hour, min, sec; if (!Strutil::scan_datetime(datetime, year, month, day, hour, min, sec)) return false; // print(""{}:{}:{} {}:{}:{}\\n"", year, month, day, hour, min, sec); struct tm tmtime; time_t now; Sysutil::get_local_time(&now, &tmtime); // fill in defaults tmtime.tm_sec = sec; tmtime.tm_min = min; tmtime.tm_hour = hour; tmtime.tm_mday = day; tmtime.tm_mon = month - 1; tmtime.tm_year = year - 1900; timet = mktime(&tmtime); return true; } static bool compImageDate(IvImage* first, IvImage* second) { std::time_t firstFile = time(NULL); std::time_t secondFile = time(NULL); double diff; std::string metadatatime = first->spec().get_string_attribute(""DateTime""); if (metadatatime.empty()) { if (first->init_spec(first->name(), 0, 0)) { metadatatime = first->spec().get_string_attribute(""DateTime""); if (metadatatime.empty()) { if (!Filesystem::exists(first->name())) return false; firstFile = Filesystem::last_write_time(first->name()); } } else return false; } DateTime_to_time_t(metadatatime.c_str(), firstFile); metadatatime = second->spec().get_string_attribute(""DateTime""); if (metadatatime.empty()) { if (second->init_spec(second->name(), 0, 0)) { metadatatime = second->spec().get_string_attribute(""DateTime""); if (metadatatime.empty()) { if (!Filesystem::exists(second->name())) return true; secondFile = Filesystem::last_write_time(second->name()); } } else return true; } DateTime_to_time_t(metadatatime.c_str(), secondFile); diff = difftime(firstFile, secondFile); if (diff == 0) return compName(first, second); return (diff < 0); } void ImageViewer::sortByImageDate() { int numImg = m_images.size(); if (numImg < 2) return; std::sort(m_images.begin(), m_images.end(), &compImageDate); current_image(0); displayCurrentImage(); // updateActions(); } static bool compFileDate(IvImage* first, IvImage* second) { std::time_t firstFile, secondFile; double diff; if (!Filesystem::exists(first->name())) return false; firstFile = Filesystem::last_write_time(first->name()); if (!Filesystem::exists(second->name())) return true; secondFile = Filesystem::last_write_time(second->name()); diff = difftime(firstFile, secondFile); if (diff == 0) return compName(first, second); return (diff < 0); } void ImageViewer::sortByFileDate() { int numImg = m_images.size(); if (numImg < 2) return; std::sort(m_images.begin(), m_images.end(), &compFileDate); current_image(0); displayCurrentImage(); // updateActions(); } void ImageViewer::sortReverse() { int numImg = m_images.size(); if (numImg < 2) return; std::reverse(m_images.begin(), m_images.end()); current_image(0); displayCurrentImage(); // updateActions(); } void ImageViewer::viewChannelFull() { viewChannel(0, RGBA); } void ImageViewer::viewChannelRed() { viewChannel(0, SINGLE_CHANNEL); } void ImageViewer::viewChannelGreen() { viewChannel(1, SINGLE_CHANNEL); } void ImageViewer::viewChannelBlue() { viewChannel(2, SINGLE_CHANNEL); } void ImageViewer::viewChannelAlpha() { viewChannel(3, SINGLE_CHANNEL); } void ImageViewer::viewChannelLuminance() { viewChannel(m_current_channel, LUMINANCE); } void ImageViewer::viewColorRGBA() { viewChannel(m_current_channel, RGBA); } void ImageViewer::viewColorRGB() { viewChannel(m_current_channel, RGB); } void ImageViewer::viewColor1Ch() { viewChannel(m_current_channel, SINGLE_CHANNEL); } void ImageViewer::viewColorHeatmap() { viewChannel(m_current_channel, HEATMAP); } void ImageViewer::viewChannelPrev() { if (glwin->is_glsl_capable()) { if (m_current_channel > 0) viewChannel(m_current_channel - 1, m_color_mode); } else { // Simulate old behavior. if (m_color_mode == RGBA || m_color_mode == RGB) { viewChannel(m_current_channel, LUMINANCE); } else if (m_color_mode == SINGLE_CHANNEL) { if (m_current_channel == 0) viewChannelFull(); else viewChannel(m_current_channel - 1, SINGLE_CHANNEL); } } } void ImageViewer::viewChannelNext() { if (glwin->is_glsl_capable()) { viewChannel(m_current_channel + 1, m_color_mode); } else { // Simulate old behavior. if (m_color_mode == LUMINANCE) { viewChannelFull(); } else if (m_color_mode == RGBA || m_color_mode == RGB) { viewChannelRed(); } else if (m_color_mode == SINGLE_CHANNEL) { viewChannel(m_current_channel + 1, SINGLE_CHANNEL); } } } void ImageViewer::viewSubimagePrev() { IvImage* img = cur(); if (!img) return; bool ok = false; if (img->miplevel() > 0) { ok = loadCurrentImage(img->subimage(), img->miplevel() - 1); } else if (img->subimage() > 0) { ok = loadCurrentImage(img->subimage() - 1); } else if (img->nsubimages() > 0) { img->auto_subimage(true); ok = loadCurrentImage(0); } if (ok) { if (fitImageToWindowAct->isChecked()) fitImageToWindow(); displayCurrentImage(); } } void ImageViewer::viewSubimageNext() { IvImage* img = cur(); if (!img) return; bool ok = false; if (img->auto_subimage()) { img->auto_subimage(false); ok = loadCurrentImage(0); } else if (img->miplevel() < img->nmiplevels() - 1) { ok = loadCurrentImage(img->subimage(), img->miplevel() + 1); } else if (img->subimage() < img->nsubimages() - 1) { ok = loadCurrentImage(img->subimage() + 1); } if (ok) { if (fitImageToWindowAct->isChecked()) fitImageToWindow(); displayCurrentImage(); } } void ImageViewer::keyPressEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_Left: case Qt::Key_Up: case Qt::Key_PageUp: prevImage(); return; //break; case Qt::Key_Right: // std::cerr << ""Modifier is "" << (int)event->modifiers() << '\\n'; // fprintf (stderr, ""%x\\n"", (int)event->modifiers()); // if (event->modifiers() & Qt::ShiftModifier) // std::cerr << ""hey, ctrl right\\n""; case Qt::Key_Down: case Qt::Key_PageDown: nextImage(); return; //break; case Qt::Key_Escape: if (m_fullscreen) fullScreenToggle(); return; case Qt::Key_Minus: case Qt::Key_Underscore: zoomOut(); break; case Qt::Key_Plus: case Qt::Key_Equal: zoomIn(); break; default: // std::cerr << ""ImageViewer key "" << (int)event->key() << '\\n'; QMainWindow::keyPressEvent(event); } } void ImageViewer::resizeEvent(QResizeEvent* event) { if (fitImageToWindowAct->isChecked()) fitImageToWindow(); QMainWindow::resizeEvent(event); } void ImageViewer::closeImg() { if (m_images.empty()) return; delete m_images[m_current_image]; m_images[m_current_image] = NULL; m_images.erase(m_images.begin() + m_current_image); // Update image indices // This should be done for all image indices we may be storing if (m_last_image == m_current_image) { if (!m_images.empty() && m_last_image > 0) m_last_image = 0; else m_last_image = -1; } if (m_last_image > m_current_image) m_last_image--; m_current_image = m_current_image < (int)m_images.size() ? m_current_image : 0; displayCurrentImage(); } void ImageViewer::print() { #if 0 Q_ASSERT(imageLabel->pixmap()); QPrintDialog dialog(&printer, this); if (dialog.exec()) { QPainter painter(&printer); QRect rect = painter.viewport(); QSize size = imageLabel->pixmap()->size(); size.scale(rect.size(), Qt::KeepAspectRatio); painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); painter.setWindow(imageLabel->pixmap()->rect()); painter.drawPixmap(0, 0, *imageLabel->pixmap()); } #endif } void ImageViewer::zoomIn() { IvImage* img = cur(); if (!img) return; if (zoom() >= 64) return; float oldzoom = zoom(); float newzoom = ceil2f(oldzoom); float xc, yc; // Center view position glwin->get_center(xc, yc); int xm, ym; // Mouse position glwin->get_focus_image_pixel(xm, ym); float xoffset = xc - xm; float yoffset = yc - ym; float maxzoomratio = std::max(oldzoom / newzoom, newzoom / oldzoom); int nsteps = (int)OIIO::clamp(20 * (maxzoomratio - 1), 2.0f, 10.0f); for (int i = 1; i <= nsteps; ++i) { float a = (float)i / (float)nsteps; // Interpolation amount float z = OIIO::lerp(oldzoom, newzoom, a); float zoomratio = z / oldzoom; view(xm + xoffset / zoomratio, ym + yoffset / zoomratio, z, false); if (i != nsteps) { QApplication::processEvents(); Sysutil::usleep(1000000 / 4 / nsteps); } } fitImageToWindowAct->setChecked(false); } void ImageViewer::zoomOut() { IvImage* img = cur(); if (!img) return; if (zoom() <= 1.0f / 64) return; float oldzoom = zoom(); float newzoom = floor2f(oldzoom); float xcpel, ycpel; // Center view position glwin->get_center(xcpel, ycpel); int xmpel, ympel; // Mouse position glwin->get_focus_image_pixel(xmpel, ympel); float xoffset = xcpel - xmpel; float yoffset = ycpel - ympel; float maxzoomratio = std::max(oldzoom / newzoom, newzoom / oldzoom); int nsteps = (int)OIIO::clamp(20 * (maxzoomratio - 1), 2.0f, 10.0f); for (int i = 1; i <= nsteps; ++i) { float a = (float)i / (float)nsteps; // Interpolation amount float z = OIIO::lerp(oldzoom, newzoom, a); float zoomratio = z / oldzoom; view(xmpel + xoffset / zoomratio, ympel + yoffset / zoomratio, z, false); if (i != nsteps) { QApplication::processEvents(); Sysutil::usleep(1000000 / 4 / nsteps); } } fitImageToWindowAct->setChecked(false); } void ImageViewer::normalSize() { IvImage* img = cur(); if (!img) return; fitImageToWindowAct->setChecked(false); float xcenter = img->oriented_full_x() + 0.5 * img->oriented_full_width(); float ycenter = img->oriented_full_y() + 0.5 * img->oriented_full_height(); view(xcenter, ycenter, 1.0, true); fitWindowToImage(false); } float ImageViewer::zoom_needed_to_fit(int w, int h) { IvImage* img = cur(); if (!img) return 1; float zw = (float)w / img->oriented_width(); float zh = (float)h / img->oriented_height(); return std::min(zw, zh); } void ImageViewer::fitImageToWindow() { IvImage* img = cur(); if (!img) return; fitImageToWindowAct->setChecked(true); zoom(zoom_needed_to_fit(glwin->width(), glwin->height())); } void ImageViewer::fitWindowToImage(bool zoomok, bool minsize) { IvImage* img = cur(); // Don't resize when there's no image or the image hasn't been opened yet // (or we failed to open it). if (!img || !img->image_valid()) return; // FIXME -- figure out a way to make it exactly right, even for the // main window border, etc. #ifdef __APPLE__ int extraw = 0; //12; // width() - minimumWidth(); int extrah = statusBar()->height() + 0; //40; // height() - minimumHeight(); #else int extraw = 4; //12; // width() - minimumWidth(); int extrah = statusBar()->height() + 4; //40; // height() - minimumHeight(); #endif // std::cerr << ""extra wh = "" << extraw << ' ' << extrah << '\\n'; float z = zoom(); int w = (int)(img->oriented_full_width() * z) + extraw; int h = (int)(img->oriented_full_height() * z) + extrah; if (minsize) { if (w < m_default_width) { w = m_default_width; } if (h < m_default_height) { h = m_default_height; } } if (!m_fullscreen) { QDesktopWidget* desktop = QApplication::desktop(); QRect availgeom = desktop->availableGeometry(this); int availwidth = availgeom.width() - extraw - 20; int availheight = availgeom.height() - extrah - menuBar()->height() - 20; #if 0 QRect screengeom = desktop->screenGeometry (this); std::cerr << ""available desktop geom "" << availgeom.x() << ' ' << availgeom.y() << ' ' << availgeom.width() << ""x"" << availgeom.height() << ""\\n""; std::cerr << ""screen desktop geom "" << screengeom.x() << ' ' << screengeom.y() << ' ' << screengeom.width() << ""x"" << screengeom.height() << ""\\n""; #endif if (w > availwidth || h > availheight) { w = std::min(w, availwidth); h = std::min(h, availheight); if (zoomok) { z = zoom_needed_to_fit(w, h); w = (int)(img->oriented_full_width() * z) + extraw; h = (int)(img->oriented_full_height() * z) + extrah; // std::cerr << ""must rezoom to "" << z << "" to fit\\n""; } // std::cerr << ""New window geom "" << w << ""x"" << h << ""\\n""; int posx = x(), posy = y(); if (posx + w > availwidth || posy + h > availheight) { if (posx + w > availwidth) posx = std::max(0, availwidth - w) + availgeom.x(); if (posy + h > availheight) posy = std::max(0, availheight - h) + availgeom.y(); // std::cerr << ""New position "" << posx << ' ' << posy << ""\\n""; move(QPoint(posx, posy)); } } } float midx = img->oriented_full_x() + 0.5 * img->oriented_full_width(); float midy = img->oriented_full_y() + 0.5 * img->oriented_full_height(); view(midx, midy, z, false, false); resize(w, h); // Resize will trigger a repaint. #if 0 QRect g = geometry(); std::cerr << ""geom "" << g.x() << ' ' << g.y() << ' ' << g.width() << ""x"" << g.height() << ""\\n""; g = frameGeometry(); std::cerr << ""frame geom "" << g.x() << ' ' << g.y() << ' ' << g.width() << ""x"" << g.height() << ""\\n""; g = glwin->geometry(); std::cerr << ""ogl geom "" << g.x() << ' ' << g.y() << ' ' << g.width() << ""x"" << g.height() << ""\\n""; std::cerr << ""Status bar height = "" << statusBar()->height() << ""\\n""; #endif #if 0 bool fit = fitWindowToImageAct->isChecked(); if (!fit) { normalSize(); } #endif updateActions(); } void ImageViewer::fullScreenToggle() { if (m_fullscreen) { menuBar()->show(); statusBar()->show(); showNormal(); m_fullscreen = false; slideTimer->stop(); disconnect(slideTimer, 0, 0, 0); } else { menuBar()->hide(); statusBar()->hide(); showFullScreen(); m_fullscreen = true; fitImageToWindow(); } } void ImageViewer::about() { QMessageBox::about( this, tr(""About iv""), tr(""

iv is the image viewer for OpenImageIO.

"" ""

(c) Copyright Contributors to the OpenImageIO project.

"" ""

See http://openimageio.org for details.

"")); } void ImageViewer::updateActions() { // zoomInAct->setEnabled(!fitImageToWindowAct->isChecked()); // zoomOutAct->setEnabled(!fitImageToWindowAct->isChecked()); // normalSizeAct->setEnabled(!fitImageToWindowAct->isChecked()); } static inline void calc_subimage_from_zoom(const IvImage* img, int& subimage, float& zoom, float& xcenter, float& ycenter) { int rel_subimage = std::trunc(std::log2(1.0f / zoom)); subimage = clamp(img->subimage() + rel_subimage, 0, img->nsubimages() - 1); if (!(img->subimage() == 0 && zoom > 1) && !(img->subimage() == img->nsubimages() - 1 && zoom < 1)) { float pow_zoom = powf(2.0f, (float)rel_subimage); zoom *= pow_zoom; xcenter /= pow_zoom; ycenter /= pow_zoom; } } void ImageViewer::view(float xcenter, float ycenter, float newzoom, bool smooth, bool redraw) { IvImage* img = cur(); if (!img) return; float oldzoom = m_zoom; float oldxcenter, oldycenter; glwin->get_center(oldxcenter, oldycenter); float zoomratio = std::max(oldzoom / newzoom, newzoom / oldzoom); int nsteps = (int)OIIO::clamp(20 * (zoomratio - 1), 2.0f, 10.0f); if (!smooth || !redraw) nsteps = 1; for (int i = 1; i <= nsteps; ++i) { float a = (float)i / (float)nsteps; // Interpolation amount float xc = OIIO::lerp(oldxcenter, xcenter, a); float yc = OIIO::lerp(oldycenter, ycenter, a); m_zoom = OIIO::lerp(oldzoom, newzoom, a); glwin->view(xc, yc, m_zoom, redraw); // Triggers redraw automatically if (i != nsteps) { QApplication::processEvents(); Sysutil::usleep(1000000 / 4 / nsteps); } } if (img->auto_subimage()) { int subimage = 0; calc_subimage_from_zoom(img, subimage, m_zoom, xcenter, ycenter); if (subimage != img->subimage()) { //std::cerr << ""Changing to subimage "" << subimage; //std::cerr << "" With zoom: "" << m_zoom << '\\n'; loadCurrentImage(subimage); glwin->update(); glwin->view(xcenter, ycenter, m_zoom, redraw); } } // zoomInAct->setEnabled (zoom() < 64.0); // zoomOutAct->setEnabled (zoom() > 1.0/64); updateStatusBar(); } void ImageViewer::zoom(float newzoom, bool smooth) { float xcenter, ycenter; glwin->get_center(xcenter, ycenter); view(xcenter, ycenter, newzoom, smooth); } void ImageViewer::showInfoWindow() { if (!infoWindow) { infoWindow = new IvInfoWindow(*this, true); infoWindow->setPalette(m_palette); } infoWindow->update(cur()); if (infoWindow->isHidden()) infoWindow->show(); else infoWindow->hide(); } void ImageViewer::showPixelviewWindow() { ((QOpenGLWidget*)(glwin))->update(); } void ImageViewer::editPreferences() { if (!preferenceWindow) { preferenceWindow = new IvPreferenceWindow(*this); preferenceWindow->setPalette(m_palette); } preferenceWindow->show(); } ",16199,True,2628.537474332979,median "= jbang - Unleash the power of Java :idprefix: :idseparator: - ifndef::env-github[] :toc: left :icons: font endif::[] ifdef::env-github[] :toc: macro :caution-caption: :fire: :important-caption: :exclamation: :note-caption: :paperclip: :tip-caption: :bulb: :warning-caption: :warning: endif::[] image:https://img.shields.io/github/release/jbangdev/jbang.svg[Release,link=https://github.com/jbangdev/jbang/releases] image:https://github.com/jbangdev/jbang/workflows/ci-build/badge.svg[Build Status,link=https://github.com/jbangdev/jbang/actions] image:https://www.eclipse.org/che/contribute.svg[Che, link=https://che.openshift.io/f?url=https://github.com/jbangdev/jbang] image:https://img.shields.io/badge/Gitpod-Workspace-blue?logo=gitpodp[Gitpod, link=https://gitpod.io/#https://github.com/jbangdev/jbang] image:https://badges.gitter.im/jbangdev/community.svg[Gitter, link=https://gitter.im/jbangdev/community] image:images/jbang_logo.svg[JBang Logo, title=""JBang Logo""] == Intro Want to learn, explore or use Java instantly without setup ? Do you like Java but use python, groovy, kotlin or similar languages for scripts, experimentation and exploration ? Ever wanted to just be able to run java from anywhere without any or very minimal setup ? Ever tried out Java 11+ support for running `.java` files directly in your shell but felt it was a bit too cumbersome ? Then try `jbang` which lets you do this: image:https://asciinema.org/a/4AiobRxUwPUPztCtrDYcmoKjs.svg[link=https://asciinema.org/a/4AiobRxUwPUPztCtrDYcmoKjs?autoplay=true&theme=solarized-dark] [source, bash] ---- $ jbang init --template=cli hello.java $ jbang hello.java Max! [jbang] Resolving dependencies... [jbang] Resolving info.picocli:picocli:4.5.0...Done [jbang] Dependencies resolved [jbang] Building jar... Hello Max! $ jbang hello.java -h Usage: hello [-hV] hello made with jbang The greeting to print -h, --help Show this help message and exit. -V, --version Print version information and exit. ---- Instant cli app generated built using java and picocli as a dependency that was fetched as needed for the compilation and execution. JBang goes beyond more than just easy scripting; you can use `jbang` to launch any kind of java application or library packaged as a jar available locally, via http/https download or in a Maven repository. toc::[] == Features * `.java` Scripting for Java 8 and upwards * `.jsh` via JShell from Java 9 and upwards * Works on icon:windows[] Windows, icon:apple[] OSX and icon:linux[] Linux * Install using curl, power shell, SDKMan (icon:apple[]/icon:linux[]), Homebrew (icon:apple[]), Chocolatey (icon:windows[]) or Scoop (icon:windows[]) * If needed will automatically install Java and even a Java editor (vscodium) for editing * Installation of scripts to user `PATH` * Include multiple files and sources * Dependency declarations using `//DEPS ` for automatic dependency resolution * Control compile and runtime options with `//JAVAC_OPTIONS ` and `//JAVA_OPTIONS ` * Compiled jar and Dependency resolution caching * native-image generation (`--native`) * Launch with debug enabled for instant debugging from your favorite IDE * Transparent launch of JavaFX Applications on Java 8 and higher * Can be used for writing plugins to other cli's like `kubectl` * Init templates to get started easily (`jbang init -t cli hello.java`) * Generate gradle and IDE config with dependencies for easy editing in your favorite IDE (`jbang edit myfile.java`) To use it install `jbang` and run `jbang yourscript.java` == Requirements Tested and verified to use on OSX, Linux and Windows (incl. command.exe, cygwin and mingw shells). == Installation To use `jbang` Java 8 is the minimum required version, however Java 11 or higher is recommended. Note: `jbang` will download and install `java` from Adopt OpenJDK if no `java` is available. Once you have installed from one of the below approaches it is recommended you run `jbang app setup` to have it setup your `PATH` to include jbang app scripts + it will on operating systems that supports it setup a `j!` alias you can use instead of `jbang`. === SDKMan icon:linux[] / icon:apple[] To install both java and `jbang` we recommend https://sdkman.io[sdkman] on Linux and OSX. [source, bash] ---- curl -s ""https://get.sdkman.io"" | bash # <.> source ~/.bash_profile # <.> sdk install java # <.> ---- Once Java is installed and ready, you install `jbang` with [source, bash] ---- sdk install jbang ---- To test your installation run: [source, bash] ---- jbang --help ---- This should print out usage information. To update run: [source] ---- sdk update jbang ---- === Chocolatey icon:windows[] On Windows you can install both `java` and jbang` with https://chocolatey.org[Chocolatey]. From a command prompt with enough rights to install with choco: choco install jdk11 Once Java in installed run: choco install jbang To upgrade to latest version: choco upgrade jbang The latest package will be published to https://chocolatey.org/packages/jbang[jbang choco package page], it might be a bit delayed as the review is still manual. In case the default version is not the latest you can see the https://chocolatey.org/packages/jbang/#versionhistory[version list] and install specific version using: choco install jbang --version= === Scoop icon:windows[] On Windows you can also install `jbang` with https://scoop.sh[Scoop]. [source, bash] ---- scoop bucket add jbangdev https://github.com/jbangdev/scoop-bucket scoop install jbang ---- To upgrade to latest version: scoop update jbang === Homebrew icon:apple[] On OSX you can install 'java' and `jbang` with https://brew.sh[Homebrew] using custom taps. To install Java 11: [source, bash] ---- brew tap AdoptOpenJDK/openjdk brew cask install adoptopenjdk11 ---- Once Java is installed you can use brew with https://github.com/jbangdev/homebrew-tap/[jbangdev/tap] to get `jbang`: brew install jbangdev/tap/jbang To upgrade to latest version: brew upgrade jbangdev/tap/jbang === (Experimental) Linux packages icon:linux[] WARNING: These builds are not fully automated yet thus might be slightly behind. You can install rpm packages from https://copr.fedorainfracloud.org/coprs/maxandersen/jbang/[Fedora Copr] by doing the following: [source] ---- dnf copr enable maxandersen/jbang dnf install jbang ---- The COPR currently includes builds from various versions of CentOS, Fedora, Mageia and OpenSuse. === Docker / GitHub Action icon:docker[] You can run `jbang` via Docker: [source, bash] ---- docker run -v `pwd`:/ws --workdir=/ws jbangdev/jbang-action helloworld.java ---- or if you prefer using Quay.io: [source, bash] ---- docker run -v `pwd`:/ws --workdir=/ws quay.io/jbangdev/jbang-action helloworld.java ---- The same container images can be used with GitHub Actions, see https://github.com/jbangdev/jbang-action[jbang-action] for details. === Manual install Unzip the https://github.com/jbangdev/jbang/releases/latest[latest binary release], add the `jbang-/bin` folder to your `$PATH` and you are set. === Wrapper install If you would like to have `jbang` available in a local directory and committed into a source code repository (akin to Maven and Gradle wrappers) you can use the `jbang wrapper` command. If you have `jbang` already installed you call `jbang wrapper install` in a folder to install a local `jbang` that will run out of that directory using `./jbang`. The `./.jbang` directory which `jbang wrapper install` creates is just a cache which you typically would not commit to a source code repository, so you can e.g. `echo .jbang/ >>.gitignore`. === ""Zero"" Install If you want to try out jbang without a package manager or similar you can run the following to download jbang in `~/.jbang` and if necessary `java`. Linux/OSX/Windows Bash: [source, bash] ---- curl -Ls https://sh.jbang.dev | bash -s - ---- For example `curl -Ls https://sh.jbang.dev | bash -s - properties@jbangdev` Windows Powershell: [source, powershell] ---- iex ""& { $(iwr -useb https://ps.jbang.dev) } "" ---- For example `iex ""& { $(iwr -useb https://ps.jbang.dev) } properties@jbangdev""` == Usage A script is just a single `.java` file with a classic static main method or a `.jsh` file which will be passed to `jshell`. Below is an (almost) minimal example you can save in `helloworld.java` or simply run `jbang init helloworld.java`: [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? # <.> class helloworld { // <.> public static void main(String[] args) { if(args.length==0) { System.out.println(""Hello World!""); } else { System.out.println(""Hello "" + args[0]); } } } ---- <.> By using this `//` style instead of shebang `#!` you trick `bash`, `zsh` etc. to run this as a script while still being valid java code. <.> A classname, can be anything when using `jbang` but to be valid java for most IDEs you'll want to name it the same as the source file. Now to run this you can call it via `jbang`: [source] ---- jbang helloworld.java ---- or if on Linux/OSX run it directly. If you created it manually you need to mark it as executable before running it. [source] ---- chmod +x helloworld.java ./helloworld.java jbang! ---- [WARNING] ==== When no <> is available in the PATH, JDK 11 will be downloaded by default to bootstrap jbang. If your script requires a higher version and you don' want to download two JDK's, you can define an alternative default with `JBANG_DEFAULT_JAVA_VERSION` env variable. $ JBANG_DEFAULT_JAVA_VERSION=14 jbang my-script.java Note that if JDK is found in the PATH, `JBANG_DEFAULT_JAVA_VERSION` will be ignored. ==== === Default application If you pass a directory or a url ending in `/` jbang will look for `main.java` to run as default application for that directory / location. === URLs from Trusted Sources You can use `http(s):/` and `file:/` url's for input:. [source] ---- jbang https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec ---- For safety reasons jbang will not run arbitrary urls before you indicated you trust their source. Thus when running the above for the first time you will see the following warning about the url not being a trusted source: [source,bash] ---- jbang https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec [jbang] https://gist.github.com/maxandersen/f43b4c52dfcfc42dcd59a04e49acf6ec is not from a trusted source thus not running it automatically. If you trust the url to be safe to run you can do one of the following: 0) Trust once: Add no trust, just run this time 1) Trust this url in future: jbang trust add https://gist.github.com/maxandersen/ Any other response will result in exit. [jbang] Type in your choice (0 or 1) and hit enter. Times out after 10 seconds. ---- You can then choose 0 to run once or 1 to trust the suggested url. If you don't answer within 10 seconds jbang will exit. To enable running it without such question you need to mark that url or a sub part of it as a trusted source. i.e. `jbang trust add https://github.com/maxandersen/` will tell `jbang` to trust anything with that base url. You can see more in the comments of the `~/.jbang/trusted-sources.json`. [TIP] ==== Sites such as GitHub, gitlab, bitbucket, gist, carbon.now.sh jbang will try and extract the proper source rather than the raw html. i.e. doing `jbang https://carbon.now.sh/ae51bf967c98f31a13cba976903030d5 carbon!` is possible. ==== [TIP] ==== URL's will follow redirects. In case you need to use it with sites with self-signed/non-trusted certificates you can if you trust the site use `--insecure`. ==== === Build and run native image (Experimental) There is support for using `native-image` from GraalVM project to produce a binary executable. Since not all java libraries can automatically be built with `native-image` - especially if using reflection feature are considered highly experimental. Just run `jbang --native helloworld.java` and `jbang` will use `native-image` from either `$JAVA_HOME/bin` or `$GRAALVM_HOME/bin` or `$PATH` to produce a native image binary. You can install the `native-image` utility binary e.g. by installing GraalVM from https://www.graalvm.org/downloads, and then once running `gu install native-image` as per https://www.graalvm.org/reference-manual/native-image. [TIP] ==== If you use `--native` with picocli remember to add `info.picocli:picocli-codegen` as that will ensure it will actually work with `native-image`. ==== === Using `.jsh` for `jshell` There is support to run `.jsh` via `jshell`. The advantage of `jshell` is that you do not need to have a class or static main method. Classic `jshell` does not support passing in arguments nor system properties, `jbang` does. In the case of `.jsh` files `jbang` injects a startup script that declares a `String[] args` which will contain any passed in arguments, and it sets any properties passed in as `-Dkey=value` as parameters to `jbang`. That means you can run a script as `jbang -Dkey=value helloworld.jsh World` and retrieve arguments and properties as: [source,java] ---- System.out.println(""Hello "" + (args.length>0?args[0]:""World"")); // <.> System.out.println(System.getProperty(""key"")); // <.> ---- <.> Line where `args` are accessible without previous declaration. <.> System properties set when passed as `-D` arguments to `jbang` The script will have the output: Hello World value Please note that `.jsh` files are source only, they are not compiled thus they are https://github.com/jbangdev/jbang/issues/506[not cached] nor can they be https://github.com/jbangdev/jbang/issues/510[built as native images]. [TIP] ==== If you use `-Dkey` where no value is specified `jbang` will interpret this as `-Dkey=true` allowing you to easily have flags passed into, i.e. `jbang -DskipTests mytestrunner.java`. Now within your script `Boolean.getBoolean('skipTests') will return true. ==== ==== Running script from standard input jbang can run scripts directly from standard input using `-` or `/dev/stdin` as input. i.e. `echo 'System.out.println(""Hello World!"");' | jbang -` [TIP] ==== If you use `--interactive` `jbang` will let `jshell` enter into interactive/REPL mode. You can write `/exit` to leave this mode. ==== [TIP] ==== If your own code needs to handle chained pipes well it is recommended to add the following code: [source,java] ---- import sun.misc.Signal; if (!""Windows"".equals(System.getProperty(""os.name""))) { Signal.handle(new Signal(""PIPE""), (final Signal sig) -> System.exit(1)); } ---- It will give a compiler warning as it is internal API; but for now it works. ==== === Running ``.jar``'s `jbang` will also run `.jar` files directly. i.e. `jbang helloworld.jar` will run `helloworld.jar` if found on your local file system. The `.jar` can be a local file or a http/https url. You can also run a `.jar` file referenced by a Maven coordinate, i.e.: jbang info.picocli:picocli-codegen:4.5.0 This will fetch the dependency stated and put the transitive dependencies on the class-path. If you need to specify a main class you can do so by using `--main` i.e. jbang --main picocli.codegen.aot.graalvm.ReflectionConfigGenerator info.picocli:picocli-codegen:4.5.0 [TIP] ==== A side effect of running GAV as a jar, the GAV could also be a `.java` or `.jsh` file and it would be launched as a script instead of a jar. No one would want to do that (right?) but now you know. ==== == Init templates To get started you can run `jbang init helloworld.java` and a simple java class with a static main is generated. Using `jbang init --template=cli helloworld.java` you get a more complete Hello World CLI using https://picocli.info/[picocli] as dependency. == Declare dependencies If you want to write real scripts you will want to use some java libraries. To specify dependencies you use gradle-style locators or links to Git sources. Below are examples for `log4j`. === Using `//DEPS` [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? // <.> //DEPS log4j:log4j:1.2.17 import static java.lang.System.out; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import java.util.Arrays; class classpath_example { static final Logger logger = Logger.getLogger(classpath_example.class); public static void main(String[] args) { BasicConfigurator.configure(); // <.> logger.info(""Welcome to jbang""); Arrays.asList(args).forEach(arg -> logger.warn(""arg: "" + arg)); logger.info(""Hello from Java!""); } } ---- <.> `//DEPS` must be placed at the start of line and can be one or more space separated dependencies. <.> Minimal logging setup - required by log4j. Now when you run this, the first time with no existing dependencies installed you should get an output like this: [source] ---- $ ./classpath_example.java [jbang] Resolving dependencies... [jbang] Resolving log4j:log4j:1.2.17...Done [jbang] Dependencies resolved 0 [main] INFO classpath_example - Welcome to jbang 1 [main] INFO classpath_example - Hello from Java! ---- === Using links to Git sources Instead of gradle-style locators you can also use URLs to projects on GitHub, GitLab or BitBucket. Links to those projects will then be converted to artifacts references on https://jitpack.io/[jitpack]. You can use links to the root of the project, to the root of a tag/release and to specific commits. If the project you link to has multiple modules and you want only a specific module you can specify the name of the module by appending `#name-of-module` to the URL. And finally if the link you provide is to a specific branch of the project then you need to append `#:SNAPSHOT` to the URL. (If you have both a branch and a module name then use `#name-of-module:SNAPSHOT`) .Examples of links and their resulting locator: |=== |Link | Locator |https://github.com/jbangdev/jbang |com.github.jbangdev:jbang:HEAD-SNAPSHOT |https://github.com/jbangdev/jbang/tree/v1.2.3 |com.github.jbangdev:jbang:v1.2.3 |https://github.com/jbangdev/jbang/tree/f1f34b031d2163e0cdc6f9a3725b59f47129c923[https://github.com/jbangdev/jbang/tree/f1f34b031...] |com.github.jbangdev:jbang:f1f34b031d |https://github.com/jbangdev/jbang#mymodule |com.github.jbangdev.jbang:mymodule:HEAD-SNAPSHOT |https://github.com/jbangdev/jbang/tree/mybranch#:SNAPSHOT |com.github.jbangdev:jbang:mybranch-SNAPSHOT |https://github.com/jbangdev/jbang/tree/mybranch#mymodule:SNAPSHOT |com.github.jbangdev.jbang.mymodule:mybranch-SNAPSHOT |=== === Offline mode In case you prefer `jbang` to just fail-fast when dependencies cannot be found locally you can run `jbang` in offline mode using `jbang -o` or `jbang --offline`. In this mode `jbang` will simply fail if dependencies have not been cached already. === Repositories By default `jbang` uses https://jcenter.bintray.com/[jcenter] as its repository as it is a superset of Maven Central and supposedly should be faster. And if you are using the above mentioned URL dependencies https://jitpack.io[jitpack] will be added automatically as well. If that is not sufficient for you or need some custom repo you can use `//REPOS id=repourl` to state which repository URL to use. For ease of use there are also a few shorthands to use popular commonly available repositories. |=== |Short name | Description |`mavencentral` |Maven Central |`jcenter` |`https://jcenter.bintray.com/` |`google` |`https://maven.google.com/` |`jitpack` |`https://jitpack.io/` |=== Following example enables use of Maven Central and add a custom `acme` repository. [source,java] ---- //REPOS mavenCentral,acme=https://maven.acme.local/maven ---- [WARNING] ==== If you add any `//REPOS` lines `jbang` will no longer consult `jcenter` thus you need to explicitly add it if needed. ==== [TIP] ==== For secure authentication `jbang` will honor `~/.m2/settings-security.xml` for configuring username/passwords. ==== === Using `@Grab` There is also support for using Groovy lang style `@Grab` syntax. [source,java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? import static java.lang.System.out; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import java.util.Arrays; import groovy.lang.Grab; // <.> import groovy.lang.Grapes; import groovy.lang.GrabResolver; @GrabResolver(""mavenCentral"") // <.> @GrabResolver(name='acme', root='https://maven.acme.local/maven') @Grapes({ // <.> @Grab(group=""org.codehaus.groovy"", module=""groovy"", version=""2.5.8""), // <.> @Grab(module = ""log4j"", group = ""log4j"", version = ""1.2.17"") }) class classpath_example { static final Logger logger = Logger.getLogger(classpath_example.class); public static void main(String[] args) { BasicConfigurator.configure(); Arrays.asList(args).forEach(arg -> out.println(arg)); } } ---- <.> Import needed to make the compiler be okey with `@Grab` annotation. <.> Using `GrabResolver` to enable `mavenCentral` and custom `acme` repository <.> In Groovy you normally put `@Grab` on import statements. That is not allowed in Java thus when having multiple imports you need to put them in a `@Grapes` annotation first. <.> `jbang` will grab any `@Grab` annotation and assume it is declaring dependencies. === System properties and Environment variables In dependencies you can refer to environment and system properties to parameterize the dependencies. It uses the format `${[env.]propertyname:}`. Furthermore to align with properties commonly used to make dependency resolution portable `jbang` exposes properties similar to what the `https://github.com/trustin/os-maven-plugin[os-maven-plugin]` does. Plus for ease of use for javafx dependencies it also setups a property named `${os.detected.jfxname}`. Examples: [source,bash] ---- ${env.USER} = 'max' ${os.name} = 'Mac OS X' ${non.existing.key:empty} = 'empty' ${os.detected.jfxname} = 'mac' ---- This can be put to use in `//DEPS` like so: //DEPS org.openjfx:javafx-graphics:11.0.2:${os.detected.jfxname} Here we use the properties to avoid hardcoding your script to a specific operating system. === JavaFX If `jbang` detects you have a `javafx-` dependency in your list of dependencies it will if you `java` command supports Java modules automatically set the necessary `--module-path` and `--add-modules`. See `link:examples/jfx.java[]` and `link:examples/jfxtiles.java[]` for examples of this. == Multiple source files It is possible to use multiple source files just by having the files in the same source directory, it will even work for a limited extent with packages. For example the example below works by just calling `jbang Main.java`: .Main.java [source,java] ---- import model.Person; public class Main { public static void main(String... args) { Person p = new Person(args[0]); System.out.println(""Hello "" + p.getName()); } } ---- .model/Person.java [source,java] ---- package model; public class Person { String name; public String getName() { return name; } public Person(String n) { this.name = n; } } ---- There are some cases where the above does not work; i.e. if two packages refer to each other - i.e. `model.Person` referring to `util.Generator` will fail. Also `jbang edit` does not know about multiple sources as it runs and must run before compilation occurs. Thus version 0.46 there is now support for having that all work with multiple source files. The main script file defines all the dependencies and you add more source files into the application using `//SOURCES `. If included source has `//SOURCES` that will also get included recursively. The listed file name(s) gets added to source list when compiling. Currently there are not `*.java` style matching or support for these `.java` files to declare `//DEPS` or other jbang configuration. That will currently only be honored by the main script/app. These will be loosened up in future based on feedback. == Adding more resources If you want to add a `META-INF/application.properties` or `META-INF/resource.index.html` or other files to the generated jar you can use `//FILES` to add them. The format is `//FILES [=]`. Example: //FILES resource.properties //FILES META-INF/resources/index.html=index.html Here `resource.properties` will be copied as is and `META-INF/resources/index.html` gets its content from `index.html`. All locations are relative to the script location. WARNING: Currently `jbang edit` and http(s) based script do not work with `//FILES`. Will be added later. == Extension-less/non-java files for cli-plugins You can use `jbang` to write plugins for cli's like `kubectl`, `git`, etc. They expect their plugins to be named like `-`, i.e. `kubectl-myplugin`. Furthermore some of them, particularly `kubectl` currently require the file to start with `#!` otherwise you get a `exec format error`. There are two ways to have that work. The first recommended way is to use `jbang app install` which setups an intermediate script to avoid the issue, i.e. `jbang app install --name kubectl-my-plugin myplugin.java`. The second is to use a bit of auto-magic `jbang` has to help in case you only want a single file, no intermediate script. That is described below. === Kebab casing of filename `jbang` lets you name your file without a `.java` or `.jsh` extension, such as `kubectl-my-plugin` or `myjavascript.sh`. `jbang` will in this case copy the file to a temporary directory using kebab-case to map the name to a proper java class name. For example, if you make a file called `kubectl-my-plugin` then `jbang` will assume the actual class name to launch to be `KubectlMyPlugin`. Note, similar is done when using `jbang edit`, here the symbolic link will be made so the IDE will treat it as regular camel cased java class. NOTE: If you do not follow this naming pattern you will get a compile error as `javac` expects both the public class and file names to be equal. === she-bang auto-stripped For extension less scripts, you can put `#!' header at the beginning to let apps recognize it is to be treated as a script. To avoid issues when compiling, `jbang` will remove that line before compilation. For now this is required for `kubectl` plugin but not `git`. https://github.com/kubernetes/kubectl/issues/822[Issue opened] on this limitation. == Java version `jbang` will by default use `JAVA_HOME` and if not available, check the `PATH` to locate the `java` executable to run the script with. If your script requires a specific or minimal version of Java you can use `//JAVA (+)`. If Jbang finds a java executable using `JAVA_HOME` or `PATH` which satisfies the stated java version jbang will use it. If no such version is found it will automatically download and install it. Examples: `//JAVA 11` will force use of Java 11. + `//JAVA 13+` will require at least java 13. Java 13 or higher will be used. In case no matching `java` is found `jbang` will fail. You can always force running with specific version of `java` using `--java` command line option, i.e. `jbang --java 8 hello.java` == Managing JDKs In the previous section it was mentioned that Jbang will automatically download and install JDKs when necessary. You can use the `jdk` command to manage JDKs, for example you can run the following: jbang jdk list which will list all the JDKs that are currently installed by Jbang. It's easy to `install` additional JDKs by running: jbang jdk install 14 which will download and install JDK version 14 into Jbang's cache (`~/.jbang/cache/jdks` by default). The list of versions that are available for installation can be found here: https://adoptopenjdk.net/releases.html The first JDK that gets installed by Jbang will be set as the ""default"" JDK. This is from then on the JDK that will be used by Jbang if no Java could be found on the system (meaning `javac` wasn't found on the `PATH` and no `JAVA_HOME` is set). You can change the default JDK by running: jbang jdk default 12 Running it without an argument will return the version of the JDK that is currently set as the default. NOTE: On Windows you might need elevated privileges to create symbolic links. If you don't have permissions then running the above command will result in an error. To use it https://stackoverflow.com/a/24353758[enable symbolic links] for your user or run your shell/terminal as administrator to have this feature working. When you `uninstall` a JDK by running: jbang jdk uninstall 12 and that JDK was set as the default, Jbang will set the next higher version JDK as the default. If no higher version is available it will select the next lower version. === Using managed JDKs yourself Given the fact that Jbang is able to easily download and install JDKs we thought that it might be a good option for our users to be able to access those JDKs for their own use instead of having to install yet another version themselves. To make that easy we added a couple of useful commands. The first can be used to set retrieve to location where the JDK is installed: jbang jdk home This will return the path to the ""default"" JDK (by default `~/.jbang/currentjdk)`, if you want to know the location of a specific JDK you can pass the version as an argument: `jbang jdk home 14`. This command could be used by scripts to find a JDK to use to run a Java program for example (eg: `JAVA_HOME=$(jbang jdk home)`. For setting up your current command line environment there's something simpler. You can run: jbang jdk java-env On Linux and Mac this will output something like: [source] ---- export PATH=""/home/user/.jbang/currentjdk/bin:$PATH"" export JAVA_HOME=""/home/user/.jbang/currentjdk"" # Run this command to configure your shell: # eval $(jbang jdk java-env) ---- And the output itself shows how to properly use it to configure your command line to use the JDK. In this case it's by running: eval $(jbang jdk java-env) To do this by default for all shells you start simply add the above line to your `~/.bashrc` file. Unfortunately on Windows using CMD things are not as easy as is show by the output of `jbang jdk java-env` on that platform: [source] ---- set PATH=C:\\Users\\user\\.jbang\\currentjdk\\bin;%PATH% set JAVA_HOME=C:\\Users\\user\\.jbang\\currentjdk rem Copy & paste the above commands in your CMD window or add rem them to your Environment Variables in the System Settings. ---- Instead of copying and pasting lines you could also redirect the output to a .bat file and execute that instead: > jbang jdk java-env > setenv.bat > setenv == Editing You can edit your script in an IDE/editor by using `jbang edit helloworld.java`. This will generate a project in a temporary location with symbolic links to your script and output the generated folder name. The easiest way to use that is to use it in a call to your IDE: [source, bash] ---- code `jbang edit helloworld.java` ---- If you add further dependencies to your file just re-run the edit command and the relevant files will be regenerated with the updated dependencies. Above does require using a shell that allows for variable evaluation, if you are on i.e. Windows then you might prefer using: [source, bash] ---- jbang edit --open=[editor] helloworld.java ---- The editor used will be what is specified as the argument to `--open` or value of `JBANG_EDITOR` environment variable. The editor command must be available on the PATH to be executed from jbang. If you are executing `jbang edit --open=code helloworld.java` a `code` executable (visual studio code) must be on the PATH. Next to this you can pass the full path to the `open` parameter like in `--open=/usr/bin/code`. NOTE: On Windows you might need elevated privileges to create symbolic links. If you don't have permissions then the `edit` option will result in an error. To use it https://stackoverflow.com/a/24353758[enable symbolic links] for your user or run your shell/terminal as administrator to have this feature working. === Install of default vscodium editor [EXPERIMENTAL] If no editor available at all jbang will offer to install https://vscodium.com[VSCodium] (free/libre version of Visual Studio code) with default java extensions enabled in so called https://code.visualstudio.com/docs/editor/portable[""portable mode""]. Portable mode means all the installed binaries and configuration does not affect rest of your system; everything is stored in `~/.jbang/editor`. This automatic install and setup of editor is fully optional and if you have another IDE or editor already installed use it using `jbang edit --open=` or set JBANG_EDITOR environment variable to have jbang use it by default. === Live Editing You can also use `jbang edit --live` and `jbang` will launch your editor while watching for file changes and regenerate the temporary project to pick up changes in dependencies. === IDE and Editor support The `edit` feature been tested with the following IDE's: :sicons: https://simpleicons.org/icons .IDE's and Editors tested with `jbang` [width=75%,frame=none,grid=none] |=== |image:{sicons}/visualstudiocode.svg[50,50] https://code.visualstudio.com[Visual Studio Code] |image:{sicons}/eclipseide.svg[50,50] https://www.eclipse.org/downloads/download.php[Eclipse] |image:{sicons}/intellijidea.svg[50,50] https://www.jetbrains.com/idea/download[IntelliJ Idea] |image:{sicons}/apachenetbeanside.svg[50,50] https://netbeans.apache.org/download/[Apache NetBeans] |image:{sicons}/neovim.svg[50,50] https://github.com/neovim/neovim/wiki/Installing-Neovim[Neovim] w/ https://spacevim.org/use-vim-as-a-java-ide/[spacevim Java] |image:{sicons}/gnuemacs.svg[50,50] https://www.gnu.org/software/emacs/[Emacs] w/ https://www.spacemacs.org[Spacemacs Java] |=== The `edit` feature works with various IDE's - it generates a `build.gradle` to use with IDE's that understands Gradle directly. For speed and consistency `jbang` also generates IDE specific settings. Currently launchers and project files are generated for Eclipse and vscode. Intellij just reads `build.gradle` for now thus to run/debug you will need to manually set it up. Some editors like Code or IDEA are not per default executable / startable from the command line. Here are some helpfull documentations for supporting command line usage of different editors: * https://www.jetbrains.com/help/idea/working-with-the-ide-features-from-command-line.html[CLI support for IDEA] * https://code.visualstudio.com/docs/setup/mac[Terminal support for VS Code on macOS] == Debugging When running `.java` scripts with `jbang` you can pass the `--debug`-flag and the script will enable debug, suspend the execution and wait until you connect a debugger to port 4004. [source, bash] ---- jbang --debug helloworld.java Listening for transport dt_socket at address: 4004 ---- You can change the debug port and host by passing in a interface pattern and number to the debug argument, e.g., `--debug=*:4321`. This will make it use port 4321 and make it listen on all ('*') network interfaces. NOTE: Be sure to put a breakpoint in your IDE/debugger before you connect to make the debugger actually stop when you need it. === Debug jbang itself Java itself will add `JAVA_TOOL_OPTIONS` which will apply to `jbang` too. For finer and more explicit control the scripts, `jbang` will add `JBANG_JAVA_OPTIONS` to the call to `jbang` itself. Thus if you want to enable debug or other details for `jbang` set that environment variable. == Flight Recorder Flight recorder is a feature of the Java VM that lets you gather diagnostic and profiling data about your script. You can use `//JAVA_OPTIONS` to have full control over it; but for the easiest setup `jbang` lets you just run with `--jfr`, e.g., jbang --jfr myapp.java By default `--jfr` will start flight recorder and tell it to dump event recordings to `myapp.jfr` (i.e. using base name of the script as its filename). Then you can use tools like `jvisualvm` or `jmc` to explore the data. If you want to tweak the configuration you can pass flight recorder options, like `jbang --jfr=filename={baseName}.jfr,maxage=24h` where `{baseName}` will be replaced by the filename and then added `maxage=24h` to flight recording options. If you want further control use `//JAVAC_OPTS -XX:StartFlightRecording=` instead. == `java` and `javac` Options If you want to tweak memory settings or enable preview features you can setup the necessary options using `//JAVA_OPTS` and `//COMPILER_OPTS` as in the following example using Java 14 experimental `record` feature: [source, java] ---- ///usr/bin/env jbang ""$0"" ""$@"" ; exit $? //JAVAC_OPTIONS --enable-preview -source 14 <.> //JAVA_OPTIONS --enable-preview // <.> import static java.lang.System.*; public class records { record Point(int x, int y) {} public static void main(String[] args) { var p = new Point(2,4); out.println(p); } } ---- Since Java 9 https://docs.oracle.com/javase/9/tools/java.htm#GUID-3B1CE181-CD30-4178-9602-230B800D4FAE__USINGTHEJDK_JAVA_OPTIONSLAUNCHERENV-F3C0E3BA[JDK_JAVA_OPTIONS] and https://docs.oracle.com/javase/9/tools/javac.htm#GUID-AEEC9F07-CB49-4E96-8BC7-BCC2C7F725C9\\_\\_USINGJDK_JAVAC_OPTIONSENVIRONMENTVA-F3C76845[JDK_JAVAC_OPTIONS] are also picked up by the Java runtime and compiler automatically. For Java 8 and if you want to set explicitly only for `jbang` you can also add flags by setting `JBANG_JAVA_OPTIONS` and `JBANG_JAVAC_OPTIONS` respectively. === (Experimental) Application Class Data Sharing If your scripts uses a lot of classes Class Data Sharing might help on your startup. The following requires Java 13+. Using `--cds` jbang will build the jar with Application Class Data Sharing enabled and when run have it load shared class data. You can put `//CDS` in the java file to enable it by default, or simply use `--cds` to force it or `--no-cds` to turn it off no matter what the jbang script file contains. == Aliases To avoid remembering long paths and to enable easy launch of jbang scripts there is an `alias` command to setup and manage aliases to actual scripts. jbang alias add hello https://github.com/jbangdev/jbang-examples/blob/master/examples/helloworld.java will add an alias named `hello` pointing to that github url which then can be run using `jbang hello`. jbang alias list will show you all the aliases that are defined locally. === Implicit Alias Catalogs The aliases you create are stored locally (see <>), but Jbang can also use remote catalogs. You can access those catalogs explicitly (see <>) but it is much easier to use what we call ""implicit catalogs"", which are aliases that have a special format and Jbang is smart enough to know where to find their definition. Examples: `jbang hello@jbangdev` will run the alias `hello` as defined in `jbang-catalog.json` found in https://github.com/jbangdev/jbang-catalog. This allows anyone to provide a set of jbang scripts defined in their github, gitlab or bitbucket repositories. The full format is `@(/repository)(/branch)(~path)` allowing you to do things like: .Implicit Catalog Examples: |==== |Command | Description |`jbang hello@acme` |`hello` alias found in `acme/jbang-catalog/jbang-catalog.json` of the default branch searched on github, gitlab and bitbucket in that order. |`jbang hello@acme/mycatalog` |`hello` found in `acme/mycatalog/jbang-catalog.json` searched on github, gitlab and bitbucket in that order. |`jbang hello@acme/mycatalog/dev` |`hello` found in `acme/mycatalog/jbang-catalog.json` in the `dev` branch searched on github, gitlab and bitbucket in that order. |`jbang hello@acme~experimental` |`hello` found in `acme/jbang-catalog/experimental/jbang-catalog.json` |==== === Local Alias Catalogs Jbang will also look in the current directory for a `jbang-catalog.json` file and if it exists it will look up any aliases in there too. In fact it will look in several places in the following order: 1. Current directory, `./jbang-catalog.json` 2. In `.jbang/jbang-catalog.json` 3. In the parent directory, `../jbang-catalog.json` 4. In the parent's `.jbang` directory, ../.jbang/jbang-catalog.json` 5. And repeating steps 3 and 4 recursively upwards to the root of the file system 6. As the last step it will look in `$HOME/.jbang/jbang-catalog.json` Jbang will use any aliases defined in those files, but on top of that it will also look at the aliases defined in any catalogs mentioned in those files as well. Aliases defined in the file have preference over aliases found in any catalogs defined in the same file. When you create aliases using `jbang alias add`, or add catalogs using `jbang catalog add` the _same_ ordering will be used to determine where to store the alias or catalog. Btw, this will only take into account _existing_ files! So if no `jbang-catalog.json` file exists in the local directory it will _not_ be created for you, but Jbang will keep looking until it finds a file to use (as a last option it will always be written to `$HOME/.jbang/jbang-catalog.json`). This means that if you want to write the alias to `jbang-catalog.json` in your local folder you will either have to create the file first (eg by running `touch jbang-catalog.json`) or by explicitly specifying the file location: jbang alias add -f jbang-catalog.json hello https://github.com/jbangdev/jbang-examples/blob/master/examples/helloworld.java Btw, the flag `--show-origin` is very useful when listing aliases to find out where exactly an alias is defined: jbang alias list --show-origin == Catalogs Catalogs are lists of Aliases as defined in the previous section, but while the `alias` command is used to manage aliases within a catalog, the `catalog` command is for managing references to catalogs. This is mostly useful when dealing with remote catalogs. You can for example add a catalog like this: jbang catalog add demo https://github.com/jbangdev/jbang-catalog/blob/master/jbang-catalog.json or simply by using the same ""implicit"" catalog system described in <>: jbang catalog add demo jbangdev The aliases in that catalog are now available by adding `@demo` to their names. For example: $ jbang alias list demo env@demo = Dump table of Environment Variables gavsearch@demo = Search search.maven.org for maven artifacts. hello@demo = Script that says hello back for each argument properties@demo = Dump table of System properties $ jbang run hello@demo World! [jbang] Building jar... Hello World! In fact it's possible to run the alias just by using `jbang run hello`, the `@demo` part is only necessary when trying to disambiguate between aliases with the same name from different catalogs. You can list the available catalogs by running: jbang catalog list NB: The output will not only show the catalogs you defined yourself but also the ones that get added implicitly when running aliases as described in the section <>. == Java Agents You can activate a javaagent using `--javaagent=[=]` where agent can be a already packaged agent jar from file, http url or Maven Coordinate. It can also be a jbang script itself where you have put `//JAVAAGENT` to activate agent packaging. You can create a basic agent using `jbang init -t agent myagent.java` to get started. == Bash/Zsh auto-completion If you are using bash or zsh in your terminal you can get auto-completion by running the following: [source, bash] ---- source <(jbang completion) ---- == Caching In previous versions of `jbang`, Java 10+ direct launch of `.java` was used, but since v0.6 `jbang` works with Java 8 and thus it needs to do a separate compile step. Besides now working with Java 8 this also allows to cache the compiled script and thus launch faster on consecutive runs. The caching goes to `~/.jbang/cache` by default, you can run `jbang cache clear` to remove all cache data from this folder. == Install apps [EXPERIMENTAL] Since version 0.56 jbang comes with ability to setup jbang to put scripts/apps into your `PATH` using `jbang app`. This is useful to easily make scripts available from anywhere on any Operating System; To get started run `jbang app setup` this will on Windows modify your system wide `PATH` to include a folder managed by jbang. On bash/zsh based shells it will setup `PATH` in your `bashrc` or `zshrc` file(s.) Once setup, you can use `jbang app install ` to install that script into the jbang managed path. i.e. `jbang app install myscript.java` will add `myscript` as a command you can run. You can also use aliases, like `jbang app install gavsearch@jbangdev`. If you have two script/apps with same name or just want to use a specific name you can use `--name` to control the generated command: `jbang app install --name mvnsearch gavsearch@jbangdev` If you want to see which are already installed use `jbang list` and you can use `jbang uinstall ` to uninstall the script/app. == Build Integration [EXPERIMENTAL] While `jbang` prepares and builds the underlying jar used for launch there is since v0.40 (for now) experimental API allowing user included dependencies to influence the generated jar and possible native image. An example use case enabled by this is to have full Quarkus integration, `jbang quarkuscode.java` will have Quarkus participate to perform its build time optimizations rather than doing it at runtime every time. It works as following: Before the jar is created `jbang` will scan the classpath for `META-INF/jbang-integration.list`. Any classes listed in this file will be loaded and jbang will expect and call the following method on these classes: [source,java] ---- /** * * @param param build dir directory which will be made into a jar when build is done * @param pomFile location of pom.xml representing the projects dependencies * @param dependencies list of GAV to Path of artifact/classpath dependencies * @param nativeImage true if --native been requested * @return Map map of returns; special keys are ""native-image"" which is a and ""files"" to * return native-image to be run and list of files to get written to the output directory. * */ Map postBuild(Path builddir, Path pomFile, List> dependencies, boolean nativeImage) ---- Still very experimental and bound to change. Example of its use can be found in https://github.com/quarkusio/quarkus/pull/11542[Quarkus]. == Cheatsheet You can get examples on running/using `jbang` using https://github.com/cheat/cheat[cheat] command with `cheat jbang`. == FAQ [qanda] Why the name j'bang?:: I was reading up on how to use the new shebang (#!) feature support in Java 10 and came up with the idea of port `kscript` to Java and needed a name. From there came j'bang which is a ""bad"" spelling of how shebang is pronounced in French. Why use gradle resource locators rather than ?:: kscript used it and it's nice as it is a one-liner and easily parsable. How does this compare to ?:: After doing `jbang` I've learned about similar projects and thought it would be nice with some comparison; + https://github.com/scijava/jgo[jgo]: an alternative way to launch jars using maven coordinates. Implemented in python, depends on Java and Maven to be available. Not really for scripting but a novel way to launch java apps already packaged as a maven dependency. + Why would I use Java to write scripts ? Java sucks for that... Use groovy, kotlin, scala, etc. instead!:: Well, does it really suck ? With Java 8 streams, static imports and greatly improved standard java libraries it is very close to what kscript and grape look like. With the following advantages: + * works with plain Java without installing additional compiler/build tools * all IDE's support editing .java files very well, content assist, etc. * great debugging + And to be honest I built `jbang` just to see if I could and get my Java skills refreshed for the newer features in the language. Use it at your own risk :) Why not use normal shebang(`#!`) in the header ?:: You can use normal shebang (`#!/usr/bin/env jbang`) and Java 10+ will actually work with it from the command line. Not recommended though as many tools and especially IDE's will start complaining about syntax errors as they don't ignore the first line in this case. + By using the `//` form it is treated as both a bash/shell file AND a valid java file and thus works everywhere a java file will work. + It's worth noting that Go https://golangcookbook.com/chapters/running/shebang/[uses a similar approach] which is also where I learned it from. HELP! My code formatter keeps breaking my `//` directives!:: When using automated code formatting tools, some care and configuration must be made to prevent the tooling from rewriting and preventing `jbang` from working as expected. + Use the following configuration blocks to correctly configure your tool: + .Configuration Tool Settings: |==== | Formatting Tool | Configuration | Clang Format a| [source] ---- CommentPragmas: '^[^ ]' ---- |==== == Thanks `jbang` was heavily inspired by how `https://github.com/holgerbrandl/kscript[kscript]` by Holger Brand works. ",12496,False,2276.6752367999516,median " // DO NOT EDIT ! // This file is generated using the MantaFlow preprocessor (prep generate). /****************************************************************************** * * MantaFlow fluid solver framework * Copyright 2011 Tobias Pfaff, Nils Thuerey * * This program is free software, distributed under the terms of the * GNU General Public License (GPL) * http://www.gnu.org/licenses * * Set boundary conditions, gravity * ******************************************************************************/ #include ""vectorbase.h"" #include ""grid.h"" #include ""commonkernels.h"" #include ""particle.h"" using namespace std; namespace Manta { //! add constant force between fl/fl and fl/em cells struct KnApplyForceField : public KernelBase { KnApplyForceField(const FlagGrid &flags, MACGrid &vel, const Grid &force, const Grid *include, bool additive, bool isMAC) : KernelBase(&flags, 1), flags(flags), vel(vel), force(force), include(include), additive(additive), isMAC(isMAC) { runMessage(); run(); } inline void op(int i, int j, int k, const FlagGrid &flags, MACGrid &vel, const Grid &force, const Grid *include, bool additive, bool isMAC) const { bool curFluid = flags.isFluid(i, j, k); bool curEmpty = flags.isEmpty(i, j, k); if (!curFluid && !curEmpty) return; if (include && ((*include)(i, j, k) > 0.)) return; Real forceX = (isMAC) ? force(i, j, k).x : 0.5 * (force(i - 1, j, k).x + force(i, j, k).x); Real forceY = (isMAC) ? force(i, j, k).y : 0.5 * (force(i, j - 1, k).y + force(i, j, k).y); Real forceZ = 0.; if (vel.is3D()) forceZ = (isMAC) ? force(i, j, k).z : 0.5 * (force(i, j, k - 1).z + force(i, j, k).z); if (flags.isFluid(i - 1, j, k) || (curFluid && flags.isEmpty(i - 1, j, k))) vel(i, j, k).x = (additive) ? vel(i, j, k).x + forceX : forceX; if (flags.isFluid(i, j - 1, k) || (curFluid && flags.isEmpty(i, j - 1, k))) vel(i, j, k).y = (additive) ? vel(i, j, k).y + forceY : forceY; if (vel.is3D() && (flags.isFluid(i, j, k - 1) || (curFluid && flags.isEmpty(i, j, k - 1)))) vel(i, j, k).z = (additive) ? vel(i, j, k).z + forceZ : forceZ; } inline const FlagGrid &getArg0() { return flags; } typedef FlagGrid type0; inline MACGrid &getArg1() { return vel; } typedef MACGrid type1; inline const Grid &getArg2() { return force; } typedef Grid type2; inline const Grid *getArg3() { return include; } typedef Grid type3; inline bool &getArg4() { return additive; } typedef bool type4; inline bool &getArg5() { return isMAC; } typedef bool type5; void runMessage() { debMsg(""Executing kernel KnApplyForceField "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 1; j < _maxY; j++) for (int i = 1; i < _maxX; i++) op(i, j, k, flags, vel, force, include, additive, isMAC); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 1; i < _maxX; i++) op(i, j, k, flags, vel, force, include, additive, isMAC); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(1, maxY), *this); } const FlagGrid &flags; MACGrid &vel; const Grid &force; const Grid *include; bool additive; bool isMAC; }; //! add constant force between fl/fl and fl/em cells struct KnApplyForce : public KernelBase { KnApplyForce( const FlagGrid &flags, MACGrid &vel, Vec3 force, const Grid *exclude, bool additive) : KernelBase(&flags, 1), flags(flags), vel(vel), force(force), exclude(exclude), additive(additive) { runMessage(); run(); } inline void op(int i, int j, int k, const FlagGrid &flags, MACGrid &vel, Vec3 force, const Grid *exclude, bool additive) const { bool curFluid = flags.isFluid(i, j, k); bool curEmpty = flags.isEmpty(i, j, k); if (!curFluid && !curEmpty) return; if (exclude && ((*exclude)(i, j, k) < 0.)) return; if (flags.isFluid(i - 1, j, k) || (curFluid && flags.isEmpty(i - 1, j, k))) vel(i, j, k).x = (additive) ? vel(i, j, k).x + force.x : force.x; if (flags.isFluid(i, j - 1, k) || (curFluid && flags.isEmpty(i, j - 1, k))) vel(i, j, k).y = (additive) ? vel(i, j, k).y + force.y : force.y; if (vel.is3D() && (flags.isFluid(i, j, k - 1) || (curFluid && flags.isEmpty(i, j, k - 1)))) vel(i, j, k).z = (additive) ? vel(i, j, k).z + force.z : force.z; } inline const FlagGrid &getArg0() { return flags; } typedef FlagGrid type0; inline MACGrid &getArg1() { return vel; } typedef MACGrid type1; inline Vec3 &getArg2() { return force; } typedef Vec3 type2; inline const Grid *getArg3() { return exclude; } typedef Grid type3; inline bool &getArg4() { return additive; } typedef bool type4; void runMessage() { debMsg(""Executing kernel KnApplyForce "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 1; j < _maxY; j++) for (int i = 1; i < _maxX; i++) op(i, j, k, flags, vel, force, exclude, additive); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 1; i < _maxX; i++) op(i, j, k, flags, vel, force, exclude, additive); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(1, maxY), *this); } const FlagGrid &flags; MACGrid &vel; Vec3 force; const Grid *exclude; bool additive; }; //! add gravity forces to all fluid cells, optionally adapts to different grid sizes automatically void addGravity(const FlagGrid &flags, MACGrid &vel, Vec3 gravity, const Grid *exclude = NULL, bool scale = true) { float gridScale = (scale) ? flags.getDx() : 1; Vec3 f = gravity * flags.getParent()->getDt() / gridScale; KnApplyForce(flags, vel, f, exclude, true); } static PyObject *_W_0(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""addGravity"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; const FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); MACGrid &vel = *_args.getPtr(""vel"", 1, &_lock); Vec3 gravity = _args.get(""gravity"", 2, &_lock); const Grid *exclude = _args.getPtrOpt>(""exclude"", 3, NULL, &_lock); bool scale = _args.getOpt(""scale"", 4, true, &_lock); _retval = getPyNone(); addGravity(flags, vel, gravity, exclude, scale); _args.check(); } pbFinalizePlugin(parent, ""addGravity"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""addGravity"", e.what()); return 0; } } static const Pb::Register _RP_addGravity("""", ""addGravity"", _W_0); extern ""C"" { void PbRegister_addGravity() { KEEP_UNUSED(_RP_addGravity); } } //! Deprecated: use addGravity(scale=false) instead void addGravityNoScale(const FlagGrid &flags, MACGrid &vel, const Vec3 &gravity, const Grid *exclude = NULL) { addGravity(flags, vel, gravity, exclude, false); } static PyObject *_W_1(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""addGravityNoScale"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; const FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); MACGrid &vel = *_args.getPtr(""vel"", 1, &_lock); const Vec3 &gravity = _args.get(""gravity"", 2, &_lock); const Grid *exclude = _args.getPtrOpt>(""exclude"", 3, NULL, &_lock); _retval = getPyNone(); addGravityNoScale(flags, vel, gravity, exclude); _args.check(); } pbFinalizePlugin(parent, ""addGravityNoScale"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""addGravityNoScale"", e.what()); return 0; } } static const Pb::Register _RP_addGravityNoScale("""", ""addGravityNoScale"", _W_1); extern ""C"" { void PbRegister_addGravityNoScale() { KEEP_UNUSED(_RP_addGravityNoScale); } } //! kernel to add Buoyancy force struct KnAddBuoyancy : public KernelBase { KnAddBuoyancy(const FlagGrid &flags, const Grid &factor, MACGrid &vel, Vec3 strength) : KernelBase(&flags, 1), flags(flags), factor(factor), vel(vel), strength(strength) { runMessage(); run(); } inline void op(int i, int j, int k, const FlagGrid &flags, const Grid &factor, MACGrid &vel, Vec3 strength) const { if (!flags.isFluid(i, j, k)) return; if (flags.isFluid(i - 1, j, k)) vel(i, j, k).x += (0.5 * strength.x) * (factor(i, j, k) + factor(i - 1, j, k)); if (flags.isFluid(i, j - 1, k)) vel(i, j, k).y += (0.5 * strength.y) * (factor(i, j, k) + factor(i, j - 1, k)); if (vel.is3D() && flags.isFluid(i, j, k - 1)) vel(i, j, k).z += (0.5 * strength.z) * (factor(i, j, k) + factor(i, j, k - 1)); } inline const FlagGrid &getArg0() { return flags; } typedef FlagGrid type0; inline const Grid &getArg1() { return factor; } typedef Grid type1; inline MACGrid &getArg2() { return vel; } typedef MACGrid type2; inline Vec3 &getArg3() { return strength; } typedef Vec3 type3; void runMessage() { debMsg(""Executing kernel KnAddBuoyancy "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 1; j < _maxY; j++) for (int i = 1; i < _maxX; i++) op(i, j, k, flags, factor, vel, strength); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 1; i < _maxX; i++) op(i, j, k, flags, factor, vel, strength); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(1, maxY), *this); } const FlagGrid &flags; const Grid &factor; MACGrid &vel; Vec3 strength; }; //! add Buoyancy force based on factor (e.g. smoke density), optionally adapts to different grid //! sizes automatically void addBuoyancy(const FlagGrid &flags, const Grid &density, MACGrid &vel, Vec3 gravity, Real coefficient = 1., bool scale = true) { float gridScale = (scale) ? flags.getDx() : 1; Vec3 f = -gravity * flags.getParent()->getDt() / gridScale * coefficient; KnAddBuoyancy(flags, density, vel, f); } static PyObject *_W_2(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""addBuoyancy"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; const FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); const Grid &density = *_args.getPtr>(""density"", 1, &_lock); MACGrid &vel = *_args.getPtr(""vel"", 2, &_lock); Vec3 gravity = _args.get(""gravity"", 3, &_lock); Real coefficient = _args.getOpt(""coefficient"", 4, 1., &_lock); bool scale = _args.getOpt(""scale"", 5, true, &_lock); _retval = getPyNone(); addBuoyancy(flags, density, vel, gravity, coefficient, scale); _args.check(); } pbFinalizePlugin(parent, ""addBuoyancy"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""addBuoyancy"", e.what()); return 0; } } static const Pb::Register _RP_addBuoyancy("""", ""addBuoyancy"", _W_2); extern ""C"" { void PbRegister_addBuoyancy() { KEEP_UNUSED(_RP_addBuoyancy); } } // inflow / outflow boundaries //! helper to parse openbounds string [xXyYzZ] , convert to vec3 inline void convertDescToVec(const string &desc, Vector3D &lo, Vector3D &up) { for (size_t i = 0; i < desc.size(); i++) { if (desc[i] == 'x') lo.x = true; else if (desc[i] == 'y') lo.y = true; else if (desc[i] == 'z') lo.z = true; else if (desc[i] == 'X') up.x = true; else if (desc[i] == 'Y') up.y = true; else if (desc[i] == 'Z') up.z = true; else errMsg(""invalid character in boundary description string. Only [xyzXYZ] allowed.""); } } //! add empty and outflow flag to cells of open boundaries void setOpenBound(FlagGrid &flags, int bWidth, string openBound = """", int type = FlagGrid::TypeOutflow | FlagGrid::TypeEmpty) { if (openBound == """") return; Vector3D lo, up; convertDescToVec(openBound, lo, up); FOR_IJK(flags) { bool loX = lo.x && i <= bWidth; // a cell which belongs to the lower x open bound bool loY = lo.y && j <= bWidth; bool upX = up.x && i >= flags.getSizeX() - bWidth - 1; // a cell which belongs to the upper x open bound bool upY = up.y && j >= flags.getSizeY() - bWidth - 1; bool innerI = i > bWidth && i < flags.getSizeX() - bWidth - 1; // a cell which does not belong to the lower or upper x bound bool innerJ = j > bWidth && j < flags.getSizeY() - bWidth - 1; // when setting boundaries to open: don't set shared part of wall to empty if neighboring wall // is not open if ((!flags.is3D()) && (loX || upX || loY || upY)) { if ((loX || upX || innerI) && (loY || upY || innerJ) && flags.isObstacle(i, j, k)) flags(i, j, k) = type; } else { bool loZ = lo.z && k <= bWidth; // a cell which belongs to the lower z open bound bool upZ = up.z && k >= flags.getSizeZ() - bWidth - 1; // a cell which belongs to the upper z open bound bool innerK = k > bWidth && k < flags.getSizeZ() - bWidth - 1; // a cell which does not belong to the lower or upper z bound if (loX || upX || loY || upY || loZ || upZ) { if ((loX || upX || innerI) && (loY || upY || innerJ) && (loZ || upZ || innerK) && flags.isObstacle(i, j, k)) flags(i, j, k) = type; } } } } static PyObject *_W_3(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""setOpenBound"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); int bWidth = _args.get(""bWidth"", 1, &_lock); string openBound = _args.getOpt(""openBound"", 2, """", &_lock); int type = _args.getOpt(""type"", 3, FlagGrid::TypeOutflow | FlagGrid::TypeEmpty, &_lock); _retval = getPyNone(); setOpenBound(flags, bWidth, openBound, type); _args.check(); } pbFinalizePlugin(parent, ""setOpenBound"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""setOpenBound"", e.what()); return 0; } } static const Pb::Register _RP_setOpenBound("""", ""setOpenBound"", _W_3); extern ""C"" { void PbRegister_setOpenBound() { KEEP_UNUSED(_RP_setOpenBound); } } //! delete fluid and ensure empty flag in outflow cells, delete particles and density and set phi //! to 0.5 void resetOutflow(FlagGrid &flags, Grid *phi = 0, BasicParticleSystem *parts = 0, Grid *real = 0, Grid *index = 0, ParticleIndexSystem *indexSys = 0) { // check if phi and parts -> pindex and gpi already created -> access particles from cell index, // avoid extra looping over particles if (parts && (!index || !indexSys)) { if (phi) debMsg( ""resetOpenBound for phi and particles, but missing index and indexSys for enhanced "" ""particle access!"", 1); for (int idx = 0; idx < (int)parts->size(); idx++) if (parts->isActive(idx) && flags.isInBounds(parts->getPos(idx)) && flags.isOutflow(parts->getPos(idx))) parts->kill(idx); } FOR_IJK(flags) { if (flags.isOutflow(i, j, k)) { flags(i, j, k) = (flags(i, j, k) | FlagGrid::TypeEmpty) & ~FlagGrid::TypeFluid; // make sure there is not fluid flag set and to reset // the empty flag // the particles in a cell i,j,k are particles[index(i,j,k)] to particles[index(i+1,j,k)-1] if (parts && index && indexSys) { int isysIdxS = index->index(i, j, k); int pStart = (*index)(isysIdxS), pEnd = 0; if (flags.isInBounds(isysIdxS + 1)) pEnd = (*index)(isysIdxS + 1); else pEnd = indexSys->size(); // now loop over particles in cell for (int p = pStart; p < pEnd; ++p) { int psrc = (*indexSys)[p].sourceIndex; if (parts->isActive(psrc) && flags.isInBounds(parts->getPos(psrc))) parts->kill(psrc); } } if (phi) (*phi)(i, j, k) = 0.5; if (real) (*real)(i, j, k) = 0; } } if (parts) parts->doCompress(); } static PyObject *_W_4(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""resetOutflow"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); Grid *phi = _args.getPtrOpt>(""phi"", 1, 0, &_lock); BasicParticleSystem *parts = _args.getPtrOpt(""parts"", 2, 0, &_lock); Grid *real = _args.getPtrOpt>(""real"", 3, 0, &_lock); Grid *index = _args.getPtrOpt>(""index"", 4, 0, &_lock); ParticleIndexSystem *indexSys = _args.getPtrOpt( ""indexSys"", 5, 0, &_lock); _retval = getPyNone(); resetOutflow(flags, phi, parts, real, index, indexSys); _args.check(); } pbFinalizePlugin(parent, ""resetOutflow"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""resetOutflow"", e.what()); return 0; } } static const Pb::Register _RP_resetOutflow("""", ""resetOutflow"", _W_4); extern ""C"" { void PbRegister_resetOutflow() { KEEP_UNUSED(_RP_resetOutflow); } } //! enforce a constant inflow/outflow at the grid boundaries struct KnSetInflow : public KernelBase { KnSetInflow(MACGrid &vel, int dim, int p0, const Vec3 &val) : KernelBase(&vel, 0), vel(vel), dim(dim), p0(p0), val(val) { runMessage(); run(); } inline void op(int i, int j, int k, MACGrid &vel, int dim, int p0, const Vec3 &val) const { Vec3i p(i, j, k); if (p[dim] == p0 || p[dim] == p0 + 1) vel(i, j, k) = val; } inline MACGrid &getArg0() { return vel; } typedef MACGrid type0; inline int &getArg1() { return dim; } typedef int type1; inline int &getArg2() { return p0; } typedef int type2; inline const Vec3 &getArg3() { return val; } typedef Vec3 type3; void runMessage() { debMsg(""Executing kernel KnSetInflow "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 0; j < _maxY; j++) for (int i = 0; i < _maxX; i++) op(i, j, k, vel, dim, p0, val); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 0; i < _maxX; i++) op(i, j, k, vel, dim, p0, val); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(0, maxY), *this); } MACGrid &vel; int dim; int p0; const Vec3 &val; }; //! enforce a constant inflow/outflow at the grid boundaries void setInflowBcs(MACGrid &vel, string dir, Vec3 value) { for (size_t i = 0; i < dir.size(); i++) { if (dir[i] >= 'x' && dir[i] <= 'z') { int dim = dir[i] - 'x'; KnSetInflow(vel, dim, 0, value); } else if (dir[i] >= 'X' && dir[i] <= 'Z') { int dim = dir[i] - 'X'; KnSetInflow(vel, dim, vel.getSize()[dim] - 1, value); } else errMsg(""invalid character in direction string. Only [xyzXYZ] allowed.""); } } static PyObject *_W_5(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""setInflowBcs"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; MACGrid &vel = *_args.getPtr(""vel"", 0, &_lock); string dir = _args.get(""dir"", 1, &_lock); Vec3 value = _args.get(""value"", 2, &_lock); _retval = getPyNone(); setInflowBcs(vel, dir, value); _args.check(); } pbFinalizePlugin(parent, ""setInflowBcs"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""setInflowBcs"", e.what()); return 0; } } static const Pb::Register _RP_setInflowBcs("""", ""setInflowBcs"", _W_5); extern ""C"" { void PbRegister_setInflowBcs() { KEEP_UNUSED(_RP_setInflowBcs); } } // set obstacle boundary conditions //! set no-stick wall boundary condition between ob/fl and ob/ob cells struct KnSetWallBcs : public KernelBase { KnSetWallBcs(const FlagGrid &flags, MACGrid &vel, const MACGrid *obvel) : KernelBase(&flags, 0), flags(flags), vel(vel), obvel(obvel) { runMessage(); run(); } inline void op( int i, int j, int k, const FlagGrid &flags, MACGrid &vel, const MACGrid *obvel) const { bool curFluid = flags.isFluid(i, j, k); bool curObs = flags.isObstacle(i, j, k); Vec3 bcsVel(0., 0., 0.); if (!curFluid && !curObs) return; if (obvel) { bcsVel.x = (*obvel)(i, j, k).x; bcsVel.y = (*obvel)(i, j, k).y; if ((*obvel).is3D()) bcsVel.z = (*obvel)(i, j, k).z; } // we use i>0 instead of bnd=1 to check outer wall if (i > 0 && flags.isObstacle(i - 1, j, k)) vel(i, j, k).x = bcsVel.x; if (i > 0 && curObs && flags.isFluid(i - 1, j, k)) vel(i, j, k).x = bcsVel.x; if (j > 0 && flags.isObstacle(i, j - 1, k)) vel(i, j, k).y = bcsVel.y; if (j > 0 && curObs && flags.isFluid(i, j - 1, k)) vel(i, j, k).y = bcsVel.y; if (!vel.is3D()) { vel(i, j, k).z = 0; } else { if (k > 0 && flags.isObstacle(i, j, k - 1)) vel(i, j, k).z = bcsVel.z; if (k > 0 && curObs && flags.isFluid(i, j, k - 1)) vel(i, j, k).z = bcsVel.z; } if (curFluid) { if ((i > 0 && flags.isStick(i - 1, j, k)) || (i < flags.getSizeX() - 1 && flags.isStick(i + 1, j, k))) vel(i, j, k).y = vel(i, j, k).z = 0; if ((j > 0 && flags.isStick(i, j - 1, k)) || (j < flags.getSizeY() - 1 && flags.isStick(i, j + 1, k))) vel(i, j, k).x = vel(i, j, k).z = 0; if (vel.is3D() && ((k > 0 && flags.isStick(i, j, k - 1)) || (k < flags.getSizeZ() - 1 && flags.isStick(i, j, k + 1)))) vel(i, j, k).x = vel(i, j, k).y = 0; } } inline const FlagGrid &getArg0() { return flags; } typedef FlagGrid type0; inline MACGrid &getArg1() { return vel; } typedef MACGrid type1; inline const MACGrid *getArg2() { return obvel; } typedef MACGrid type2; void runMessage() { debMsg(""Executing kernel KnSetWallBcs "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 0; j < _maxY; j++) for (int i = 0; i < _maxX; i++) op(i, j, k, flags, vel, obvel); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 0; i < _maxX; i++) op(i, j, k, flags, vel, obvel); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(0, maxY), *this); } const FlagGrid &flags; MACGrid &vel; const MACGrid *obvel; }; //! set wall BCs for fill fraction mode, note - only needs obstacle SDF struct KnSetWallBcsFrac : public KernelBase { KnSetWallBcsFrac(const FlagGrid &flags, const MACGrid &vel, MACGrid &velTarget, const MACGrid *obvel, const Grid *phiObs, const int &boundaryWidth = 0) : KernelBase(&flags, 0), flags(flags), vel(vel), velTarget(velTarget), obvel(obvel), phiObs(phiObs), boundaryWidth(boundaryWidth) { runMessage(); run(); } inline void op(int i, int j, int k, const FlagGrid &flags, const MACGrid &vel, MACGrid &velTarget, const MACGrid *obvel, const Grid *phiObs, const int &boundaryWidth = 0) const { bool curFluid = flags.isFluid(i, j, k); bool curObs = flags.isObstacle(i, j, k); velTarget(i, j, k) = vel(i, j, k); if (!curFluid && !curObs) return; // zero normal component in all obstacle regions if (flags.isInBounds(Vec3i(i, j, k), 1)) { if (curObs | flags.isObstacle(i - 1, j, k)) { Vec3 dphi(0., 0., 0.); const Real tmp1 = (phiObs->get(i, j, k) + phiObs->get(i - 1, j, k)) * .5; Real tmp2 = (phiObs->get(i, j + 1, k) + phiObs->get(i - 1, j + 1, k)) * .5; Real phi1 = (tmp1 + tmp2) * .5; tmp2 = (phiObs->get(i, j - 1, k) + phiObs->get(i - 1, j - 1, k)) * .5; Real phi2 = (tmp1 + tmp2) * .5; dphi.x = phiObs->get(i, j, k) - phiObs->get(i - 1, j, k); dphi.y = phi1 - phi2; if (phiObs->is3D()) { tmp2 = (phiObs->get(i, j, k + 1) + phiObs->get(i - 1, j, k + 1)) * .5; phi1 = (tmp1 + tmp2) * .5; tmp2 = (phiObs->get(i, j, k - 1) + phiObs->get(i - 1, j, k - 1)) * .5; phi2 = (tmp1 + tmp2) * .5; dphi.z = phi1 - phi2; } normalize(dphi); Vec3 velMAC = vel.getAtMACX(i, j, k); velTarget(i, j, k).x = velMAC.x - dot(dphi, velMAC) * dphi.x; } if (curObs | flags.isObstacle(i, j - 1, k)) { Vec3 dphi(0., 0., 0.); const Real tmp1 = (phiObs->get(i, j, k) + phiObs->get(i, j - 1, k)) * .5; Real tmp2 = (phiObs->get(i + 1, j, k) + phiObs->get(i + 1, j - 1, k)) * .5; Real phi1 = (tmp1 + tmp2) * .5; tmp2 = (phiObs->get(i - 1, j, k) + phiObs->get(i - 1, j - 1, k)) * .5; Real phi2 = (tmp1 + tmp2) * .5; dphi.x = phi1 - phi2; dphi.y = phiObs->get(i, j, k) - phiObs->get(i, j - 1, k); if (phiObs->is3D()) { tmp2 = (phiObs->get(i, j, k + 1) + phiObs->get(i, j - 1, k + 1)) * .5; phi1 = (tmp1 + tmp2) * .5; tmp2 = (phiObs->get(i, j, k - 1) + phiObs->get(i, j - 1, k - 1)) * .5; phi2 = (tmp1 + tmp2) * .5; dphi.z = phi1 - phi2; } normalize(dphi); Vec3 velMAC = vel.getAtMACY(i, j, k); velTarget(i, j, k).y = velMAC.y - dot(dphi, velMAC) * dphi.y; } if (phiObs->is3D() && (curObs | flags.isObstacle(i, j, k - 1))) { Vec3 dphi(0., 0., 0.); const Real tmp1 = (phiObs->get(i, j, k) + phiObs->get(i, j, k - 1)) * .5; Real tmp2; tmp2 = (phiObs->get(i + 1, j, k) + phiObs->get(i + 1, j, k - 1)) * .5; Real phi1 = (tmp1 + tmp2) * .5; tmp2 = (phiObs->get(i - 1, j, k) + phiObs->get(i - 1, j, k - 1)) * .5; Real phi2 = (tmp1 + tmp2) * .5; dphi.x = phi1 - phi2; tmp2 = (phiObs->get(i, j + 1, k) + phiObs->get(i, j + 1, k - 1)) * .5; phi1 = (tmp1 + tmp2) * .5; tmp2 = (phiObs->get(i, j - 1, k) + phiObs->get(i, j - 1, k - 1)) * .5; phi2 = (tmp1 + tmp2) * .5; dphi.y = phi1 - phi2; dphi.z = phiObs->get(i, j, k) - phiObs->get(i, j, k - 1); normalize(dphi); Vec3 velMAC = vel.getAtMACZ(i, j, k); velTarget(i, j, k).z = velMAC.z - dot(dphi, velMAC) * dphi.z; } } // not at boundary } inline const FlagGrid &getArg0() { return flags; } typedef FlagGrid type0; inline const MACGrid &getArg1() { return vel; } typedef MACGrid type1; inline MACGrid &getArg2() { return velTarget; } typedef MACGrid type2; inline const MACGrid *getArg3() { return obvel; } typedef MACGrid type3; inline const Grid *getArg4() { return phiObs; } typedef Grid type4; inline const int &getArg5() { return boundaryWidth; } typedef int type5; void runMessage() { debMsg(""Executing kernel KnSetWallBcsFrac "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 0; j < _maxY; j++) for (int i = 0; i < _maxX; i++) op(i, j, k, flags, vel, velTarget, obvel, phiObs, boundaryWidth); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 0; i < _maxX; i++) op(i, j, k, flags, vel, velTarget, obvel, phiObs, boundaryWidth); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(0, maxY), *this); } const FlagGrid &flags; const MACGrid &vel; MACGrid &velTarget; const MACGrid *obvel; const Grid *phiObs; const int &boundaryWidth; }; //! set zero normal velocity boundary condition on walls // (optionally with second order accuracy using the obstacle SDF , fractions grid currentlyl not // needed) void setWallBcs(const FlagGrid &flags, MACGrid &vel, const MACGrid *obvel = 0, const MACGrid *fractions = 0, const Grid *phiObs = 0, int boundaryWidth = 0) { if (!phiObs || !fractions) { KnSetWallBcs(flags, vel, obvel); } else { MACGrid tmpvel(vel.getParent()); KnSetWallBcsFrac(flags, vel, tmpvel, obvel, phiObs, boundaryWidth); vel.swap(tmpvel); } } static PyObject *_W_6(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""setWallBcs"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; const FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); MACGrid &vel = *_args.getPtr(""vel"", 1, &_lock); const MACGrid *obvel = _args.getPtrOpt(""obvel"", 2, 0, &_lock); const MACGrid *fractions = _args.getPtrOpt(""fractions"", 3, 0, &_lock); const Grid *phiObs = _args.getPtrOpt>(""phiObs"", 4, 0, &_lock); int boundaryWidth = _args.getOpt(""boundaryWidth"", 5, 0, &_lock); _retval = getPyNone(); setWallBcs(flags, vel, obvel, fractions, phiObs, boundaryWidth); _args.check(); } pbFinalizePlugin(parent, ""setWallBcs"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""setWallBcs"", e.what()); return 0; } } static const Pb::Register _RP_setWallBcs("""", ""setWallBcs"", _W_6); extern ""C"" { void PbRegister_setWallBcs() { KEEP_UNUSED(_RP_setWallBcs); } } //! add Forces between fl/fl and fl/em cells (interpolate cell centered forces to MAC grid) struct KnAddForceIfLower : public KernelBase { KnAddForceIfLower(const FlagGrid &flags, MACGrid &vel, const Grid &force) : KernelBase(&flags, 1), flags(flags), vel(vel), force(force) { runMessage(); run(); } inline void op( int i, int j, int k, const FlagGrid &flags, MACGrid &vel, const Grid &force) const { bool curFluid = flags.isFluid(i, j, k); bool curEmpty = flags.isEmpty(i, j, k); if (!curFluid && !curEmpty) return; if (flags.isFluid(i - 1, j, k) || (curFluid && flags.isEmpty(i - 1, j, k))) { Real forceMACX = 0.5 * (force(i - 1, j, k).x + force(i, j, k).x); Real min = std::min(vel(i, j, k).x, forceMACX); Real max = std::max(vel(i, j, k).x, forceMACX); Real sum = vel(i, j, k).x + forceMACX; vel(i, j, k).x = (forceMACX > 0) ? std::min(sum, max) : std::max(sum, min); } if (flags.isFluid(i, j - 1, k) || (curFluid && flags.isEmpty(i, j - 1, k))) { Real forceMACY = 0.5 * (force(i, j - 1, k).y + force(i, j, k).y); Real min = std::min(vel(i, j, k).y, forceMACY); Real max = std::max(vel(i, j, k).y, forceMACY); Real sum = vel(i, j, k).y + forceMACY; vel(i, j, k).y = (forceMACY > 0) ? std::min(sum, max) : std::max(sum, min); } if (vel.is3D() && (flags.isFluid(i, j, k - 1) || (curFluid && flags.isEmpty(i, j, k - 1)))) { Real forceMACZ = 0.5 * (force(i, j, k - 1).z + force(i, j, k).z); Real min = std::min(vel(i, j, k).z, forceMACZ); Real max = std::max(vel(i, j, k).z, forceMACZ); Real sum = vel(i, j, k).z + forceMACZ; vel(i, j, k).z = (forceMACZ > 0) ? std::min(sum, max) : std::max(sum, min); } } inline const FlagGrid &getArg0() { return flags; } typedef FlagGrid type0; inline MACGrid &getArg1() { return vel; } typedef MACGrid type1; inline const Grid &getArg2() { return force; } typedef Grid type2; void runMessage() { debMsg(""Executing kernel KnAddForceIfLower "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 1; j < _maxY; j++) for (int i = 1; i < _maxX; i++) op(i, j, k, flags, vel, force); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 1; i < _maxX; i++) op(i, j, k, flags, vel, force); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(1, maxY), *this); } const FlagGrid &flags; MACGrid &vel; const Grid &force; }; // Initial velocity for smoke void setInitialVelocity(const FlagGrid &flags, MACGrid &vel, const Grid &invel) { KnAddForceIfLower(flags, vel, invel); } static PyObject *_W_7(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""setInitialVelocity"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; const FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); MACGrid &vel = *_args.getPtr(""vel"", 1, &_lock); const Grid &invel = *_args.getPtr>(""invel"", 2, &_lock); _retval = getPyNone(); setInitialVelocity(flags, vel, invel); _args.check(); } pbFinalizePlugin(parent, ""setInitialVelocity"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""setInitialVelocity"", e.what()); return 0; } } static const Pb::Register _RP_setInitialVelocity("""", ""setInitialVelocity"", _W_7); extern ""C"" { void PbRegister_setInitialVelocity() { KEEP_UNUSED(_RP_setInitialVelocity); } } //! Kernel: gradient norm operator struct KnConfForce : public KernelBase { KnConfForce(Grid &force, const Grid &grid, const Grid &curl, Real str, const Grid *strGrid) : KernelBase(&force, 1), force(force), grid(grid), curl(curl), str(str), strGrid(strGrid) { runMessage(); run(); } inline void op(int i, int j, int k, Grid &force, const Grid &grid, const Grid &curl, Real str, const Grid *strGrid) const { Vec3 grad = 0.5 * Vec3(grid(i + 1, j, k) - grid(i - 1, j, k), grid(i, j + 1, k) - grid(i, j - 1, k), 0.); if (grid.is3D()) grad[2] = 0.5 * (grid(i, j, k + 1) - grid(i, j, k - 1)); normalize(grad); if (strGrid) str += (*strGrid)(i, j, k); force(i, j, k) = str * cross(grad, curl(i, j, k)); } inline Grid &getArg0() { return force; } typedef Grid type0; inline const Grid &getArg1() { return grid; } typedef Grid type1; inline const Grid &getArg2() { return curl; } typedef Grid type2; inline Real &getArg3() { return str; } typedef Real type3; inline const Grid *getArg4() { return strGrid; } typedef Grid type4; void runMessage() { debMsg(""Executing kernel KnConfForce "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 1; j < _maxY; j++) for (int i = 1; i < _maxX; i++) op(i, j, k, force, grid, curl, str, strGrid); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 1; i < _maxX; i++) op(i, j, k, force, grid, curl, str, strGrid); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(1, maxY), *this); } Grid &force; const Grid &grid; const Grid &curl; Real str; const Grid *strGrid; }; void vorticityConfinement(MACGrid &vel, const FlagGrid &flags, Real strength = 0, const Grid *strengthCell = NULL) { Grid velCenter(flags.getParent()), curl(flags.getParent()), force(flags.getParent()); Grid norm(flags.getParent()); GetCentered(velCenter, vel); CurlOp(velCenter, curl); GridNorm(norm, curl); KnConfForce(force, norm, curl, strength, strengthCell); KnApplyForceField(flags, vel, force, NULL, true, false); } static PyObject *_W_8(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""vorticityConfinement"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; MACGrid &vel = *_args.getPtr(""vel"", 0, &_lock); const FlagGrid &flags = *_args.getPtr(""flags"", 1, &_lock); Real strength = _args.getOpt(""strength"", 2, 0, &_lock); const Grid *strengthCell = _args.getPtrOpt>( ""strengthCell"", 3, NULL, &_lock); _retval = getPyNone(); vorticityConfinement(vel, flags, strength, strengthCell); _args.check(); } pbFinalizePlugin(parent, ""vorticityConfinement"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""vorticityConfinement"", e.what()); return 0; } } static const Pb::Register _RP_vorticityConfinement("""", ""vorticityConfinement"", _W_8); extern ""C"" { void PbRegister_vorticityConfinement() { KEEP_UNUSED(_RP_vorticityConfinement); } } void addForceField(const FlagGrid &flags, MACGrid &vel, const Grid &force, const Grid *region = NULL, bool isMAC = false) { KnApplyForceField(flags, vel, force, region, true, isMAC); } static PyObject *_W_9(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""addForceField"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; const FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); MACGrid &vel = *_args.getPtr(""vel"", 1, &_lock); const Grid &force = *_args.getPtr>(""force"", 2, &_lock); const Grid *region = _args.getPtrOpt>(""region"", 3, NULL, &_lock); bool isMAC = _args.getOpt(""isMAC"", 4, false, &_lock); _retval = getPyNone(); addForceField(flags, vel, force, region, isMAC); _args.check(); } pbFinalizePlugin(parent, ""addForceField"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""addForceField"", e.what()); return 0; } } static const Pb::Register _RP_addForceField("""", ""addForceField"", _W_9); extern ""C"" { void PbRegister_addForceField() { KEEP_UNUSED(_RP_addForceField); } } void setForceField(const FlagGrid &flags, MACGrid &vel, const Grid &force, const Grid *region = NULL, bool isMAC = false) { KnApplyForceField(flags, vel, force, region, false, isMAC); } static PyObject *_W_10(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""setForceField"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; const FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); MACGrid &vel = *_args.getPtr(""vel"", 1, &_lock); const Grid &force = *_args.getPtr>(""force"", 2, &_lock); const Grid *region = _args.getPtrOpt>(""region"", 3, NULL, &_lock); bool isMAC = _args.getOpt(""isMAC"", 4, false, &_lock); _retval = getPyNone(); setForceField(flags, vel, force, region, isMAC); _args.check(); } pbFinalizePlugin(parent, ""setForceField"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""setForceField"", e.what()); return 0; } } static const Pb::Register _RP_setForceField("""", ""setForceField"", _W_10); extern ""C"" { void PbRegister_setForceField() { KEEP_UNUSED(_RP_setForceField); } } struct KnDissolveSmoke : public KernelBase { KnDissolveSmoke(const FlagGrid &flags, Grid &density, Grid *heat, Grid *red, Grid *green, Grid *blue, int speed, bool logFalloff, float dydx, float fac) : KernelBase(&flags, 0), flags(flags), density(density), heat(heat), red(red), green(green), blue(blue), speed(speed), logFalloff(logFalloff), dydx(dydx), fac(fac) { runMessage(); run(); } inline void op(int i, int j, int k, const FlagGrid &flags, Grid &density, Grid *heat, Grid *red, Grid *green, Grid *blue, int speed, bool logFalloff, float dydx, float fac) const { bool curFluid = flags.isFluid(i, j, k); if (!curFluid) return; if (logFalloff) { density(i, j, k) *= fac; if (heat) { (*heat)(i, j, k) *= fac; } if (red) { (*red)(i, j, k) *= fac; (*green)(i, j, k) *= fac; (*blue)(i, j, k) *= fac; } } else { // linear falloff float d = density(i, j, k); density(i, j, k) -= dydx; if (density(i, j, k) < 0.0f) density(i, j, k) = 0.0f; if (heat) { if (fabs((*heat)(i, j, k)) < dydx) (*heat)(i, j, k) = 0.0f; else if ((*heat)(i, j, k) > 0.0f) (*heat)(i, j, k) -= dydx; else if ((*heat)(i, j, k) < 0.0f) (*heat)(i, j, k) += dydx; } if (red && notZero(d)) { (*red)(i, j, k) *= (density(i, j, k) / d); (*green)(i, j, k) *= (density(i, j, k) / d); (*blue)(i, j, k) *= (density(i, j, k) / d); } } } inline const FlagGrid &getArg0() { return flags; } typedef FlagGrid type0; inline Grid &getArg1() { return density; } typedef Grid type1; inline Grid *getArg2() { return heat; } typedef Grid type2; inline Grid *getArg3() { return red; } typedef Grid type3; inline Grid *getArg4() { return green; } typedef Grid type4; inline Grid *getArg5() { return blue; } typedef Grid type5; inline int &getArg6() { return speed; } typedef int type6; inline bool &getArg7() { return logFalloff; } typedef bool type7; inline float &getArg8() { return dydx; } typedef float type8; inline float &getArg9() { return fac; } typedef float type9; void runMessage() { debMsg(""Executing kernel KnDissolveSmoke "", 3); debMsg(""Kernel range"" << "" x "" << maxX << "" y "" << maxY << "" z "" << minZ << "" - "" << maxZ << "" "", 4); }; void operator()(const tbb::blocked_range &__r) const { const int _maxX = maxX; const int _maxY = maxY; if (maxZ > 1) { for (int k = __r.begin(); k != (int)__r.end(); k++) for (int j = 0; j < _maxY; j++) for (int i = 0; i < _maxX; i++) op(i, j, k, flags, density, heat, red, green, blue, speed, logFalloff, dydx, fac); } else { const int k = 0; for (int j = __r.begin(); j != (int)__r.end(); j++) for (int i = 0; i < _maxX; i++) op(i, j, k, flags, density, heat, red, green, blue, speed, logFalloff, dydx, fac); } } void run() { if (maxZ > 1) tbb::parallel_for(tbb::blocked_range(minZ, maxZ), *this); else tbb::parallel_for(tbb::blocked_range(0, maxY), *this); } const FlagGrid &flags; Grid &density; Grid *heat; Grid *red; Grid *green; Grid *blue; int speed; bool logFalloff; float dydx; float fac; }; void dissolveSmoke(const FlagGrid &flags, Grid &density, Grid *heat = NULL, Grid *red = NULL, Grid *green = NULL, Grid *blue = NULL, int speed = 5, bool logFalloff = true) { float dydx = 1.0f / (float)speed; // max density/speed = dydx float fac = 1.0f - dydx; KnDissolveSmoke(flags, density, heat, red, green, blue, speed, logFalloff, dydx, fac); } static PyObject *_W_11(PyObject *_self, PyObject *_linargs, PyObject *_kwds) { try { PbArgs _args(_linargs, _kwds); FluidSolver *parent = _args.obtainParent(); bool noTiming = _args.getOpt(""notiming"", -1, 0); pbPreparePlugin(parent, ""dissolveSmoke"", !noTiming); PyObject *_retval = 0; { ArgLocker _lock; const FlagGrid &flags = *_args.getPtr(""flags"", 0, &_lock); Grid &density = *_args.getPtr>(""density"", 1, &_lock); Grid *heat = _args.getPtrOpt>(""heat"", 2, NULL, &_lock); Grid *red = _args.getPtrOpt>(""red"", 3, NULL, &_lock); Grid *green = _args.getPtrOpt>(""green"", 4, NULL, &_lock); Grid *blue = _args.getPtrOpt>(""blue"", 5, NULL, &_lock); int speed = _args.getOpt(""speed"", 6, 5, &_lock); bool logFalloff = _args.getOpt(""logFalloff"", 7, true, &_lock); _retval = getPyNone(); dissolveSmoke(flags, density, heat, red, green, blue, speed, logFalloff); _args.check(); } pbFinalizePlugin(parent, ""dissolveSmoke"", !noTiming); return _retval; } catch (std::exception &e) { pbSetError(""dissolveSmoke"", e.what()); return 0; } } static const Pb::Register _RP_dissolveSmoke("""", ""dissolveSmoke"", _W_11); extern ""C"" { void PbRegister_dissolveSmoke() { KEEP_UNUSED(_RP_dissolveSmoke); } } } // namespace Manta ",16368,True,3851.547885293186,median "= Asciidoctor Changelog :uri-asciidoctor: http://asciidoctor.org :uri-asciidoc: {uri-asciidoctor}/docs/what-is-asciidoc :uri-repo: https://github.com/asciidoctor/asciidoctor :icons: font :star: icon:star[role=red] ifndef::icons[] :star: ★ endif::[] {uri-asciidoctor}[Asciidoctor] is a _fast_, open source text processor and publishing toolchain for converting {uri-asciidoc}[AsciiDoc] content into HTML5, DocBook 5 (or 4.5) and other formats. This document provides a high-level view of the changes introduced in Asciidoctor by release. For a detailed view of what has changed, refer to the {uri-repo}/commits/master[commit history] on GitHub. // tag::compact[] == 1.5.4 (2016-01-03) - @mojavelinux Enhancements:: * translate README into French (@anthonny, @mogztter, @gscheibel, @mgreau) (#1630) * allow linkstyle in manpage output to be configured (#1610) Improvements:: * upgrade to MathJax 2.6.0 and disable loading messages * upgrade to Font Awesome 4.5.0 * disable toc if document has no sections (#1633) * convert inline asciimath to MathML (using asciimath gem) in DocBook converter (#1622) * add attribute to control build reproducibility (@bk2204) (#1453) * recognize \\file:/// as a file root in Opal browser env (#1561) * honor icon attribute on admonition block when font-based icons are enabled (@robertpanzer) (#1593) * resolve custom icon relative to iconsdir; add file extension if absent (#1634) * allow asciidoctor cli to resolve library path when invoked without leading ./ Compliance:: * allow special section to be nested at any depth (#1591) * ensure colpcwidth values add up to 100%; increase precision of values to 4 decimal places (#1647) * ignore blank cols attribute on table (#1647) * support shorthand syntax for block attributes on document title (#1650) Bug fixes:: * don't include default toc in AsciiDoc table cell; don't pass toc location attributes to nested document (#1582) * guard against nil dlist list item in find_by (#1618) * don't swallow trailing line when include file is not readable (#1602) * change xlink namespace to xl in DocBook 5 output to prevent parse error (#1597) * make callouts globally unique within document, including AsciiDoc table cells (#1626) * initialize Slim-related attributes regardless of when Slim was loaded (@terceiro) (#1576) * differentiate literal backslash from escape sequence in manpage output (@ds26gte) (#1604) * don't mistake line beginning with \\. for troff macro in manpage output (@ds26gte) (#1589) * escape leading dots so user content doesn't trigger troff macros in manpage output (@ds26gte) (#1631) * use \\c after .URL macro to remove extraneous space in manpage output (@ds26gte) (#1590) * fix missing endline after .URL macro in manpage output (#1613) * properly handle spacing around .URL/.MTO macro in manpage output (@ds26gte) (#1641) * don't swallow doctitle attribute followed by block title (#1587) * change strategy for splitting names of author; fixes bug in Opal/Asciidoctor.js * don't fail if library is loaded more than once Infrastructure:: * remove trailing endlines in project source code * update contributing guidelines * explicitly test ifeval scenario raised in issue #1585 * remove backreference substitution hack for Opal/Asciidoctor.js * fix assignment of default Hash value for Opal/Asciidoctor.js * add JRuby 9.0.4.0 and Ruby 2.3.0 to the Travis CI build matrix Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] * https://apps.fedoraproject.org/packages/rubygem-asciidoctor[Fedora (rubygem-asciidoctor)] * http://packages.debian.org/sid/asciidoctor[Debian (asciidoctor)] * http://packages.ubuntu.com/saucy/asciidoctor[Ubuntu (asciidoctor)] https://github.com/asciidoctor/asciidoctor/issues?q=milestone%3Av1.5.4[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v1.5.4[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v1.5.3...v1.5.4[full diff] == 1.5.3 (2015-10-31) - @mojavelinux Enhancements:: * add support for interactive & inline SVGs (#1301, #1224) * add built-in manpage backend (@davidgamba) (#651) * create Mallard backend; asciidoctor/asciidoctor-mallard (@bk2204) (#425) * add AsciiMath to MathML converter to support AsciiMath in DocBook converter (@pepijnve) (#954) * allow text of selected lines to be highlighted in source block by Pygments or CodeRay (#1429) * use value of `docinfo` attribute to control docinfo behavior (#1510) * add `docinfosubs` attribute to control which substitutions are performed on docinfo files (@mogztter) (#405) * drop ability to specify multiple attributes with a single `-a` flag when using the CLI (@mogztter) (#405) * make subtitle separator chars for document title configurable (@rmannibucau) (#1350) * make XrefInlineRx regexp more permissive (Mathieu Boespflug) (#844) Improvements:: * load JavaScript and CSS at bottom of HTML document (@mogztter) (#1238) * list available backends in help text (@plaindocs) (#1271) * properly expand tabs in literal text (#1170, #841) * add `source-indent` as document attribute (@mogztter) (#1169) * upgrade MathJax to 2.5.3 (#1329) * upgrade Font Awesome to 4.4.0 (@mogztter) (#1465) * upgrade highlight.js to 8.6 (now 8.9.1) (#1390) * don't abort if syntax highlighter isn't available (#1253) * insert docinfo footer below footer div (#1503) * insert toc at default location in embeddable HTML (#1443) * replace _ and - in generated alt text for inline images * restore attributes to header attributes after parse (#1255) * allow docdate and doctime to be overridden (#1495) * add CSS class `.center` for center block alignment (#1456) * recognize U+2022 as alternative marker for unordered lists (@mogztter) (#1177) * allow videos to work for local files by prepending asset-uri-scheme (Chris) (#1320) * always assign playlist param when loop option is enabled for YouTube video * parse isolated version in revision line (@bk2204) (#790) * autoload Tilt when template converter is instantiated (#1313) * don't overwrite existing id entry in references table (#1256) * use outfilesuffix attribute defined in header when resolving outfile (#1412) * make AsciiDoc safe mode option on Slim engine match document (#1347) * honor htmlsyntax attribute when backend is html/html5 (#1530) * tighten spacing of wrapped lines in TOC (#1542) * tune padding around table cells in horizontal dlist (#1418) * load Droid Sans Mono 700 in default stylesheet * set line height of table cells used for syntax highlighting * set font-family of kbd; refine styling (#1423) * extract condition into `quote_lines?` method (@mogztter) * extract inline code into `read_paragraph` method (@mogztter) * parent of block in ListItem should be ListItem (#1359) * add helper methods to List and ListItem (#1551) * add method `AbstractNode#add_role` and `AbstractNode#remove_role` (@robertpanzer) (#1366) * introduce helper methods for sniffing URIs (#1422) * add helper to calculate basename without file extension * document `-I` and `-r` options in the manual page (@bk2204) * fix `+--help+` output text for `-I` (@bk2204) * don't require open-uri-cached if already loaded * do not attempt to scan pattern of non-existent directory in template converter Compliance:: * use `` for footnote reference in text instead of `` (#1523) * fix alignment of wrapped text in footnote (#1524) * include full stop after footnote number in embeddable HTML * show manpage title & name section in embeddable HTML (#1179) * resolve missing attribute in ifeval to empty string (#1387) * support unbreakable & breakable options on table (rockyallen) (#1140) Bug fixes:: * don't truncate exception stack in `Asciidoctor.load` (#1248) * don't fail to save cause of Java exception (@robertpanzer) (#1458) * fix precision error in timings report (#1342) * resolve regexp for inline macro lazily (#1336) * block argument to `find_by` should filter results (#1393) * strip comment lines in indented text of dlist item (#1537) * preserve escaped delimiter at end of line in a table (#1306) * correctly calculate colnames for implicit columns (#1556) * don't crash if colspan exceeds colspec (#1460) * account for empty records in colspec (#1375) * ignore empty cols attribute on table * use `.inspect` to print MathJax delimiters (again) (#1198) * use while loop instead of begin/while loop to address bug in Asciidoctor.js (#1408) * force encoding of attribute values passed from cli (#1191) * don't copy css if stylesheet or stylesdir is a URI (#1400) * fix invalid color value in default CodeRay theme * built-in writer no longer fails if output is nil (#1544) * custom template engine options should take precedence * fallback to require with a non-relative path to support Debian package (@mogztter) * pass opts to recursive invocations of `PathResolver#system_path` * fix and test external links in docbook backend * use format symbol `:html` instead of `:html5` for Slim to fix warnings * fix documentation for inline_macro and block_macro (Andrea Bedini) * fix grammar in warning messages regarding thread_safe gem Infrastructure:: * migrate opal_ext from core to Asciidoctor.js (#1517) * add Ruby 2.2 to CI build; only specify minor Ruby versions * enable containerized builds on Travis CI * add config to run CI build on AppVeyor * exclude benchmark folder from gem (#1522) Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] * https://apps.fedoraproject.org/packages/rubygem-asciidoctor[Fedora (rubygem-asciidoctor)] * http://packages.debian.org/sid/asciidoctor[Debian (asciidoctor)] * http://packages.ubuntu.com/saucy/asciidoctor[Ubuntu (asciidoctor)] https://github.com/asciidoctor/asciidoctor/issues?q=milestone%3Av1.5.3[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v1.5.3[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v1.5.2...v1.5.3[full diff] == 1.5.2 (2014-11-27) - @mojavelinux Enhancements:: * add docinfo extension (@mogztter) (#1162) * allow docinfo to be in separate directory from content, specified by `docinfodir` attribute (@mogztter) (#511) * enable TeX equation auto-numbering if `eqnums` attribute is set (@jxxcarlson) (#1110) Improvements:: * recognize `--` as valid line comment for callout numbers; make line comment configurable (#1068) * upgrade highlight.js to version 8.4 (#1216) * upgrade Font Awesome to version 4.2.0 (@clojens) (#1201) * define JAVASCRIPT_PLATFORM constant to simplify conditional logic in the JavaScript environment (#897) * provide access to destination directory, outfile and outdir via Document object (#1203) * print encoding information in version report produced by `asciidoctor -v` (#1210) * add intrinsic attribute named `cpp` with value `C++` (#1208) * preserve URI targets passed to `stylesheet` and related attributes (#1192) * allow numeric characters in block attribute name (#1103) * support custom YouTube playlists (#1105) * make start number for unique id generation configurable (#1148) * normalize and force UTF-8 encoding of docinfo content (#831) * allow subs and default_subs to be specified in Block constructor (#749) * enhance error message when reading binary input files (@mogztter) (#1158) * add `append` method as alias to `<<` method on AbstractBlock (#1085) * assign value of `preface-title` as title of preface node (#1090) * fix spacing around checkbox in checklist (#1138) * automatically load Slim's include plugin when using slim templates (@jirutka) (#1151) * mixin Slim helpers into execution scope of slim templates (@jirutka) (#1143) * improve DocBook output for manpage doctype (@bk2204) (#1134, #1142) Compliance:: * substitute attribute entry value in attributes defined outside of header (#1130) * allow empty cell to appear at end of table row (#1106) * only produce one row for table in CSV or DSV format with a single cell (#1180) Bug fixes:: * add explicit to_s call to generate delimiter settings for MathJax config (#1198) * fix includes that reference absolute Windows paths (#1144) * apply DSL to extension block in a way compatible with Opal Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] * https://apps.fedoraproject.org/packages/rubygem-asciidoctor[Fedora (rubygem-asciidoctor)] * http://packages.debian.org/sid/asciidoctor[Debian (asciidoctor)] * http://packages.ubuntu.com/saucy/asciidoctor[Ubuntu (asciidoctor)] https://github.com/asciidoctor/asciidoctor/issues?q=milestone%3Av1.5.2[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v1.5.2[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v1.5.1...v1.5.2[full diff] // end::compact[] == 1.5.1 (2014-09-29) - @mojavelinux Bug fixes:: * recognize tag directives inside comments within XML files for including tagged regions * restore passthroughs inside footnotes when more than one footnote appears on the same line * -S flag in cli recognizes safe mode name as lowercase string * do not match # in character reference when looking for marked text * add namespace to lang attribute in DocBook 5 backend * restore missing space before conum on last line of listing when highlighting with Pygments * place conums on correct lines when line numbers are enabled when highlighting with Pygments * don't expand mailto links in print styles Improvements:: * implement File.read in Node (JavaScript) environment * assign sectnumlevels and toclevels values to maxdepth attribute on AsciiDoc processing instructions in DocBook output * add test for usage of image block macro with data URI * use badges from shields.io in README Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] * https://apps.fedoraproject.org/packages/rubygem-asciidoctor[Fedora (rubygem-asciidoctor)] * http://packages.debian.org/sid/asciidoctor[Debian (asciidoctor)] * http://packages.ubuntu.com/saucy/asciidoctor[Ubuntu (asciidoctor)] https://github.com/asciidoctor/asciidoctor/issues?q=milestone%3Av1.5.1[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v1.5.1[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v1.5.0...v1.5.1[full diff] == 1.5.0 (2014-08-12) - @mojavelinux Performance:: * 10% increase in speed compared to 0.1.4 * rewrite built-in converters in Ruby instead of ERB Enhancements:: * {star} introduce new curved quote syntax (pass:[""`double quotes`""], pass:['`single quotes`']) if compat-mode attribute not set (#1046) * {star} add single curved quote replacement for pass:[`'] (#715) * {star} use backtick (`) for monospaced text if compat-mode attribute not set (#714, #718) * {star} use single and double plus (pass:[+], pass:[++]) for inline passthrough if compat-mode attribute not set (#714, #718) * {star} disable single quotes as formatting marks for emphasized text if compat-mode attribute not set (#717) * {star} enable compat-mode by default if document has atx-style doctitle * {star} output phrase surrounded by # as marked text (i.e., ) (#225) * {star} add MathJax integration and corresponding blocks and macros (#492, #760) * {star} switch to open source fonts (Open Sans, Noto Serif and Droid Sans Mono) in default stylesheet, major refinements to theme (#879) * {star} embed remote images when data-uri and allow-uri-read attributes are set (#612) * {star} support leveloffset on include directive and honor relative leveloffset values (#530) * {star} switch default docbook backend to docbook5 (@bk2204) (#554) * {star} added hide-uri-scheme attribute to hide uri scheme in automatic links (#800) * {star} allow substitutions to be incrementally added & removed (#522) * {star} add compatibility with Opal, add shim compat library, use compatibility regexp, require libraries properly (@mogztter) (#679, #836, #846) * {star} output XHTML when backend is xhtml or xhtml5 (#494) * {star} add shorthand subs and specialchars as an alias for specialcharacters (#579) * {star} deprecate toc2 attribute in favor of position and placement values on toc attribute (e.g., toc=left) (#706) * {star} add source map (file and line number) information to blocks (#861) * {star} write to file by default if input is file (#907) * {star} add -r and -I flags from ruby command to asciidoctor command for loading additional libraries (#574) * support backslash (\\) as line continuation character in the value of an attribute entry (#1022) * disable subs on pass block by default (#737) * add basic support for resolving xref target from reftext (#589) * add time range anchor to video element (#886) * match implicit URLs that use the file scheme (#853) * added sectnumlevels to control depth of section numbering (#549) * add hardbreaks option to block (#630) * sub attributes in manname (e.g., pass:[{docname}]) * warn on reference to missing attribute if attribute-missing is ""warn"" * only enable toc macro if toc is enabled and toc-placement attribute has the value macro (#706) * add sectnums attribute as alternative alias to numbered attribute (#684) Improvements:: * {star} don't select lines that contain a tag directive when including tagged lines, make tag regexp more strict (#1027) * {star} use https scheme for assets by default * {star} upgrade to Font Awesome 4.1 (@mogztter) (#752) * {star} improve print styles, add print styles for book doctype (@leif81) (#997, #952) * {star} add proper grid and frame styles for tables (@leif81) (#569) * {star} use glyphs for checkboxes when not using font icons (#878) * {star} prefer source-language attribute over language attribute for defining default source language (#888) * {star} pass document as first argument to process method on Preprocessor * don't parse link attributes when linkattrs is set unless text contains equal sign * detect bare links, mark with bare class; don't repeat URL of bare link in print styles * allow Treeprocessor#process method to replace tree (#1035) * add AbstractNode#find_by method to locate nodes in tree (#862) * add API for parsing title and subtitle (#1000) * add use_fallback option to doctitle, document method * constrain subscript & superscript markup (#564, #936) * match cell specs when cell separator is customized (#985) * use stylesheet to set default table width (#975) * display nested elements correctly in toc (@kenfinnigan) (#967) * add support for id attribute on links (@mogztter) (#935) * add support for title attribute on links (@aslakknutsen) * add -t flag to cli to control output of timing information (@mogztter) (#909) * rewrite converter API (#778) * rewrite extensions to support extension instances for AsciidoctorJ (#804) * integrate thread_safe gem (#638) * allow inline macro extensions that define a custom regexp to be matched (#792) * make Reader#push_include work with default file, path and dir (@bk2204) (#743) * honor custom outfilesuffix and introduce relfileprefix (#801) * add author and copyright to meta in HTML5 backend (#838) * output attribution in front of citetitle for quote and verse blocks * recognize float style with shorthand syntax outside block (#818) * honor background color in syntax highlighting themes (#813) * print runtime environment in version output, support -v as version flag (#785) * unwrap preamble if standalone (#533) * drop leading & trailing blank lines in verbatim & raw content (#724) * remove trailing endlines from source data (#727) * add flag to cli to suppress warnings (#557) * emit warning if tag(s) not found in include file (#639) * use element for vertical table headers instead of header class (@davidgamba) (#738) * share select references between AsciiDoc-style cell & main document (#729) * number chapters sequentially, always (#685) * add vbar attribute, make brvbar resolve properly (#643) * add implicit user-home attribute that resolves to user's home directory (#629) * enable sidebar toc for small screens (#628) * add square brackets around button in HTML output (#631) * make language hover text work for all languages in listing block * set background color on toc2 to cover scrolling content (@neher) * make document parsing a discrete step, make Reader accessible as property on Document * allow custom converter to set backend info such as outfilesuffix and htmlsyntax * report an informative error message when a converter cannot be resolved (@mogztter) * add conum class to b element when icons are disabled, make conum CSS selector more specific * expose Document object to extension point IncludeProcessor (@aslakknutsen) * style audioblock title, simplify rules for block titles * alias :name_attributes to :positional_attributes in extension DSL * upgrade to highlight.js 7.4 (and later 8.0) (@mogztter) (#756) Compliance:: * only include xmlns in docbook45 backend if xmlns attribute is specified (#929) * add xmlns attribute for xhtml output (@bk2204) * warn if table without a body is converted to DocBook (#961) * wrap around admonition inside example block in DocBook 4.5 (#931) * use if block image doesn't have a title (#927) * fix invalid docbook when adding role to formatted text (#956) * move all compliance flags to Compliance module (#624) * add compliance setting to control use of shorthand property syntax (#789) * wrap top-level content inside preamble in DocBook backend when doctype is book (#971) * escape special chars in image alt text (#972) * set starting number in ordered list for docbook (@megathaum) (#925) * match word characters in regular expressions as defined by Unicode (#892) * put source language class names on child code element of pre element (#921) * ignore case of attribute in conditional directives (#903) * allow attribute entry to reset / reseed counter (#870) * allow doctype to be set in AsciiDoc table cell (#863) * match URL macro following entity (@jmbruel) (#819) * handle BOM when normalizing source (#824) * don't output revhistory if revdate is not set (#802) * perform normal subs on verse content (#799) * automatically wrap part intro content in partintro block, emit warning if part is invalid (#768) * force encoding of docinfo content to UTF-8 (#773) * add scaling & alignment attributes to block image in DocBook backend (#763) * add support for pass:[anchor:[\\]] macro (#531) * substitute anchor and xref macros in footnotes (#676) * remove all string mutation operations for compatibility with Opal (#735) * honor reftext defined in embedded section title anchor (#697) * allow spaces in reftext defined in block anchor (#695) * use reftext of section or block in text of xref link (#693) * number sections in appendix using appendix number (#683) * unescape escaped square closing bracket in footnote text (#677) * support quoted index terms that may contain commas (#597) * don't assign role attribute if quoted text has no roles (#647) * disallow quoted values in block and inline anchors * add % to scaledwidth if no units given * ignore block attribute with unquoted value None * preserve entity references with 5 digits Bug Fixes:: * resolve relative paths relative to base_dir in unsafe mode (#690) * properly handle nested passthroughs (#1034) * don't clobber outfilesuffix attribute if locked (#1024) * correctly calculate columns if colspan used in first row of table (#924) * pass theme to Pygments when pygments-css=style (#919) * fallback to text lexer when using pygments for source highlighting (#987) * only make special section if style is specified (#917) * an unresolved footnote ref should not crash processor (#876) * rescue failure to resolve ::Dir.home (#896) * recognize Windows UNC path as absolute and preserve it (#806) * adjust file glob to account for backslash in Windows paths (#805) * don't match e-mail address inside URL (#866) * test include directive resolves file with space in name (#798) * return nil from Reader#push_include and Reader#pop_include methods (#745) * fixed broken passthroughs caused by source highlighting (#720) * copy custom stylesheet if linkcss is set (#300) * honor list continuations for indented, nested list items (#664) * fix syntax errors in converters (@jljouannic) * fix iconfont-remote setting * fix syntax error (target -> node.target) in Docbook 5 converter (@jf647) * output and style HTML for toc macro correctly Infrastructure:: * add Ruby 2.1 to list of supported platforms * reenable rbx in Travis build * switch tests to minitest (@ktdreyer) * update RPM for Fedora Rawhide (@ktdreyer) * refactor unit tests so they work in RubyMine (@cmoulliard) * add preliminary benchmark files to repository (#1021) * clean out old fixtures from test suite (#960) * add initial Cucumber test infrastructure (#731) * use gem tasks from Bundler in Rakefile (#654) * build gemspec files using git ls-tree (#653) * use in-process web server for URI tests * update manpage to reflect updates in 1.5.0 * rework README (@mogztter) (#651) Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] * https://apps.fedoraproject.org/packages/rubygem-asciidoctor[Fedora (rubygem-asciidoctor)] * http://packages.debian.org/sid/asciidoctor[Debian (asciidoctor)] * http://packages.ubuntu.com/saucy/asciidoctor[Ubuntu (asciidoctor)] https://github.com/asciidoctor/asciidoctor/issues?milestone=8&state=closed[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v1.5.0[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v0.1.4...v1.5.0[full diff] == 0.1.4 (2013-09-05) - @mojavelinux Performance:: * 15% increase in speed compared to 0.1.3 Enhancements:: * updated xref inline macro to support inter-document references (#417) * added extension API for document processing (#79) * added include directive processor extension (#100) * added id and role shorthand for formatted (quoted) text (#517) * added shorthand syntax for specifying block options (#481) * added support for checklists in unordered list (#200) * added support for inline style for unordered lists (#620) * added DocBook 5 backend (#411) * added docinfo option for footer (#486) * added Pygments as source highlighter option (pygments) (#538) * added icon inline macro (#529) * recognize implicit table header row (#387) * uri can be used in inline image (#470) * add float attribute to inline image (#616) * allow role to be specified on text enclosed in backticks (#419) * added XML comment-style callouts for use in XML listings (#582) * made callout bullets non-selectable in HTML output (#478) * pre-wrap literal blocks, added nowrap option to listing blocks (#303) * skip (retain) missing attribute references by default (#523) * added attribute-missing attribute to control how a missing attribute is handled (#495) * added attribute-undefined attribute to control how an undefined attribute is handled (#495) * permit !name syntax for undefining attribute (#498) * ignore front matter used by static site generators if skip-front-matter attribute is set (#502) * sanitize contents of HTML title element in html5 backend (#504) * support toc position for toc2 (#467) * cli accepts multiple files as input (@lordofthejars) (#227) * added Markdown-style horizontal rules and pass Markdown tests (#455) * added float clearing classes (.clearfix, .float-group) (#602) * don't disable syntax highlighting when explicit subs is used on listing block * asciidoctor package now available in Debian Sid and Ubuntu Saucy (@avtobiff) (#216) Compliance:: * embed CSS by default, copy stylesheet when linkcss is set unless copycss! is set (#428) * refactor reader to track include stack (#572) * made include directive resolve relative to current file (#572) * track include stack to enforce maximum depth (#581) * fixed greedy comment blocks and paragraphs (#546) * enable toc and numbered by default in DocBook backend (#540) * ignore comment lines when matching labeled list item (#524) * correctly parse footnotes that contain a URL (#506) * parse manpage metadata, output manpage-specific HTML, set docname and outfilesuffix (#488, #489) * recognize preprocessor directives on first line of AsciiDoc table cell (#453) * include directive can retrieve data from uri if allow-uri-read attribute is set (#445) * support escaping attribute list that precedes formatted (quoted) text (#421) * made improvements to list processing (#472, #469, #364) * support percentage for column widths (#465) * substitute attributes in docinfo files (#403) * numbering no longer increments on unnumbered sections (#393) * fixed false detection of list item with hyphen marker * skip include directives when processing comment blocks * added xmlns to root element in docbook45 backend, set noxmlns attribute to disable * added a Compliance module to control compliance-related behavior * added linkattrs feature to AsciiDoc compatibility file (#441) * added level-5 heading to AsciiDoc compatibility file (#388) * added new XML-based callouts to AsciiDoc compatibility file * added absolute and uri image target matching to AsciiDoc compatibility file * added float attribute on inline image macro to AsciiDoc compatibility file * removed linkcss in AsciiDoc compatibility file * fixed fenced code entry in compatibility file Bug Fixes:: * lowercase attribute names passed to API (#508) * numbered can still be toggled even when enabled in API (#393) * allow JRuby Map as attributes (#396) * don't attempt to highlight callouts when using CodeRay and Pygments (#534) * correctly calculate line length in Ruby 1.8 (#167) * write to specified outfile even when input is stdin (#500) * only split quote attribution on first comma in Markdown blockquotes (#389) * don't attempt to print render times when doc is not rendered * don't recognize line with four backticks as a fenced code block (#611) Improvements:: * upgraded Font Awesome to 3.2.1 (#451) * improved the built-in CodeRay theme to match Asciidoctor styles * link to CodeRay stylesheet if linkcss is set (#381) * style the video block (title & margin) (#590) * added Groovy, Clojure, Python and YAML to floating language hint * only process callouts for blocks in which callouts are found * added content_model to AbstractBlock, rename buffer to lines * use Untitled as document title in rendered output if document has no title * rename include-depth attribute to max-include-depth, set 64 as default value (#591) * the tag attribute can be used on the include directive to identify a single tagged region * output multiple authors in HTML backend (#399) * allow multiple template directories to be specified, document in usage and manpage (#437) * added option to cli to specify template engine (#406) * added support for external video hosting services in video block macro (@xcoulon) (#587) * strip leading separator(s) on section id if idprefix is blank (#551) * customized styling of toc placed inside body content (#507) * consolidate toc attribute so toc with or without toc-position can make sidebar toc (#618) * properly style floating images (inline & block) (#460) * add float attribute to inline images (#616) * use ul list for TOC in HTML5 backend (#431) * support multiple terms per labeled list item in model (#532) * added role?, has_role?, option? and roles methods to AbstractNode (#423, 474) * added captioned_title method to AbstractBlock * honor showtitle attribute as alternate to notitle! (#457) * strip leading indent from literal paragraph blocks assigned the style normal * only process lines in AsciiDoc files * emit message that tilt gem is required to use custom backends if missing (#433) * use attributes for version and last updated messages in footer (#596) * added a basic template cache (#438) * include line info in several of the warnings (for lists and tables) * print warning/error messages using warn (#556) * lines are not preprocessed when peeking ahead for section underline * introduced Cursor object to track line info * fixed table valign classes, no underline on image link * removed dependency on pending library, lock Nokogiri version to 1.5.10 * removed require rubygems line in asciidoctor.rb, add to cli if RUBY_VERSION < 1.9 * added tests for custom backends * added test that shorthand doesn't clobber explicit options (#481) * removed unnecessary monospace class from literal and listing blocks Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] * https://apps.fedoraproject.org/packages/rubygem-asciidoctor[Fedora (rubygem-asciidoctor)] * http://packages.debian.org/sid/asciidoctor[Debian (asciidoctor)] * http://packages.ubuntu.com/saucy/asciidoctor[Ubuntu (asciidoctor)] https://github.com/asciidoctor/asciidoctor/issues?milestone=7&state=closed[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v0.1.4[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v0.1.3...v0.1.4[full diff] == 0.1.3 (2013-05-30) - @mojavelinux Performance:: * 10% increase in speed compared to 0.1.2 Enhancements:: * added support for inline rendering by setting doctype to inline (#328) * added support for using font-based icons (#115) * honor haml/slim/jade-style shorthand for id and role attributes (#313) * support Markdown-style headings as section titles (#373) * support Markdown-style quote blocks * added section level 5 (maps to h6 element in the html5 backend) (#334) * added btn inline macro (#259) * added menu inline menu to identify a menu selection (@bleathem) (#173) * added kbd inline macro to identify a key or key combination (@bleathem) (#172) * support alternative quote forms (#196) * added indent attribute to verbatim blocks (#365) * added prettify source-highlighter (#202) * link section titles (#122) * introduce shorthand syntax for table format (#350) * parse attributes in link when use-link-attrs attribute is set (#214) * support preamble toc-placement (#295) * exclude attribute div if quote has no attribution (#309) * support attributes passed to API as string or string array (#289) * allow safe mode to be set using string, symbol or int in API (#290) * make level 0 section titles more prominent in TOC (#369) Compliance:: * ~ 99.5% compliance with AsciiDoc * drop line if target of include directive is blank (#376) * resolve attribute references in target of include directive (#367) * added irc scheme to link detection (#314) * toc should honor numbered attribute (#341) * added toc2 layout to default stylesheet (#285) * consecutive terms in labeled list share same entry (#315) * support set:name:value attribute syntax (#228) * block title not allowed above document title (#175) * assign caption even if no title (#321) * horizontal dlist layout in docbook backend (#298) * set doctitle attribute (#337) * allow any backend to be specified in cli (@lightguard) (#320) * support for abstract and partintro (#297) Bug Fixes:: * fixed file path resolution on Windows (#330) * fixed bad variable name that was causing crash, add test for it (#335) * set proper encoding on input data (#308) * don't leak doctitle into nested document (#382) * handle author(s) defined using attributes (#301) Improvements:: * added tests for all special sections (#80) * added test for attributes defined as string or string array (@lightguard) (#291) Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] * https://apps.fedoraproject.org/packages/rubygem-asciidoctor[Fedora (rubygem-asciidoctor)] http://asciidoctor.org/news/2013/05/31/asciidoctor-0-1-3-released[release notes] | https://github.com/asciidoctor/asciidoctor/issues?milestone=4&state=closed[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v0.1.3[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v0.1.2...v0.1.3[full diff] == 0.1.2 (2013-04-25) - @mojavelinux Performance:: * 28% increase in speed compared to 0.1.1, 32% increase compared to 0.1.0 Enhancements:: * new website at http://asciidoctor.org * added a default stylesheet (#76) * added viewport meta tag for mobile browsers (#238) * set attributes based on safe mode (#244) * added admonition name as style class (#265) * removed hardcoded CSS, no one likes hardcoded CSS (#165) * support multiple authors in document header (#223) * include footnotes block in embedded document (#206) * allow comma delimiter in include attribute values (#226) * support including tagged lines (#226) * added line selection to include directive (#226) * Asciidoctor#render APIs return Document when document is written to file Compliance:: * added AsciiDoc compatibility file to make AsciiDoc behave like Asciidoctor (#257) * restore alpha-based xml entities (#211) * implement video and audio block macros (#155) * implement toc block macro (#269) * correctly handle multi-part books (#222) * complete masquerade functionality for blocks & paragraphs (#187) * support explicit subs on blocks (#220) * use code element instead of tt (#260) * honor toc2 attribute (#221) * implement leveloffset feature (#212) * include docinfo files in header when safe mode < SERVER (#116) * support email links and mailto inline macros (#213) * question must be wrapped in simpara (#231) * allow round bracket in link (#218) Bug Fixes:: * trailing comma shouldn't be included in link (#280) * warn if file in include directive doesn't exist (#262) * negative case for inline ifndef should only affect current line (#241) * don't compact nested documents (#217) * nest revision info inside revision element (#236) Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] http://asciidoctor.org/news/2013/04/25/asciidoctor-0-1-2-released[release notes] | https://github.com/asciidoctor/asciidoctor/issues?milestone=3&state=closed[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v0.1.2[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v0.1.1...v0.1.2[full diff] == 0.1.1 (2013-02-26) - @erebor Performance:: * 15% increase in speed compared to 0.1.0 Enhancements:: * migrated repository to asciidoctor organization on GitHub (#77) * include document title when header/footer disabled and notitle attribute is unset (#103) * honor GitHub-flavored Markdown fenced code blocks (#118) * added :doctype and :backend keys to options hash in API (#163) * added :to_dir option to the Asciidoctor#render API * added option :header_only to stop parsing after reading the header * preliminary line number tracking * auto-select backend sub-folder containing custom templates * rubygem-asciidoctor package now available in Fedora (#92) Compliance:: * refactor reader, process attribute entries and conditional blocks while parsing (#143) * support limited value comparison functionality of ifeval (#83) * added support for multiple attributes in ifdef and ifndef directives * don't attempt to embed image with uri reference when data-uri is set (#157) * accomodate trailing dot in author name (#156) * don't hardcode language attribute in html backend (#185) * removed language from DocBook root node (#188) * fixed revinfo line swallowing attribute entry * auto-generate caption for listing blocks if listing-caption attribute is set * support nested includes * support literal and listing paragraphs * support em dash shorthand at the end of a line * added ftp support to link inline macro * added support for the page break block macro Bug Fixes:: * pass through image with uri reference when data-uri is set (#157) * print message for failed arg (#152) * normalize whitespace at the end of lines (improved) * properly load custom templates and required libraries Improvements:: * parse document header in distinct parsing step * moved hardcoded english captions to attributes Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] https://github.com/asciidoctor/asciidoctor/issues?milestone=1&state=closed[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v0.1.1[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v0.1.0...v0.1.1[full diff] == 0.1.0 (2013-02-04) - @erebor Enhancements:: * introduced Asciidoctor API (Asciidoctor#load and Asciidoctor#render methods) (#34) * added SERVER safe mode level (minimum recommended security for serverside usage) (#93) * added the asciidoctor commandline interface (cli) * added asciidoctor-safe command, enables safe mode by default * added man page for the asciidoctor command * use blockquote tag for quote block content (#124) * added hardbreaks option to preserve line breaks in paragraph text (#119) * :header_footer option defaults to false when using the API, unless rendering to file * added idseparator attribute to customized separator used in generated section ids * do not number special sections (differs from AsciiDoc) Compliance:: * use callout icons if icons are enabled, unless safe mode is SECURE * added support for name=value@ attribute syntax passed via cli (#97) * attr refs no longer case sensitive (#109) * fixed several cases of incorrect list handling * don't allow links to consume endlines or surrounding angled brackets * recognize single quote in author name * support horizontal labeled list style * added support for the d cell style * added support for bibliography anchors * added support for special sections (e.g., appendix) * added support for index term inline macros * added support for footnote and footnoteref inline macros * added auto-generated numbered captions for figures, tables and examples * added counter inline macros * added support for floating (discrete) section titles Bug Fixes:: * fixed UTF-8 encoding issue by adding magic encoding line to ERB templates (#144) * resolved Windows compatibility issues * clean CRLF from end of lines (#125) * enabled warnings when running tests, fixed warnings (#69) Improvements:: * renamed iconstype attribute to icontype Distribution Packages:: * http://rubygems.org/gems/asciidoctor[RubyGem (asciidoctor)] https://github.com/asciidoctor/asciidoctor/issues?milestone=12&state=closed[issues resolved] | https://github.com/asciidoctor/asciidoctor/releases/tag/v0.1.0[git tag] | https://github.com/asciidoctor/asciidoctor/compare/v0.0.9...v0.1.0[full diff] == Older releases (pre-0.0.1) For information about older releases, refer to the https://github.com/asciidoctor/asciidoctor/tags[commit history] on GitHub. ",12092,True,2686.451255200877,median "namespace openstudio { namespace model { /** \\mainpage OpenStudio Model * * \\section overview_model Overview * * An OpenStudio Model (\\ref introduction_model) represents a single building energy model, * either complete (simulatable with EnergyPlus) or partial. It is composed of a collection of * \\link ModelObject ModelObjects \\endlink (\\ref modelobject), which are polymorphic, that is, * ModelObject is the base class from which more specific object types are derived. Each leaf of * the inheritance tree wraps a specific data object type that is ultimately defined by the * OpenStudio.idd file. The following classes form the foundation of the OpenStudio Model: * * \\li Model * \\li Component * \\li ModelObject * \\li ParentObject * \\li ResourceObject * * The specific model object types can largely be broken down into the categories of simulation * settings; output data; resources; site and location; geometry; building loads; advanced daylighting; * heating, ventilation and air conditioning (HVAC) systems; * economics; and standards. We will now list the most important classes in each of these * categories. The lists are not meant to be exhaustive, but rather to give an intuitive sense * of what is and is not currently covered by the OpenStudio Model. Throughout, some of the * classes will be concrete (have a one-to-one mapping with an object in OpenStudio.idd), and * some will be abstract (provide a higher level interface to multiple Idd objects). * * \\subsection simulation_settings_classes Simulation Settings * * \\li Version * \\li YearDescription * \\li SimulationControl * \\li LightingSimulationControl * \\li Timestep * \\li RunPeriod * \\li ConvergenceLimits * \\li SizingParameters * * \\subsection output_data_classes Output Data * * \\li Meter * \\li OutputVariable * * \\subsection resource_classes Resources * * \\li Schedule * \\li ScheduleTypeLimits * \\li DefaultScheduleSet * \\li Construction * \\li DefaultConstructionSet * \\li OpaqueMaterial * \\li FenestrationMaterial * \\li ModelPartitionMaterial * \\li SpaceType * \\li ElectricEquipmentDefinition * \\li GasEquipmentDefinition * \\li InternalMassDefinition * \\li LightsDefinition * \\li LuminaireDefinition * \\li PeopleDefinition * \\li ExteriorLightsDefinition * \\li ExteriorFuelEquipmentDefinition * \\li ExteriorWaterEquipmentDefinition * * \\subsection site_location_classes Site and Location * * \\li Site * \\li DesignDay * \\li LightingDesignDay * \\li WeatherFile * \\li SiteWaterMainsTemperature * * \\subsection geometry_classes Geometry * * \\li Facility * \\li Building * \\li BuildingStory * \\li Space * \\li Surface * \\li SubSurface * \\li ShadingSurfaceGroup * \\li ShadingSurface * \\li InteriorPartitionSurfaceGroup * \\li InteriorPartitionSurface * * \\subsection building_loads_classes Building Loads * * \\li ElectricEquipment * \\li GasEquipment * \\li InternalMass * \\li Lights * \\li Luminaire * \\li People * \\li SpaceInfiltrationDesignFlowRate * \\li DesignSpecificationOutdoorAir * \\li ExteriorLights * \\li ExteriorFuelEquipment * \\li ExteriorWaterEquipment * * \\subsection advanced_daylighting_classes Advanced Daylighting * * \\li DaylightingControl * \\li GlareSensor * \\li IlluminanceMap * \\li DaylightingDeviceShelf * \\li LightingSimulationZone * * \\subsection hvac_classes HVAC Systems * * \\li AirLoopHVAC * \\li PlantLoop * \\li ThermalZone * \\li SizingZone * \\li SizingSystem * \\li Splitter * \\li Mixer * \\li Node * \\li HVACComponent * \\li ZoneHVACComponent * \\li StraightComponent * \\li WaterToAirComponent * \\li Curve * \\li ThermostatSetpointDualSetpoint * \\li AvailabilityManagerScheduled * \\li ControllerMechanicalVentilation * \\li ControllerOutdoorAir * \\li ControllerWaterCoil * * \\subsection economics_classes Economics * * This subsection of the model is not fully developed. Classes like ComponentCost_LineItem * are available, but we expect to do a full refactor of this area of * the model as time allows. * * \\subsection standards_classes Standards * * This subsection of the model is not fully developed. BuildingStandardsInformation, * ConstructionBaseStandardsInformation, and ClimateZones are examples of this type * of object. * * \\subsection other_links Other Links * * The following links may also be of general interest: * * \\li \\ref components * \\li \\link ConcreteModelObjects.hpp Alphabetical List of Concrete ModelObjects \\endlink * \\li \\ref modelobject_hierachy ""Concrete ModelObjects in Parent-Child Tree"" * * \\section introduction_model What is the Openstudio Model? * * The OpenStudio Model is a hierarchical, object-oriented model of a partial or complete building * that exists to support annual energy and other simulations and related analyses. Complete * building models may be simulated with EnergyPlus, which is developed by the Department of Energy * and is our primary simulation target (http://apps1.eere.energy.gov/buildings/energyplus/). * Daylighting simulation with Radiance is also supported, and OpenStudio can conduct some economic * analyses natively. The OpenStudio Model aims to integrate input and output data into a seamless * whole. EnergyPlus output data is accessed through the Model by connecting to an appropriate SqlFile (see the * utilities documentation), which provides a basic interface to the EnergyPlus SQLite output. Once * the basic connection to an output file is established, intuitive interfaces to specific pieces of * output data are provided at the object level. For instance, see Facility, ThermalZone, * and \\ref modelobjectOutputDataAccessMethods. * * \\subsection underlying_data Foundation: Data Model * * The underlying input data for Model is adapted from the EnergyPlus IDD/IDF file formats, where * an IDD (input data definition) file is a data schema, analogous to an XML Schema file, and an * IDF (input data file) is an instantiation of that schema, analogous to an XML file. The * OpenStudio IDD has been developed using a subset of objects in the EnergyPlus IDD as a starting point so * that OpenStudio can directly leverage EnergyPlus's numerous and extensively documented data * objects. Over time the OpenStudio IDD has grown to include more objects from the EnergyPlus IDD, with a * focus on including the most important types for energy simulation first. Additionally, new object types * have been added to the OpenStudio IDD to provide functionalities such as: * *
    *
  1. File/run management ('OS:WeatherFile', WeatherFile)
  2. *
  3. Output data integration ('OS:Facility', Facility)
  4. *
  5. Radiance integration ('OS:Luminaire', Luminaire)
  6. *
  7. HVAC abstractions ('OS:Node', Node)
  8. *
  9. Data sharing ('OS:ComponentData', ComponentData, Component)
  10. *
  11. Codes and standards support ('OS:ClimateZones', ClimateZones; * 'OS:StandardsInforamtion:Building', BuildingStandardsInformation)
  12. *
* * Each OpenStudio IDD object is wrapped by a corresponding ModelObject which provides an intelligent API for working * with that data object in an OpenStudio Model. * * \\link Model Models\\endlink are serialized to files with the extension '.osm', which are * instance files of the OpenStudio data schema. OSM files are clear text and look very similar * to IDF. * * \\subsection object_model Raison D'Etre: Object Model * * The last thing the building energy modeling community needs is yet another data model. So why * did we create the OpenStudio Model? * * To harness object-oriented programming techniques to provide a powerful interface for * building energy modeling at all fidelity levels, for various software development and user * communities. * * By formalizing relationships among data objects (\\ref modelobjectRelationships); and by placing * high-level, big-knob methods in appropriate data objects (\\ref modelobjectCompoundMethods); by * making it possible to access related input and output data from the same location ( \\ref * modelobjectOutputDataAccessMethods); and by supporting multiple types of simulation engines, * the OpenStudio Model provides a number of advantages over direct manipulation and analysis of * EnergyPlus input and output formats. * * \\subsection model_implementation Implementation Details * * Model serves as a container for \\link ModelObject ModelObjects \\endlink and a SqlFile. Model * inherits its functionality for storing and querying objects from openstudio::Workspace, which is * essentially an in-memory, custom database for openstudio::WorkspaceObject. The hierarchy of * object types will be described in full in \\ref object_implementation. For now it is important * to note that all of Workspace's methods (listed in the utilities documentation) are also * available to Model. Ideally, the underlying Workspace methods should only be called in model .cpp files; Model and ModelObject provides * methods for adding and removing objects with more built in intelligence. However, the basic * getters (e.g., getObjectByNameAndReference) and query methods (e.g., numObjects, * numObjectsOfType) may be of general interest. * * Model is implemented using the pImpl (pointer to implementation) idiom. In this pattern, each * public class (e.g. openstudio::model::Model) holds a pointer to an * implementation class (e.g. * openstudio::model::detail::Model_Impl) that actually holds the object data and implements its * methods. The public classes forward almost all user requests to the implementation class. This * idiom was adopted because it results in data sharing between copies of public class instances, * without the need for exposed pointers; and because it provides consistency of interface across * native C++ and the SWIG bindings. (At this time, the OpenStudio SDK is available in Ruby and * C#, in addition to C++, by way of SWIG.) * * Example of data sharing: * * \\code * openstudio::path modelPath = toPath(pathString); * OptionalModel oModel = Model::load(modelPath); * if (oModel) { * Model model = *oModel; // model accesses the same data as *oModel or oModel-> * Model anotherCopy = model; // anotherCopy accesses the same data as model * Building buildingObject = model.getUniqueModelObject(); * // now all of these asserts will pass, because every copy of the model public object provides * // access to the same Building object * OS_ASSERT(model.numObjects() == 1u); * OS_ASSERT(model.numObjects() == anotherCopy.numObjects()); * OS_ASSERT(model.numObjects() == oModel->numObjects()); * // the equality operator tests for whether two public objects point to the exact same * // implementation object * OS_ASSERT(buildingObject == anotherCopy.getUniqueModelObject()); * } * \\endcode * * \\section modelobject What is a ModelObject? * * At its most basic, ModelObject is the OpenStudio class that represents an IDF object. Just * like a text IDF object, it consists of a number of ordered string fields, some of which may be * in extensible groups, and all of which conform to the corresponding IDD object. Please see the * utilities IDD and IDF documentation (specifically openstudio::IddObject, * openstudio::ExtensibleIndex, and openstudio::IdfObject) for more information. \\link ModelObject * ModelObjects \\endlink are always owned by/live in a containing Model, which makes it possible * for \\link ModelObject ModelObjects \\endlink to point to each other in a meaningful way, even * when multiple \\link Model Models \\endlink are being operated on side-by-side. * * Although, strictly speaking, ModelObject provides access to its underlying string fields, a user * of the OpenStudio SDK should not need to resort to that low-level interface in most * circumstances. ModelObject is the base class for a large inheritance hierarchy, the terminating * nodes of which each wrap a specific object in the OpenStudio IDD. Each data field that should * be publicly accessible is wrapped into a getter and a setter method (see \\ref * modelobjectGetSet), several types of \\ref modelobjectCompoundMethods and \\ref * modelobjectOutputDataAccessMethods are provided, as are object getters and setters appropriate * to the various \\ref modelobjectRelationships in the Model. Methods for creating and deleting * data are also provided and available through a uniform interface, see \\ref modelobjectKeyBehaviors. * * At this time, \\link ModelObject ModelObjects \\endlink are uniquely identifiable by their * IddObjectType and name. \\link ModelObject ModelObjects \\endlink also have a unique handle that * is available and used in memory, but is currently not serialized to file. A number of objects * are unique in a given model. Unique objects may or may not have a name, as a name is not strictly * necessary for identification. For example: * * \\code * Model model; * Building building = model.getUniqueModelObject(); * OptionalString oName = building.name(); * OS_ASSERT(oName); // passes, because Building has a name * Version version = model.getUniqueModelObject(); * oName = version.name(); * OS_ASSERT(!oName); // passes, because Version does not have (and does not need) a name * \\endcode * * ModelObjects of different types can share a name as long as they are not be in the same IDD * reference list; ModelObjects of the same IddObjectType cannot. * * \\subsection modelobjectGetSet Field Getters and Setters * * \\todo The OpenStudio development team is currently in the process of fully implementing these * coding standards. * * Every data field that the user should be able to directly manipulate (possibly with side effects, * as in Lights::setLightingLevel), is exposed through getter and setter methods tailored to the * specifics of that field as specified by the IDD. For instance, the IDD slash code '\\\\type real' * results in getters and setters on double or boost::optional. The name of the field * is generated off of the IDD field name, keeping the names as close to the same as possible, but * removing non-word characters, and transforming to lower camel case. Fields that point to other * objects (\\\\type object-list) are not exposed in quite the same way, see * \\ref modelobjectRelationships. * * By maintaining the field names defined in the IDD, and by listing the name of the IDD object * wrapped by a given ModelObject in each \\link ConcreteModelObjects.hpp concrete object's\\endlink * documentation, we maintain a link with the EnergyPlus Input-Output reference for those \\link * ModelObject ModelObjects \\endlink that directly or essentially wrap a particular EnergyPlus IDD * object. We therefore do not provide detailed documentation for these methods, unless the field * was introduced by the OpenStudio IDD. However, side effects, like multiple fields being touched * by one setter, are documented. * * Data fields in extensible groups also have getters and setters, but may be exposed in different * ways, for instance, in a getter that takes the extensible group's index as an argument * (e.g., GasMixture::getGasType, GasMixture::setGasType), as part of a class that derives from * ModelExtensibleGroup (e.g. ClimateZone), or through the introduction of a specialized data * structure (e.g. PlanarSurface::vertices, PlanarSurface::setVertices). Classes that derive from * ModelExtensibleGroup are generally preferred, as they let the extensible groups be dealt with * on their own terms as individual objects. An exception to this is the case where there are just * a few simple pieces of data in the group, then a small struct (like the one used by * PlanarSurface::vertices) may be preferable. A ModelObject with a companion ModelExtensibleGroup * should provide a wrapper method for numExtensibleGroups with the name of the ModelExtesibleGroup * derived class replacing ""ExtensibleGroups"", and similar wrappers for getExtensibleGroup, * extensibleGroups, clearExtensibleGroups and pushExtensibleGroup (perhaps replacing ""push"" with * ""add""), at a minimum. * * \\todo Streamline the Idf and Workspace-level ExtensibleGroup interface and port any applicable * changes over to Model. * * In general, we make the following translations from IDD slash codes to C++ syntax. * * \\subsubsection allDataFields All Data Fields * * IDD fields that are '\\\\required' are provided in the object constructors, and are * always returned by value (double, int, or std::string, as opposed to boost::optional, * boost::optional, or boost::optional, respectively), unless the field can accept * different data types (as is the case with '\\\\autocalculatable' and '\\\\autosizable' fields). IDD * fields with '\\\\default' values are also returned by value if the field can only accept one data * type (e.g. it is not '\\\\autocalculatable' or '\\\\autosizable'). Note that some fields in the EnergyPlus * IDD are marked as '\\\\required' and '\\\\default', this is logically inconsistent so these fields are treated * as if they were marked only as '\\\\default' and not as '\\\\required'. It is preferable to mark fields as * '\\\\default' in the OpenStudio IDD if there is a suitable default value instead of providing default * arguments to the ModelObject constructor. * * If, the field is not required and does not have a default or the field can contain * multiple data types (e.g. such as '\\\\autocalculatable' or '\\\\autosizable' fields), the return value is wrapped in a boost::optional. If such an optional * return value evaluates to false, then there is no underlying data, and the user must not * dereference the optional container. If the return value evaluates to true, the actual returned * data may be accessed by dereferencing with '*' or '->', for example: * * \\code * Model model; * Lights lights(model); // by default, sets lightingLevel to 0 W * // OptionalDouble is typedef for boost::optional provided in utilities/core/Optional.hpp * OptionalDouble oLightingLevel = lights.lightingLevel(); * OS_ASSERT(oLightingLevel); * double lightingLevel = *oLightingLevel; // or oLightingLevel.get() * std::cout << ""Default lighting level for a new Lights object is "" << lightingLevel << "" W.""; * \\endcode * * If the user goes around the Model getter and setter methods by hand editing files or using the * WorkspaceObject interface directly, it is possible to break the return-by-value getters, in * which case a fatal error will be logged, and an openstudio::Exception will be thrown. To make it * clear to a user when a default value is set (the underlying field is empty), fields with default * values are provided with a query bool [fieldName]IsSetToDefault() const. * * If it is possible for a setter to fail, the setter will return a boolean to indicate success * (true) or failure (false). Otherwise, the return type will be void, and the user can trust that * the specified action will execute as expected. * * \\subsubsection numericFields Numeric Fields * * Numeric fields are based on the C++ data types double (if '\\\\type real') or int (if * '\\\\type integer'). The getters return a value if the field is required or has a numeric default, and is not * '\\\\autocalculatable' or '\\\\autosizable'; and return an optional otherwise. The setters accept a * double or int depending on the appropriate type. If the IDD specifies a minimum or maximum value then * setter may fail and thus returns a bool; otherwise the set operation cannot fail and void is returned. * If the field has a default, the user can check if the field is defaulted using [fieldName]IsSetToDefault, * the user can set the field to default value using set[FieldName]ToDefault. If the field has can be autocalculated, * the user can check if the field is autocalculated using [fieldName]IsSetToAutocalculate, * the user can set the field to autocalculate using set[FieldName]ToAutocalculate. * * \\todo Implement autosize/autocalculate getters and setters. * * \\subsubsection choiceFields Choice Fields * * Fields of '\\\\type choice' are IDD defined enumerations. Originally, enum classes were used for choice fields. * However, those classes greatly increased the size of the Model library. Therefore, the following rules were * developed. * * If the IddKeys associated with * a choice field are (case-insensitive) 'Yes'/'No', 'On'/'Off', or 'True'/'False'; then the OpenStudo getters and setters use bool * values. Two additional methods 'std::string [fieldName]String() const' and 'bool set[FieldName]String(const std::string&)' are provided * if the user needs to work with the string values. The general rules concerning getter return values, and setter return values apply to * string versions of the field getters and setters. The general rules concerning default fields apply to the bool version of the getter and setter. * However the bool setters cannot fail, and so always return void. Finally, if there is no default value and the field is not required * the bool getter will return a boost::optional the user must be careful not to confuse whether this optional is initialized with * the actual value of the field. * * Other choice fields operate solely off of std::string. The allowable values are case insensitive, * defined by the IDD and exposed through static methods like Gas::validGasTypes(). The setters can * always fail; whether a boost::optional is returned by the getter or accepted by the * setter conforms to the general rules. * * \\todo Return OptionalString() for unset choice fields (rather than empty strings)? * * \\subsubsection urlFields URL Fields * * The OpenStudio IDD introduces the '\\\\type url' field to help with locating files other than the * OSM on which a simulation depends. (See WeatherFile for instance.) * RunManager provides functionality to normalize url fields at job creation time. RunManager * looks for the file across all URLSearchPaths (see utilities documentation) passed in to the * job creation. In this process, if the referenced file can be found, RunManager ensures that the * file is copied to the local computer running the job and that the url field is set to a valid * absolute path to that file for all child jobs (the url field is unchanged in the original input * Model). If the field immediately following a url field is named 'Checksum' and is of type alpha, * that field contains a checksum (computed by openstudio::checksum()) that RunManager uses to * verify that the file found is the desired file. External files may be referenced using url * fields in several ways: * * \\li The url field may contain a single file name (e.g. 'Chicago.epw'). URLSearchPaths are used * to look for relative urls and may be specified as relative to the job's working directory * or to the original input Model. * * \\li The url field may contain a relative file path (e.g. '../../Chicago.epw'). URLSearchPaths * are used to look for relative urls and may be specified as relative to the job's working * directory or to the original input Model. * * \\li The url field may contain an absolute file path (e.g. 'C:/weatherData/Chicago.epw' or * '/weatherData/Chicago.epw'). URLSearchPaths are not used to look for absolute file paths. * * \\li The url field may contain an absolute url (e.g. 'file://C:/weatherData/Chicago.epw' or * 'http://www.weatherdata.org/Chicago.epw'). URLSearchPaths are not used to look for absolute * urls. * * \\li The url field may contain the UUID of a file in a Building Component Library (e.g. * '{550e8400-e29b-41d4-a716-446655440000}'). (This is not yet implemented). * * Url fields are implemented with two overloaded set methods which each return void; one taking * a string and one taking an openstudio::path. The get method returns a * string. Normal rules for required and default fields apply. * * \\subsubsection otherFields Other Fields * * All other types of fields ('\\\\type alpha' or '\\\\type external-list') are treated as strings and * conform to the general rules. * * \\todo Return OptionalString() for unset string fields (rather than empty strings)? * * An extended example of data field getter and setter usage: * * \\code * Model model; * ScheduleCompact scheduleCompact(model); * * //the curve * CurveBiquadratic ccFofT(model); * CurveBiquadratic eirFofT(model); * CurveQuadratic ccFofF(model); * CurveQuadratic eirFofF(model); * CurveQuadratic plf(model); * * ccFofT.setCoefficient1Constant(1.0); * ccFofT.setCoefficient2x(2.0); * ccFofT.setCoefficient3xPOW2(3.0); * ccFofT.setCoefficient4y(4.0); * ccFofT.setCoefficient5yPOW2(5.0); * ccFofT.setCoefficient6xTIMESY(6.0); * ccFofT.setMinimumValueofx(-10.0); * ccFofT.setMaximumValueofx(100.03); * ccFofT.setMinimumValueofy(-99999); * ccFofT.setMaximumValueofy(100232); * ccFofT.setMinimumCurveOutput(-1000); * ccFofT.setMaximumCurveOutput(99999); * ccFofT.setInputUnitTypeforX(""Temperature""); * ccFofT.setOutputUnitType(""MassFlow""); * * CoilCoolingDXSingleSpeed cool(model, * scheduleCompact, * ccFofT, * ccFofF, * eirFofT, * eirFofF, * plf); * * Schedule s = cool.getAvailabilitySchedule(); * OS_ASSERT(s == scheduleCompact) * OptionalDouble od; * cool.setRatedTotalCoolingCapacity(od); // set to ""AutoCalculate"" * * // this passes because the constructor set it to ""AirCooled""for you. * OS_ASSERT(cool.getCondenserType() == ""AiRCoolEd"") * * OptionalSchedule s2 = cool.getBasinHeaterOperatingSchedule(); * OS_ASSERT(!s2) * // s2 evaluates to false because this schedule is not required and not set * \\endcode * * \\subsection modelobjectCompoundMethods Compound Methods * * OpenStudio \\link ModelObject ModelObjects \\endlink provide ""big knob"" compound methods to enable * high-level modeling and various types of analysis (perturbation, optimization, standards, etc.) * For example, Space::lightingPowerPerFloorArea calculates lighting power in the space by adding up * lighting power from all Lights and Luminaire objects directly assigned to the space or it's space type, * then dividing by the floor area of these space. Furthermore, * that method, and the Space compound ""getter"" that corresponds to it are wrapped up together in * an Attribute named ""lightingPowerDensity"" available through the ModelObject::getAttribute * interface. * * PlanarSurface::uFactor and PlanarSurface::setUFactor (and the associated Attribute) is another * example that brings a lot of pieces together to expose a high-level piece of data. Depending on * the underlying construction type, these methods may operate directly on a SimpleGlazing object; * may use static film resistance data in conjunction with one or more Material objects, and maybe * a ConstructionBaseStandardsInformation object (the latter is sometimes needed for the u-factor * setter); or may query the output data in the SqlFile. If u-factor is available through input and * output data, the output data is returned, but in the meantime the two values are compared and a * message is logged if their difference exceeds some tolerance. Related methods are available * through ConstructionBase. * * Several objects include a number of methods (some static) provided to give the user access to * basic physical information used in EnergyPlus or in building energy standards. The film * resistances alluded to above are available through PlanarSurface::filmResistance and * PlanarSurface::stillAirFilmResistance. Physical properties of gases commonly found in * multi-paned windows are available from FenestrationMaterial. * * Overall, the compound methods are difficult to characterize as a whole. We encourage users to * peruse the documentation for each individual object in which they have an interest. Compound * methods are generally listed outside of the ""Getters"" and ""Setters"" sections, even though some * methods' functionality will be similar to a get or a set. In general, these methods should be * well documented since they are native to OpenStudio. * * \\subsection modelobjectOutputDataAccessMethods Output Data Access Methods * * The model.setSqlFile(const SqlFile& sqlFile) method is used to attach a Model to related EnergyPlus * simulation output. Because the OpenStudio Model must be translated to EnergyPlus IDF for simulation, the * results of the EnergyPlus simulation will not map exactly to the Model. However, the Model will perform * some checks to verify that the given SqlFile does relate to the given Model, the setSqlFile operation will * fail if these checks are not satisfied. If model.sqlFile() evaluates to true, then a given model is hooked * up to its EnergyPlus simulation output data in the form of a SQLite file, and a number of ways to retrieve output data become * active. * * \\li \\link Meter Meters \\endlink provide access to related data once the SqlFile is attached. Meters * may be present at the Facility, Building, ThermalZone, System, and Plant levels. * * \\li Every concrete ModelObject must implement the method \\link ModelObject::outputVariables * outputVariables() \\endlink. With the SqlFile attached, the TimeSeries (see the utilities * documentation) associated with those \\link OutputVariable OutputVariables \\endlink may be * retrieved, given an appropriate environment period string (see SimulationControl). * * \\li High level simulation results are available through methods of appropriate ModelObjects. * * \\li When possible, calculation of a result (e.g. floorArea) from the input data only is preferred to * requiring simulation output be attached to the Model. In these cases, the method always * computes its value from input data alone, the method does not check simulation results. * At least one unit test ensures that the value calculated from input data matches the value in the * simulation results. * * \\li Results which require simulation to report (e.g. annualNetSiteEnergy) return an uninitialized optional value * unless a valid SqlFile is attached. Results that are not specific to a particular environment period (e.g. u-factor) may be accessed * without specifying an environment period. Results that are specific to a particular environment period (e.g. totalLightingEnergy) require * the environment period to report results as an input. Results that presume an annual simulation or some other condition * (e.g. annualNetSiteEnergy presumes the presence of one and only one annual simulation run period) do not require * an environment period as an input but return an uninitialized optional value if that condition is not met. * * \\li Finally some virtual methods may be implemented by some concrete classes to require output data but by other classes * to not require output data. For instance, * PlanarSurface::uFactor may require simulation data in order to return an actual value, * depending on the exact construction type. (And the u-factor may not be available at all if output data is required * and the surface is not adjacent to the outside environment.) In this case, the operation of any specific class always uses either * input or output data, the user must refer to the documentation for the specific derived types to understand how the virtual method * will operate in all situations. * * The connection to the SqlFile can be reset using model.resetSqlFile(). Closing the SqlFile connection is necessary in order * to resimulate the Model using EnergyPlus. * * \\subsection modelobjectRelationships Relationships * * There are three primary types of relationships among \\link ModelObject ModelObjects\\endlink: * Parent-Child, Resource-ResourceUser, and (HVAC) Connection. * * The Parent-Child relationship is used to represent containment relationships in the building. * For example, Building parents Space, which parents a number of objects including Lights, People, and * ElectricEquipment. If a ParentObject is removed, * its children (and on down the line recursively to grandchildren, etc.) should also * be removed; and if a ParentObject is cloned (copied), its children (recursively) should also * be cloned. * * In addition to helping define behaviors, the Parent-Child relationship is useful for model * visualization and navigation. Navigating using ModelObject::parent() and ParentObject::children() * in a Ruby script, for instance, can give the user intuition about how the various aspects of a * Model conceptually fit together in OpenStudio and EnergyPlus. * * A ResourceObject is a ModelObject that can be used by multiple other data objects. For instance, * unlike a Lights object which can only be associated with one Space or SpaceType, a Schedule can be used by * any number of objects, so long as the data type of the Schedule (fractional, on/off, * temperature, etc.) is appropriate for the context. Every ModelObject can return the \\link * ResourceObject ResourceObjects \\endlink that is uses with the method ModelObject::resources(). * \\link ResourceObject ResourceObjects \\endlink can report their use counts, see * ResourceObject::directUseCount and ResourceObject::nonResourceObjectUseCount. Unused resources * can be removed in one fell swoop with Model::purgeUnusedResourceObjects. * * Unlike children, resources are meant to be shared, so they are not removed when a user of the * resource is removed, and they are not automatically cloned when one of their users is cloned * (see \\ref modelobjectKeyBehaviors). * * Parents, children and resources are available through generic and typed interfaces. For * instance, Building::children() will return all of the \\link Space Spaces \\endlink in a * std::vector, and Building also has a method \\link Building::spaces() spaces() * \\endlink that returns the same data as a std::vector. The Schedule associated with a * Lights object can be found through the std::vector returned by * Schedule::resources(), and also through the method Lights::schedule(). Lights also has the * method \\link Lights::setSchedule setSchedule(const Schedule&) \\endlink. * * Connections join multiple ModelObjects together via designated points called ports. Connections * between ModelObjects are directional and they are created by identifying a source ModelObject and port * as well as a target ModelObject object and port. Once a connection is made, it is easy to access the ModelObject * connected to a particular port using ModelObject::connectedObject. New Connections are made using the * openstudio::model::Model::connect function. * * ModelObject connections are similar to EnergyPlus nodes, however a connection between ports is * more general than a node connection in Energyplus. In the OpenStudio model, connections serve * the same role as nodes in EnergyPlus, but OpenStudio connections can be applied in contexts other * than the EnergyPlus system nodes. OpenStudio's connections and ports can be used any time one * ModelObject can be arbitrarily connected to another ModelObject. For example, EnergyPlus EMS * sensors and actuators could be thought of as source and target ports, and a connection could be * made between the two. * * \\subsection modelobject_hierachy Parent-Child Hierarchy * * As described above, objects in the OpenStudio Model can be organized into a tree (actually a * forest) by linking ModelObject types based on their Parent-Child relationships. The following * is a complete listing of the concrete \\link ModelObject ModelObjects \\endlink displayed in * Parent-Child hierarchical form. The immediate base class of each object is listed in * parentheses. Some object types are listed more than once because they can be the child of * multiple concrete types (in which case the Parent-Child relationship is often defined by an * abstract base class). If the class name is somewhat different from the IddObjectType valueName, * the name of the IDD object is also listed for reference. * *
    *
  • Version (ModelObject, unique) *
  • Site (ParentObject, unique) – wraps 'Site:Location' *
      *
    • ClimateZones (ModelObject, unique) *
    • DesignDay (SizingPeriod) – wraps 'SizingPeriod:DesignDay' *
        *
      • SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature' *
      *
    • LightingDesignDay (ModelObject) *
    • SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature' *
    • SiteGroundReflectance (ModelObject, unique) *
    • SiteGroundTemperatureBuildingSurface (ModelObject, unique) *
    • SiteWaterMainsTemperature (ModelObject, unique) *
    • WeatherFile (ModelObject, unique) *
    • WeatherFileConditionType (SizingPeriod) *
        *
      • SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature' *
      *
    • WeatherFileDays (SizingPeriod) *
        *
      • SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature' *
      *
    • ShadingSurfaceGroup (PlanarSurfaceGroup) *
        *
      • ShadingSurface (PlanarSurface) *
      *
    *
  • YearDescription (ParentObject, unique) *
      *
    • RunPeriodControlSpecialDays (ModelObject) *
    • RunPeriodControlDaylightSavingTime (ModelObject, unique) *
    *
  • SimulationControl (ParentObject, unique) *
      *
    • Timestep (ModelObject, unique) *
    • RunPeriod (ParentObject) *
        *
      • SkyTemperature (ModelObject) – wraps 'OS:WeatherProperty:SkyTemperature' *
      *
    • ConvergenceLimits (ModelObject, unique) *
    • ShadowCalculation (ModelObject, unique) *
    • HeatBalanceAlgorithm (ModelObject, unique) *
    • InsideSurfaceConvectionAlgorithm (ModelObject, unique) *
    • OutsideSurfaceConvectionAlgorithm (ModelObject, unique) *
    • SizingParameters (ModelObject, unique) *
    • ZoneAirContaminantBalance (ModelObject, unique) *
    • ZoneAirHeatBalanceAlgorithm (ModelObject, unique) *
    • ZoneCapacitanceMultiplierResearchSpecial (ModelObject, unique) *
    *
  • LightingSimulationControl (ModelObject) *
  • Facility (ParentObject, unique) *
      *
    • Meter (ModelObject) *
    • ExteriorLights (ExteriorLoadInstance) *
    • ExteriorFuelEquipment (ExteriorLoadInstance) *
    • ExteriorWaterEquipment (ExteriorLoadInstance) *
    • Building (ParentObject, unique) *
        *
      • BuildingStandardsInformation (ModelObject, unique) *
      • Meter (ModelObject) *
      • BuildingStory (ModelObject) *
      • ShadingSurfaceGroup (PlanarSurfaceGroup) *
          *
        • ShadingSurface (PlanarSurface) *
        *
      • Space (PlanarSurfaceGroup) *
          *
        • ShadingSurfaceGroup (PlanarSurfaceGroup) *
            *
          • ShadingSurface (PlanarSurface) *
          *
        • InteriorPartitionSurfaceGroup (PlanarSurfaceGroup) *
            *
          • InteriorPartitionSurface (PlanarSurface) *
          *
        • Surface (PlanarSurface) *
            *
          • SubSurface (PlanarSurface) *
              *
            • DaylightingDeviceShelf (ModelObject) *
            *
          *
        • ElectricEquipment (SpaceLoadInstance) *
        • GasEquipment (SpaceLoadInstance) *
        • HotWaterEquipment (SpaceLoadInstance) *
        • SteamEquipment (SpaceLoadInstance) *
        • OtherEquipment (SpaceLoadInstance) *
        • InternalMass (SpaceLoadInstance) *
        • Lights (SpaceLoadInstance) *
        • Luminaire (SpaceLoadInstance) *
        • People (SpaceLoadInstance) *
        • SpaceInfiltrationDesignFlowRate (SpaceLoad) *
        • SpaceInfiltrationEffectiveLeakageArea (SpaceLoad) *
        • DaylightingControl (SpaceItem) *
        • IlluminanceMap (SpaceItem) *
        • GlareSensor (SpaceItem) *
        *
      • ThermalZone (HVACComponent) *
      *
    *
  • AirLoopHVAC (Loop) *
  • PlantLoop (Loop) *
  • AirLoopHVACZoneSplitter (Splitter) *
  • AirLoopHVACZoneMixer (Mixer) *
  • ConnectorSplitter (Splitter) *
  • ConnectorMixer (Mixer) *
  • Connection (ModelObject) *
  • SizingZone (ModelObject) *
  • SizingSystem (ModelObject) *
  • ThermostatSetpointDualSetpoint (ModelObject) *
  • AvailabilityManagerScheduled (ParentObject) *
  • ControllerMechanicalVentilation (ParentObject) *
  • AirLoopHVACOutdoorAirSystem (HVACComponent) *
      *
    • ControllerOutdoorAir (ParentObject) *
    *
  • ControllerWaterCoil (HVACComponent) *
  • Node (StraightComponent) *
      *
    • SetpointManagerSingleZoneReheat (HVACComponent) *
    • SetpointManagerScheduled (HVACComponent) *
    • SetpointManagerMixedAir (HVACComponent) *
    *
  • AirLoopHVACUnitaryHeatPumpAirToAir (StraightComponent) *
      *
    • (HVACComponent) *
    *
  • AirTerminalSingleDuctParallelPIUReheat (StraightComponent) *
      *
    • (HVACComponent) *
    *
  • AirTerminalSingleDuctConstantVolumeNoReheat (StraightComponent) *
  • AirTerminalSingleDuctVAVReheat (StraightComponent) *
  • FanConstantVolume (StraightComponent) *
  • FanVariableVolume (StraightComponent) *
  • CoilHeatingGas (StraightComponent) *
  • EvaporativeCoolerDirectResearchSpecial (StraightComponent) *
  • CoilHeatingDXSingleSpeed (StraightComponent) *
      *
    • (Curve) *
    *
  • CoilCoolingDXSingleSpeed (StraightComponent) *
      *
    • (Curve) *
    *
  • CoilCoolingDXTwoSpeed (StraightComponent) *
      *
    • (Curve) *
    *
  • CoilHeatingElectric (StraightComponent) *
  • PumpVariableSpeed (StraightComponent) *
      *
    • (Curve) *
    *
  • BoilerHotWater (StraightComponent) *
      *
    • (Curve) *
    *
  • CoilCoolingWater (WaterToAirComponent) *
  • CoilHeatingWater (WaterToAirComponent) *
  • ZoneHVACFourPipeFanCoil (ZoneHVACComponent) *
      *
    • (HVACComponent) *
    *
  • ZoneHVACPackagedTerminalAirConditioner (ZoneHVACComponent) *
      *
    • (HVACComponent) *
    *
  • ZoneHVACPackagedTerminalHeatPump (ZoneHVACComponent) *
      *
    • (HVACComponent) *
    *
  • CurveBicubic (Curve) *
  • CurveBiquadratic (Curve) *
  • CurveCubic (Curve) *
  • CurveDoubleExponentialDecay (Curve) *
  • CurveExponent (Curve) *
  • CurveExponentialDecay (Curve) *
  • CurveExponentialSkewNormal (Curve) *
  • CurveFanPressureRise (Curve) *
  • CurveFunctionalPressureDrop (Curve) *
  • CurveLinear (Curve) *
  • CurveQuadratic (Curve) *
  • CurveQuadraticLinear (Curve) *
  • CurveQuartic (Curve) *
  • CurveRectangularHyperbola1 (Curve) *
  • CurveRectangularHyperbola2 (Curve) *
  • CurveSigmoid (Curve) *
  • CurveTriquadratic (Curve) *
  • LightingSimulationZone (ModelObject) *
  • ScheduleTypeLimits (ResourceObject) *
  • ScheduleConstant (Schedule) *
  • ScheduleCompact (Schedule) *
  • ScheduleRuleset (Schedule) *
      *
    • ScheduleDay (ScheduleBase) *
    • ScheduleRule (ParentObject) *
        *
      • ScheduleDay (ScheduleBase) *
      *
    *
  • ScheduleYear (Schedule) *
  • ScheduleWeek (ResourceObject) *
  • ScheduleDay (ScheduleBase) *
  • ScheduleVariableInterval (ScheduleInterval) *
  • ScheduleFixedInterval (ScheduleInterval) *
  • DefaultScheduleSet (ResourceObject) *
  • Construction (LayeredConstruction) *
      *
    • ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction' *
    *
  • ConstructionWithInternalSource (LayeredConstruction) – wraps 'OS:%Construction:InternalSource' *
      *
    • ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction' *
    *
  • CFactorUndergroundWallConstruction (ConstructionBase) – wraps 'OS:%Construction:CfactorUndergroundWall' *
      *
    • ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction' *
    *
  • FFactorGroundFloorConstruction (ConstructionBase) – wraps 'OS:%Construction:FfactorGroundFloor' *
      *
    • ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction' *
    *
  • WindowDataFile (ConstructionBase) – wraps 'OS:%Construction:%WindowDataFile' *
      *
    • ConstructionBaseStandardsInformation (ModelObject) – wraps 'OS:StandardsInformation:%Construction' *
    *
  • DefaultConstructionSet (ResourceObject) *
  • DefaultSubSurfaceConstructions (ResourceObject) *
  • DefaultSurfaceConstructions (ResourceObject) *
  • StandardOpaqueMaterial (OpaqueMaterial) – wraps 'OS:%Material' *
  • MasslessOpaqueMaterial (OpaqueMaterial) – wraps 'OS:%Material:NoMass' *
  • Gas (GasLayer) – wraps 'OS:WindowMaterial:%Gas' *
  • GasMixture (GasLayer) – wraps 'OS:WindowMaterial:%GasMixture' *
  • InfraredTransparentMaterial (ModelPartitionMaterial) – wraps 'OS:%Material:InfraredTransparent' *
  • AirWallMaterial (ModelPartitionMaterial) – wraps 'OS:%Material:AirWall' *
  • Shade (ShadingMaterial) – wraps 'OS:WindowMaterial:%Shade' *
  • Screen (ShadingMaterial) – wraps 'OS:WindowMaterial:%Screen' *
  • Blind (ShadingMaterial) – wraps 'OS:WindowMaterial:%Blind' *
  • AirGap (OpaqueMaterial) – wraps 'OS:%Material:%AirGap' *
  • RoofVegetation (OpaqueMaterial) – wraps 'OS:%Material:%RoofVegetation' *
  • StandardGlazing (Glazing) – wraps 'OS:WindowMaterial:%Glazing' *
  • SimpleGlazing (Glazing) – wraps 'OS:WindowMaterial:SimpleGlazingSystem' *
  • ThermochromicGlazing (Glazing) – wraps 'OS:WindowMaterial:GlazingGroup:Thermochromic' *
  • RefractionExtinctionGlazing (Glazing) – wraps 'OS:WindowMaterial:Glazing:RefractionExtinctionMethod' *
  • SpaceType (ResourceObject) *
      *
    • ElectricEquipment (SpaceLoadInstance) *
    • GasEquipment (SpaceLoadInstance) *
    • HotWaterEquipment (SpaceLoadInstance) *
    • SteamEquipment (SpaceLoadInstance) *
    • OtherEquipment (SpaceLoadInstance) *
    • InternalMass (SpaceLoadInstance) *
    • Lights (SpaceLoadInstance) *
    • Luminaire (SpaceLoadInstance) *
    • People (SpaceLoadInstance) *
    • SpaceInfiltrationDesignFlowRate (SpaceLoad) *
    • SpaceInfiltrationEffectiveLeakageArea (SpaceLoad) *
    *
  • RenderingColor (ResourceObject) *
  • ElectricEquipmentDefinition (SpaceLoadDefinition) *
  • GasEquipmentDefinition (SpaceLoadDefinition) *
  • HotWaterEquipmentDefinition (SpaceLoadDefinition) *
  • SteamEquipmentDefinition (SpaceLoadDefinition) *
  • OtherEquipmentDefinition (SpaceLoadDefinition) *
  • InternalMassDefinition (SpaceLoadDefinition) *
  • LightsDefinition (SpaceLoadDefinition) *
  • LuminaireDefinition (SpaceLoadDefinition) *
  • PeopleDefinition (SpaceLoadDefinition) *
  • ExteriorLightsDefinition (ExteriorLoadDefinition) *
  • ExteriorFuelEquipmentDefinition (ExteriorLoadDefinition) *
  • ExteriorWaterEquipmentDefinition (ExteriorLoadDefinition) *
  • DesignSpecificationOutdoorAir (ResourceObject) *
  • CurrencyType (ParentObject) *
  • LifeCycleCost_UsePriceEscalation (ParentObject) *
  • LifeCycleCost_UseAdjustment (ParentObject) *
  • LifeCycleCost_Parameters (ParentObject) *
  • ComponentCost_Adjustments (ParentObject) *
  • ComponentCost_Reference (ParentObject) *
* * Special Cases that can be Parented by many \\link ModelObject ModelObjects \\endlink * *
    *
  • OutputVariable (ModelObject) *
  • ComponentCost_LineItem (ModelObject) *
  • LifeCycleCost_RecurringCosts (ParentObject) *
  • LifeCycleCost_NonrecurringCost (ParentObject) *
* * Special Cases related to the Building Component Library * *
    *
  • ComponentData (ParentObject)
  • *
* * \\subsection modelobjectKeyBehaviors Key Behaviors * * \\subsubsection newmodel Create a New Model * * There are four constructors available for Model. The default constructor creates a new Model * with a single Version object in it. Version objects are not returned by Model::objects or * counted by Model::numObjects. * * \\code * Model model; * OS_ASSERT(model.versionObject()); * OS_ASSERT(model.numObjects() == 0u); * OS_ASSERT(model.iddFileType() == IddFileType::OpenStudio); * OS_ASSERT(model.strictnessLevel() == StrictnessLevel::Draft); * \\endcode * * The preferred method for creating a Model from an OSM file is * * \\code * OptionalModel oModel = Model::load(modelFilePath); * if (!oModel) { LOG_AND_THROW(""Unable to open '"" << toString(modelFilePath) << ""'.""); } * Model model = *oModel; * \\endcode * * UNLESS that OSM file might be from an old version of OpenStudio, in which case the version * translator should be used: * * \\code * osversion::VersionTranslator translator; * OptionalModel oModel = translator.loadModel(modelFilePath); * if (!oModel) { * LOG_AND_THROW(""Unable to open and translate '"" << toString(modelFilePath) << ""'.""); * } * Model model = *oModel; * \\endcode * * The preferred method for creating a Model from IDF file is * * \\code * #include * * OptionalModel oModel = energyplus::loadAndTranslateIdf(idfFilePath); * \\endcode * * In addition, constructors are provided from IdfFile and Workspace (see the utilities * documentation). Those constructors will throw if IdfFile or Workspace uses the wrong IDD file. * * Because Model is required to support partial (unsimulatable) building models for data * sharing, and to provide a flexible interface for editing, it is ultimately up to the user to * ensure that a Model is ready for simulation. Model::validityReport and similar methods (see * the utilities documentation, especially Workspace::validityReport, * WorkspaceObject::validityReport, and ValidityEnums.hpp) are provided to help users bring their * models up to the standard set by the IDD. (And there are a few places in Model where validity * checking goes beyond the data schema to rules internal to EnergyPlus, see for instance * LayeredConstruction::layersAreValid, which is used by the virtual implementation of * validityReport for \\link LayeredConstruction LayeredConstructions \\endlink.) Beyond that, users * will sometimes need to go through an iterative process of modeling, trying to run EnergyPlus * (or another simulation engine), addressing simulation errors, etc. * * \\subsubsection newmodelobject Create a New ModelObject * * Every concrete ModelObject has one or more public constructors, unless * it is marked unique by the IDD. In this case, there is no public constructor in order to * prevent the accidental construction of multiple instance of that type in the same model. Instead, * these objects are made available through Model::getUniqueModelObject and * Model::getOptionalUniqueModelObject: * * \\code * Model model; * * // getOptionalUniqueModelObject only returns an object if it is already in the Model. * // It constructs any new objects. * OptionalBuilding oBuilding = model.getOptionalUniqueModelObject(); * OS_ASSERT(!oBuilding); * OS_ASSERT(model.numObjects() == 0u); * * // getUniqueModelObject constructs the object if it is not yet present. * Building building = model.getUniqueModelObject(); * OS_ASSERT(model.numObjects() == 1u); * * // now getOptionalUniqueModelObject can return the object that was just created * oBuilding = model.getOptionalUniqueModelObject(); * OS_ASSERT(oBuilding); * OS_ASSERT(model.numObjects() == 1u); * OS_ASSERT(oBuilding.get() == building); * \\endcode * * For non-unique objects, all public constructors will ensure that required fields, children, * and resources are present as a post-condition. Depending on the constructor, the user may be * required to explicitly provide those objects, or they may be default constructed. For example * the LightsDefinition object is a required argument to the Lights object constructor. Parents * are often not required by the public constructors; as appropriate, convenience constructors * that take the parent as an argument may be provided. (Orphan construction is allowed in order * to better support data sharing. For instance, if someone wants to create a lighting component * for the Building Component Library, requiring Lights to be constructed with a Space or * SpaceType would be inconvenient.) * * \\subsubsection removemodelobject Delete a ModelObject * * ModelObject::remove is used to remove a ModelObject from a Model. When a model object is * removed, all of its children are also removed. Objects related to the removed object through * a resource or connection relationship are not deleted. Resources persist so they can be used * by other objects. Connections are broken by object removal, but the adjacent object is left * behind, unless it happens to also be a child of the removed object. However, when a resource or * child object is removed, its user objects or parents may also be removed, if the relationship * is a required one for the user/parent. For instance, SpaceLoadDefinition::remove also removes * all of its SpaceLoadDefinition::instances, since a SpaceLoadInstance cannot exist without its * definition. * * For all deleted objects, when all the instances of that object go out of scope and stop * referencing the shared implementation pointer, the memory will be automatically freed for you. * * \\subsubsection clonemodelobject Clone a ModelObject * * ModelObject::clone is used to duplicate a ModelObject. The clone method may be used to copy * an object into another model, or to duplicate an object in the same model. The act of cloning * an object will change the duplicate object's name if an object of the same type and name * already exists in the target model. Therefore, cloning into the same model will always result * in name change for the duplicate so as to avoid a name collision with the original object. * Cloning a ModelObject also clones all of its children (recursively). Resources are cloned as * necessary (when an equivalent object cannot be located, see IdfObject::dataFieldsEqual and * IdfObject::managedObjectListFieldsNonConflicting in the utilities documentation) when the * original and target models are different. * * Examples: * \\code * LightsVector originalLights = space.lights(); * clonedSpace= space.clone(space.model()); * LightsVector clonedLights = clonedSpace.lights(); * OS_ASSERT(originalLights.size() == clonedLights.size()) * * if (originalLights.size() > 0) { * LightVector::iterator i = std::find(originalLights.begin(),originalLights.end(),clonedLights[0]); * OS_ASSERT(i == originalLights.end()); // clonedLights[0] not found in originalLights * // (std::find uses ==, which for ModelObjects checks * // to see if the objects point to the exact same * // implementation object) * } * \\endcode * * The following code would also pass its OS_ASSERTs. Because we cloned into the same model, the * schedule (a ResourceObject) was NOT cloned. * * \\code * // continuing from above * * if (originalLights.size() > 0) { * // originalLights[0] and clonedLights[0] share the exact same schedule ... * // ... == verifies it. * OS_ASSERT(originalLights[0].schedule() == clonedLights[0].schedule()); * // ... as does making a change in clonedLights[0].schedule() * clonedLights[0].schedule().setName(""Some Cool Name"") * // ... and then looking for the change in originalLights[0].schedule(). * OS_ASSERT(originalLights[0].schedule().name().get() == ""Some Cool Name"") * } * \\endcode * * \\subsection object_implementation Implementation Details * * Similar to Model inheriting from openstudio::Workspace, ModelObject inherits from * openstudio::WorkspaceObject, which in turn inherits from openstudio::IdfObject. Briefly, * IdfObject corresponds to a single data object in an IDF file. It has an IddObject, which defines * its type, and it otherwise consists of a vector (ordered list) of string fields, accessible by * index and with an optional user comment. (If you never specify an IDF field comment, default * comments are generated for you from the IddField::name()'s.) WorkspaceObject provides the added * functionality of turning the '\\\\type object-list' fields that in clear text point to other data * objects by name reference into bi-directional, name-independent pointers to particular objects. * Please see the utilities/idf documentation for more information. * * In this way, IdfObject, WorkspaceObject, and Workspace form the underlying data model used by * OpenStudio to represent a single building (assuming the OpenStudio, rather than the EnergyPlus * or other, IDD is referenced). Model, ModelObject and everything else in the openstudio::model * namespace exists to turn that data model into a full-featured object model. * * Because Model and ModelObject publicly inherit from Workspace and WorkspaceObject, methods of * Workspace and WorkspaceObject are directly available for use through Model and ModelObject. * Use of these methods is discouraged where it is not necessary as these data model-level * modifications bypass the best-practice logic built into classes derived from ModelObject. * * \\link ModelObject ModelObjects \\endlink (and WorkspaceObjects and IdfObjects) also use the * pImpl idiom described \\ref model_implementation ""above"". So basic copying * and assignment results in data sharing, for example: * * \\code * Space spaceA(model); * spaceA.setName(""Space A""); * OS_ASSERT(spaceA.name().get() == ""Space A""); * Space spaceB = spaceA; * spaceB.setName(""Space B""); * OS_ASSERT(spaceA.name().get() == ""Space B""); // may not be the intended behavior ... * // use clone() to get a deep copy * * // Sharing also happens just by passing objects around as arguments. * // For instance, this function takes a non-const copy, it does not pass by reference. * void changeName(ModelObject object) { * object.setName(""New Name""); * } * * Space spaceC(model); * // function looks like all changes are local to it ... * changeName(spaceC); * // ... but they are not because of pImpl. * OS_ASSERT(spaceC.name().get() == ""New Name""); * \\endcode * * The pointer to the implementation is managed by a reference counting pointer, so the * implementation object is destroyed when the last wrapper class goes out of scope. Because the * implementation is shared between copies of the public class, signal and slot connections will * remain active after the public object is destroyed provided that another object still references * the same implementation. Note that at the very least this other object is typically the Model * of which the ModelObject is a member, as Model (actually Workspace) maintains a map of all of its * objects' implementation reference counting pointers. * * The combined use of template methods such as Model::getModelObjects() with the pImpl idiom * has led to the unfortunate case where users of a class may need to also include the * corresponding implementation class, for example: * * \\code * // user will have to include Space.hpp and Space_Impl.hpp * std::vector spaces = model.getModelObjects(); * \\endcode * * Another important detail about the OpenStudio Model is that ModelObjects are only valid when * they are part of a Model. The benefit of this requirement is that any ModelObject can access the * entire Model to search for related ModelObjects. For the most part, the Model interface * enforces this requirement. However, there are some cases where it is possible to break this * invariant, for example: * * \\code * * // EXAMPLE OF WHAT NOT TO DO * * // vector to hold ModelObjects * std::vector modelObjects; * * { // create new scope * * // create new Model * Model model; * * // add some objects * model.getUniqueModelObject(); * model.getUniqueModelObject(); * Space space1(model); * Space space2(model); * * // get objects, they are valid here * modelObjects = model.modelObjects(); * * } // model goes out of scope * * // modelObjects now contains invalid ModelObjects * OS_ASSERT(!modelObjects[0].initialized()); // Model_Impl destructor disconnects objects * * \\endcode * * \\section components What is a Component? * * A Component is a partial Model that can be created from a ModelObject and then shared between * models or with other modelers. When ModelObject::createComponent is called, ModelObject::clone * is used to copy that object (the primary object) and related objects (often the children and * resources of the object, evaluated recursively) into a new, blank Component. A Component is a * Model that satisfies a few additional constraints. * * \\link Component Components\\endlink always contain one ComponentData object, which * provides a place to list all the objects in the Component, as well as universal identifiers * and timestamps used to keep track of the Component as it travels to and from local and remote * Building Component Libraries (BCLs). The contents list is always headed by the primary object, * which induces a parent-child tree plus resource and connection relationships on the rest of * objects. For instance, a Construction Component would have a Construction object as its * primary object, and would likely also contain a number of Material objects (resources of * the Construction), and a ComponentCost_LineItem object (child of the Construction). * * A component creation example follows: * \\code * OptionalModel oModel = Model::load(osmFilepath); * OS_ASSERT(oModel); * model = *oModel; * ConstructionVector constructions = model.getModelObjects(); * if (constructions.size() > 0) { * Component constructionComponent = constructions[0].createComponent(); * ModelObject primary = constructionComponent.primaryObject(); * OS_ASSERT(primary.optionalCast()); * OS_ASSERT(primary.cast().layers().size() == constructions[0].layers().size()); * OS_ASSERT(primary.cast() != constructions[0]); * OS_ASSERT(primary.model() != constructions[0].model()); * } * \\endcode * * The Component class disallows some of the non-const operations of Model. In particular, no * objects can be added to or inserted into a Component. Objects can be removed, except for the * primary ModelObject and the ComponentData object. If either of those objects are removed, the * Component is invalidated and throws an exception. Once created, Components can be saved for * future use, or directly used in another Model. To save a Component for future use, it should be * added to a local BCL, and/or uploaded to the online %Building %Component Library. (These * features are currently under development. Please see the documentation for utilities/bcl and * http://bcl.nrel.gov/.) * * To use a Component (either directly, or deserialized from a building component library) in a * Model, use the method Model::insertComponent(const Component& ). This method first looks to see * if a copy of the Component is already present in the Model; if not, it clones all of the * objects into the Model. In either case, if successful, the method returns the resulting * ComponentData object. After an insertComponent operation, Model watches the contents of the * inserted Component, changing the ComponentData::versionUUID if data is modified, and deleting * the ComponentData object (and discontinuing the watching operation) if it is invalidated (by * removal of the primaryObject, for instance). In this way, Model can be queried to find out what * \\link Component Components \\endlink it uses, and one can ascertain whether any data has changed * as compared to the original version. Therefore, this is a mechanism that can be used to trace * coherent pieces of input data through a series of related models, between similar research * project models, or to ensure that the appropriate components are used for building energy * standards compliance. * * An example of using the component created above: * \\code * if (constructions.size() > 0) { * Model newModel; * OptionalComponentData ocd = newModel.insertComponent(constructionComponent); * OS_ASSERT(ocd); * unsigned n = newModel.numObjects(); * ComponentData cd = *ocd; * Construction clonedConstruction = cd.primaryComponentObject().cast(); * // now I can make some geometry and assign the construction to a planar surface * // ... or I can remove the new construction, thereby ""destroying"" the component: * clonedConstruction.remove(); * OS_ASSERT(clonedConstruction.handle().isNull()); // clonedConstruction removed from model * OS_ASSERT(cd.handle().isNull()); // ComponentData object also removed * OS_ASSERT(newModel.numObjects() < n); * OS_ASSERT(newModel.getModelObjects().empty()); * // there may be some orphaned resources (Materials) still hanging around … * newModel.purgeUnusedResources(); * OS_ASSERT(newModel.numObjects() == 0u); * } * \\endcode */ } // model } // openstudio ",16276,True,2997.3489538028357,median "[[smpp-component]] = SMPP Component *Since Camel 2.2* // HEADER START *Both Producer and Consumer are supported* // HEADER END This component provides access to an SMSC (Short Message Service Center) over the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP] protocol to send and receive SMS. The http://jsmpp.org[JSMPP] library is used for the protocol implementation. The Camel component currently operates as an http://en.wikipedia.org/wiki/ESME[ESME] (External Short Messaging Entity) and not as an SMSC itself. You are also able to execute ReplaceSm, QuerySm, SubmitMulti, CancelSm and DataSm. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-smpp x.x.x ------------------------------------------------------------ == SMS limitations SMS is neither reliable or secure. Users who require reliable and secure delivery may want to consider using the XMPP or SIP components instead, combined with a smartphone app supporting the chosen protocol. * Reliability: although the SMPP standard offers a range of feedback mechanisms to indicate errors, non-delivery and confirmation of delivery it is not uncommon for mobile networks to hide or simulate these responses. For example, some networks automatically send a delivery confirmation for every message even if the destination number is invalid or not switched on. Some networks silently drop messages if they think they are spam. Spam detection rules in the network may be very crude, sometimes more than 100 messages per day from a single sender may be considered spam. * Security: there is basic encryption for the last hop from the radio tower down to the recipient handset. SMS messages are not encrypted or authenticated in any other part of the network. Some operators allow staff in retail outlets or call centres to browse through the SMS message histories of their customers. Message sender identity can be easily forged. Regulators and even the mobile telephone industry itself has cautioned against the use of SMS in two-factor authentication schemes and other purposes where security is important. While the Camel component makes it as easy as possible to send messages to the SMS network, it can not offer an easy solution to these problems. == Data coding, alphabet and international character sets Data coding and alphabet can be specified on a per-message basis. Default values can be specified for the endpoint. It is important to understand the relationship between these options and the way the component acts when more than one value is set. Data coding is an 8 bit field in the SMPP wire format. Alphabet corresponds to bits 0-3 of the data coding field. For some types of message, where a message class is used (by setting bit 5 of the data coding field), the lower two bits of the data coding field are not interpreted as alphabet and only bits 2 and 3 impact the alphabet. Furthermore, current version of the JSMPP library only seems to support bits 2 and 3, assuming that bits 0 and 1 are used for message class. This is why the Alphabet class in JSMPP doesn't support the value 3 (binary 0011) which indicates ISO-8859-1. Although JSMPP provides a representation of the message class parameter, the Camel component doesn't currently provide a way to set it other than manually setting the corresponding bits in the data coding field. When setting the data coding field in the outgoing message, the Camel component considers the following values and uses the first one it can find: * the data coding specified in a header * the alphabet specified in a header * the data coding specified in the endpoint configuration (URI parameter) Older versions of Camel had bugs in support for international character sets. This feature only worked when a single encoding was used for all messages and was troublesome when users wanted to change it on a per-message basis. Users who require this to work should ensure their version of Camel includes the fix for JIRA Issues Macro: com.atlassian.sal.api.net.ResponseStatusException: Unexpected response received. Status code: 404 . In addition to trying to send the data coding value to the SMSC, the Camel component also tries to analyze the message body, convert it to a Java String (Unicode) and convert that to a byte array in the corresponding alphabet When deciding which alphabet to use in the byte array, the Camel SMPP component does not consider the data coding value (header or configuration), it only considers the specified alphabet (from either the header or endpoint parameter). If some characters in the String can't be represented in the chosen alphabet, they may be replaced by the question mark ( ? ) symbol. Users of the API may want to consider checking if their message body can be converted to ISO-8859-1 before passing it to the component and if not, setting the alphabet header to request UCS-2 encoding. If the alphabet and data coding options are not specified at all then the component may try to detect the required encoding and set the data coding for you. The list of alphabet codes are specified in the SMPP specification v3.4, section 5.2.19. One notable limitation of the SMPP specification is that there is no alphabet code for explicitly requesting use of the GSM 3.38 (7 bit) character set. Choosing the value 0 for the alphabet selects the SMSC _default_ alphabet, this usually means GSM 3.38 but it is not guaranteed. The SMPP gateway Nexmo https://help.nexmo.com/hc/en-us/articles/204015813-How-to-change-the-character-encoding-in-SMPP-[actually allows the default to be mapped to any other character set with a control panel option]. It is suggested that users check with their SMSC operator to confirm exactly which character set is being used as the default. == Message splitting and throttling After transforming a message body from a String to a byte array, the Camel component is also responsible for splitting the message into parts (within the 140 byte SMS size limit) before passing it to JSMPP. This is completed automatically. If the GSM 3.38 alphabet is used, the component will pack up to 160 characters into the 140 byte message body. If an 8 bit character set is used (e.g. ISO-8859-1 for western Europe) then 140 characters will be allowed within the 140 byte message body. If 16 bit UCS-2 encoding is used then just 70 characters fit into each 140 byte message. Some SMSC providers implement throttling rules. Each part of a message that has been split may be counted separately by the provider's throttling mechanism. The Camel Throttler component can be useful for throttling messages in the SMPP route before handing them to the SMSC. == URI format [source,java] -------------------------------------------- smpp://[username@]hostname[:port][?options] smpps://[username@]hostname[:port][?options] -------------------------------------------- If no *username* is provided, then Camel will provide the default value `smppclient`. + If no *port* number is provided, then Camel will provide the default value `2775`. + If the protocol name is ""smpps"", camel-smpp with try to use SSLSocket to init a connection to the server. You can append query options to the URI in the following format, `?option=value&option=value&...` == URI Options // component options: START The SMPP component supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (advanced) | To use the shared SmppConfiguration as configuration. | | SmppConfiguration | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *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 | *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 |=== // component options: END // endpoint options: START The SMPP endpoint is configured using URI syntax: ---- smpp:host:port ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *host* | Hostname for the SMSC server to use. | localhost | String | *port* | Port number for the SMSC server to use. | 2775 | Integer |=== === Query Parameters (40 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *initialReconnectDelay* (common) | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | long | *maxReconnect* (common) | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | int | *reconnectDelay* (common) | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | long | *splittingPolicy* (common) | You can specify a policy for handling long messages: ALLOW - the default, long messages are split to 140 bytes per message TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered. REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long. | ALLOW | SmppSplittingPolicy | *systemType* (common) | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *addressRange* (consumer) | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *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 | *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. | | ExchangePattern | *destAddr* (producer) | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *destAddrNpi* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *destAddrTon* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *lazySessionCreation* (producer) | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | boolean | *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 | *numberingPlanIndicator* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *priorityFlag* (producer) | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level 2 priority 3: Level 3 (highest) priority | | byte | *protocolId* (producer) | The protocol id | | byte | *registeredDelivery* (producer) | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined: 0: No SMSC delivery receipt requested. 1: SMSC delivery receipt requested where final delivery outcome is success or failure. 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure. | | byte | *replaceIfPresentFlag* (producer) | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined: 0: Don't replace 1: Replace | | byte | *serviceType* (producer) | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined: CMT: Cellular Messaging CPT: Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting WAP: Wireless Application Protocol USSD: Unstructured Supplementary Services Data | | String | *sourceAddr* (producer) | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *sourceAddrNpi* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *sourceAddrTon* (producer) | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *typeOfNumber* (producer) | Defines the type of number (TON) to be used in the SME. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *enquireLinkTimer* (advanced) | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *sessionStateListener* (advanced) | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transactionTimer* (advanced) | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *alphabet* (codec) | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19. 0: SMSC Default Alphabet 4: 8 bit Alphabet 8: UCS2 Alphabet | | byte | *dataCoding* (codec) | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are: 0: SMSC Default Alphabet 3: Latin 1 (ISO-8859-1) 4: Octet unspecified (8-bit binary) 8: UCS2 (ISO/IEC-10646) 13: Extended Kanji JIS(X 0212-1990) | | byte | *encoding* (codec) | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *httpProxyHost* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *httpProxyPassword* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *httpProxyPort* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *httpProxyUsername* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *proxyHeaders* (proxy) | These headers will be passed to the proxy server while establishing the connection. | | Map | *password* (security) | The password for connecting to SMSC server. | | String | *systemId* (security) | The system id (username) for connecting to SMSC server. | smppclient | String | *usingSSL* (security) | Whether using SSL with the smpps protocol | false | boolean |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-smpp-starter x.x.x ---- The component supports 40 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.smpp.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.smpp.bridge-error-handler* | 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 | *camel.component.smpp.configuration.address-range* | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *camel.component.smpp.configuration.alphabet* | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19.
  • 0: SMSC Default Alphabet
  • 4: 8 bit Alphabet
  • 8: UCS2 Alphabet
| | Byte | *camel.component.smpp.configuration.data-coding* | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are:
  • 0: SMSC Default Alphabet
  • 3: Latin 1 (ISO-8859-1)
  • 4: Octet unspecified (8-bit binary)
  • 8: UCS2 (ISO/IEC-10646)
  • 13: Extended Kanji JIS(X 0212-1990)
| | Byte | *camel.component.smpp.configuration.dest-addr* | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *camel.component.smpp.configuration.dest-addr-npi* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.dest-addr-ton* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.encoding* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *camel.component.smpp.configuration.enquire-link-timer* | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *camel.component.smpp.configuration.host* | Hostname for the SMSC server to use. | localhost | String | *camel.component.smpp.configuration.http-proxy-host* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-password* | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-port* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *camel.component.smpp.configuration.http-proxy-username* | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *camel.component.smpp.configuration.initial-reconnect-delay* | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | Long | *camel.component.smpp.configuration.lazy-session-creation* | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | Boolean | *camel.component.smpp.configuration.max-reconnect* | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | Integer | *camel.component.smpp.configuration.numbering-plan-indicator* | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.password* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | | String | *camel.component.smpp.configuration.port* | Port number for the SMSC server to use. | 2775 | Integer | *camel.component.smpp.configuration.priority-flag* | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported:
  • 0: Level 0 (lowest) priority
  • 1: Level 1 priority
  • 2: Level 2 priority
  • 3: Level 3 (highest) priority
| | Byte | *camel.component.smpp.configuration.protocol-id* | The protocol id | | Byte | *camel.component.smpp.configuration.proxy-headers* | These headers will be passed to the proxy server while establishing the connection. | | Map | *camel.component.smpp.configuration.reconnect-delay* | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | Long | *camel.component.smpp.configuration.registered-delivery* | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined:
  • 0: No SMSC delivery receipt requested.
  • 1: SMSC delivery receipt requested where final delivery outcome is success or failure.
  • 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure.
| | Byte | *camel.component.smpp.configuration.replace-if-present-flag* | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined:
  • 0: Don't replace
  • 1: Replace
| | Byte | *camel.component.smpp.configuration.service-type* | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined:
  • CMT: Cellular Messaging
  • CPT: Cellular Paging
  • VMN: Voice Mail Notification
  • VMA: Voice Mail Alerting
  • WAP: Wireless Application Protocol
  • USSD: Unstructured Supplementary Services Data
| | String | *camel.component.smpp.configuration.session-state-listener* | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *camel.component.smpp.configuration.source-addr* | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *camel.component.smpp.configuration.source-addr-npi* | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.source-addr-ton* | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.splitting-policy* | You can specify a policy for handling long messages:
  • ALLOW - the default, long messages are split to 140 bytes per message
  • TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered.
  • REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long.
| | SmppSplittingPolicy | *camel.component.smpp.configuration.system-id* | The system id (username) for connecting to SMSC server. | smppclient | String | *camel.component.smpp.configuration.system-type* | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *camel.component.smpp.configuration.transaction-timer* | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *camel.component.smpp.configuration.type-of-number* | Defines the type of number (TON) to be used in the SME. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.using-s-s-l* | Whether using SSL with the smpps protocol | false | Boolean | *camel.component.smpp.enabled* | Enable smpp component | true | Boolean | *camel.component.smpp.lazy-start-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 |=== // spring-boot-auto-configure options: END You can have as many of these options as you like. [source,java] ------------------------------------------------------------------------------------------------------------------ smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer ------------------------------------------------------------------------------------------------------------------ == Producer Message Headers The following message headers can be used to affect the behavior of the SMPP producer [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppDestAddr` |`List`/`String` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the destination SME address(es). For mobile terminated messages, this is the directory number of the recipient MS. Is must be a `List` for SubmitMulti and a `String` otherwise. |`CamelSmppDestAddrTon` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the type of number (TON) to be used in the SME destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppDestAddrNpi` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddr` |`String` |Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrTon` |`Byte` |Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppSourceAddrNpi` |`Byte` |Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppServiceType` |`String` |The service type parameter can be used to indicate the SMS Application service associated with the message. Use the URI option `serviceType` settings above. |`CamelSmppRegisteredDelivery` |`Byte` |*only for SubmitSm, ReplaceSm, SubmitMulti and DataSm* Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. Use the URI option `registeredDelivery` settings above. |`CamelSmppPriorityFlag` |`Byte` |*only for SubmitSm and SubmitMulti* Allows the originating SME to assign a priority level to the short message. Use the URI option `priorityFlag` settings above. |`CamelSmppScheduleDeliveryTime` |`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in chapter 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String`/`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. If it's provided as `Date`, it's interpreted as absolute time or relative time format if you provide it as `String` as specified in chapter 7.1.1 in the smpp specification v3.4. |`CamelSmppReplaceIfPresentFlag` |`Byte` |*only for SubmitSm and SubmitMulti* The replace if present flag parameter is used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following values are defined: `0`, Don't replace and `1`, Replace |`CamelSmppAlphabet` / `CamelSmppDataCoding` |`Byte` |*For SubmitSm, SubmitMulti and ReplaceSm* The data coding according to the SMPP 3.4 specification, section 5.2.19. Use the URI option `alphabet` settings above. |`CamelSmppOptionalParameter` |`Map` |*only for SubmitSm, SubmitMulti and DataSm* The optional parameter which are send to the SMSC. The value is converted in the following way: `String` -> `org.jsmpp.bean.OptionalParameter.COctetString`, `byte[]` -> `org.jsmpp.bean.OptionalParameter.OctetString`, `Byte` -> `org.jsmpp.bean.OptionalParameter.Byte`, `Integer` -> `org.jsmpp.bean.OptionalParameter.Int`, `Short` -> `org.jsmpp.bean.OptionalParameter.Short`, `null` -> `org.jsmpp.bean.OptionalParameter.Null` |CamelSmppEncoding |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the encoding (character set name) of the bytes in the message body. If the message body is a string then this is not relevant because Java Strings are always Unicode. If the body is a byte array then this header can be used to indicate that it is ISO-8859-1 or some other value. Default value is specified by the endpoint configuration parameter _encoding_ |CamelSmppSplittingPolicy |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the policy for message splitting for this exchange. Possible values are described in the endpoint configuration parameter _splittingPolicy_ |======================================================================= The following message headers are used by the SMPP producer to set the response from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppId` |`List`/`String` |The id to identify the submitted short message(s) for later use. In case of a ReplaceSm, QuerySm, CancelSm and DataSm this header vaule is a `String`. In case of a SubmitSm or SubmitMultiSm this header vaule is a `List`. |`CamelSmppSentMessageCount` |`Integer` |*only for SubmitSm and SubmitMultiSm* The total number of messages which has been sent. |`CamelSmppError` |`Map>>` |*only for SubmitMultiSm* The errors which occurred by sending the short message(s) the form `Map>>` (messageID : (destAddr : address, error : errorCode)). |`CamelSmppOptionalParameter` |`Map` |*only for DataSm* The optional parameter which are returned from the SMSC by sending the message. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= == Consumer Message Headers The following message headers are used by the SMPP consumer to set the request data from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppSequenceNumber` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* A sequence number allows a response PDU to be correlated with a request PDU. The associated SMPP response PDU must preserve this field. |`CamelSmppCommandId` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* The command id field identifies the particular SMPP PDU. For the complete list of defined values see chapter 5.1.2.1 in the smpp specification v3.4. |`CamelSmppSourceAddr` |`String` |*only for AlertNotification, DeliverSm and DataSm* Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrNpi` |`Byte` |*only for AlertNotification and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddrTon` |`Byte` |*only for AlertNotification and DataSm* Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppEsmeAddr` |`String` |*only for AlertNotification* Defines the destination ESME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppEsmeAddrNpi` |`Byte` |*only for AlertNotification* Defines the numeric plan indicator (NPI) to be used in the ESME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppEsmeAddrTon` |`Byte` |*only for AlertNotification* Defines the type of number (TON) to be used in the ESME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppId` |`String` |*only for smsc DeliveryReceipt and DataSm* The message ID allocated to the message by the SMSC when originally submitted. |`CamelSmppDelivered` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages delivered. This is only relevant where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDoneDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message reached it's final state. The format is as follows: YYMMDDhhmm. |`CamelSmppStatus` |`DeliveryReceiptState` |*only for smsc DeliveryReceipt:* The final status of the message. The following values are defined: `DELIVRD`: Message is delivered to destination, `EXPIRED`: Message validity period has expired, `DELETED`: Message has been deleted, `UNDELIV`: Message is undeliverable, `ACCEPTD`: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service), `UNKNOWN`: Message is in invalid state, `REJECTD`: Message is in a rejected state |`CamelSmppCommandStatus` |`Integer` |*only for DataSm* The Command status of the message. |`CamelSmppError` |`String` |*only for smsc DeliveryReceipt* Where appropriate this may hold a Network specific error code or an SMSC error code for the attempted delivery of the message. These errors are Network or SMSC specific and are not included here. |`CamelSmppSubmitDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message was submitted. In the case of a message which has been replaced, this is the date that the original message was replaced. The format is as follows: YYMMDDhhmm. |`CamelSmppSubmitted` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages originally submitted. This is only relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDestAddr` |`String` |*only for DeliverSm and DataSm:* Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppScheduleDeliveryTime` |`String` |*only for DeliverSm:* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in Section 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String` |*only for DeliverSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. It can be defined in absolute time format or relative time format. The encoding of absolute and relative time format is specified in Section 7.1.1 in the smpp specification v3.4. |`CamelSmppServiceType` |`String` |*only for DeliverSm and DataSm* The service type parameter indicates the SMS Application service associated with the message. |`CamelSmppRegisteredDelivery` |`Byte` |*only for DataSm* Is used to request an delivery receipt and/or SME originated acknowledgements. Same values as in Producer header list above. |`CamelSmppDestAddrNpi` |`Byte` |*only for DataSm* Defines the numeric plan indicator (NPI) in the destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppDestAddrTon` |`Byte` |*only for DataSm* Defines the type of number (TON) in the destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppMessageType` |`String` |Identifies the type of an incoming message: `AlertNotification`: an SMSC alert notification, `DataSm`: an SMSC data short message, `DeliveryReceipt`: an SMSC delivery receipt, `DeliverSm`: an SMSC deliver short message |`CamelSmppOptionalParameter` |`Map` |*only for DeliverSm* The optional parameters send back by the SMSC. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= TIP: *JSMPP library* See the documentation of the http://jsmpp.org[JSMPP Library] for more details about the underlying library. == Exception handling This component supports the general Camel exception handling capabilities When an error occurs sending a message with SubmitSm (the default action), the org.apache.camel.component.smpp.SmppException is thrown with a nested exception, org.jsmpp.extra.NegativeResponseException. Call NegativeResponseException.getCommandStatus() to obtain the exact SMPP negative response code, the values are explained in the SMPP specification 3.4, section 5.1.3. + When the SMPP consumer receives a `DeliverSm` or `DataSm` short message and the processing of these messages fails, you can also throw a `ProcessRequestException` instead of handle the failure. In this case, this exception is forwarded to the underlying http://jsmpp.org[JSMPP library] which will return the included error code to the SMSC. This feature is useful to e.g. instruct the SMSC to resend the short message at a later time. This could be done with the following lines of code: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .doTry() .to(""bean:dao?method=updateSmsState"") .doCatch(Exception.class) .throwException(new ProcessRequestException(""update of sms state failed"", 100)) .end(); -------------------------------------------------------------------------------------------------------------------------- Please refer to the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP specification] for the complete list of error codes and their meanings. == Samples A route which sends an SMS using the Java DSL: [source,java] ------------------------------------------------------------------------------------------ from(""direct:start"") .to(""smpp://smppclient@localhost:2775? password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=producer""); ------------------------------------------------------------------------------------------ A route which sends an SMS using the Spring XML DSL: [source,xml] ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Java DSL: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Spring XML DSL: [source,xml] ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- TIP: *SMSC simulator* If you need an SMSC simulator for your test, you can use the simulator provided by http://opensmpp.logica.com/CommonPart/Download/download2.html#simulator[Logica]. == Debug logging This component has log level *DEBUG*, which can be helpful in debugging problems. If you use log4j, you can add the following line to your configuration: [source,java] -------------------------------------------------- log4j.logger.org.apache.camel.component.smpp=DEBUG -------------------------------------------------- ",12108,False,2387.8617610949022,median "// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2020 The Vuicoin 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 #include #include #include #include #include #include