image.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. #include <jni.h>
  2. #include <cstdio>
  3. #include <csetjmp>
  4. #include <cstdlib>
  5. #include <cstring>
  6. #include <cmath>
  7. #include <unistd.h>
  8. #include <android/bitmap.h>
  9. #include <string>
  10. #include <mozjpeg/java/org_libjpegturbo_turbojpeg_TJ.h>
  11. #include <mozjpeg/jpeglib.h>
  12. #include <tgnet/FileLog.h>
  13. #include <vector>
  14. #include <algorithm>
  15. #include "libwebp/webp/decode.h"
  16. #include "libwebp/webp/encode.h"
  17. #include "mozjpeg/turbojpeg.h"
  18. #include "c_utils.h"
  19. extern "C" {
  20. jclass jclass_NullPointerException;
  21. jclass jclass_RuntimeException;
  22. jclass jclass_Options;
  23. jfieldID jclass_Options_inJustDecodeBounds;
  24. jfieldID jclass_Options_outHeight;
  25. jfieldID jclass_Options_outWidth;
  26. jint imageOnJNILoad(JavaVM *vm, JNIEnv *env) {
  27. jclass_NullPointerException = (jclass) env->NewGlobalRef(env->FindClass("java/lang/NullPointerException"));
  28. if (jclass_NullPointerException == 0) {
  29. return JNI_FALSE;
  30. }
  31. jclass_RuntimeException = (jclass) env->NewGlobalRef(env->FindClass("java/lang/RuntimeException"));
  32. if (jclass_RuntimeException == 0) {
  33. return JNI_FALSE;
  34. }
  35. jclass_Options = (jclass) env->NewGlobalRef(env->FindClass("android/graphics/BitmapFactory$Options"));
  36. if (jclass_Options == 0) {
  37. return JNI_FALSE;
  38. }
  39. jclass_Options_inJustDecodeBounds = env->GetFieldID(jclass_Options, "inJustDecodeBounds", "Z");
  40. if (jclass_Options_inJustDecodeBounds == 0) {
  41. return JNI_FALSE;
  42. }
  43. jclass_Options_outHeight = env->GetFieldID(jclass_Options, "outHeight", "I");
  44. if (jclass_Options_outHeight == 0) {
  45. return JNI_FALSE;
  46. }
  47. jclass_Options_outWidth = env->GetFieldID(jclass_Options, "outWidth", "I");
  48. if (jclass_Options_outWidth == 0) {
  49. return JNI_FALSE;
  50. }
  51. return JNI_TRUE;
  52. }
  53. static inline uint64_t getColors(const uint8_t *p) {
  54. return p[0] + (p[1] << 16) + ((uint64_t) p[2] << 32) + ((uint64_t) p[3] << 48);
  55. }
  56. static inline uint64_t getColors565(const uint8_t *p) {
  57. uint16_t *ps = (uint16_t *) p;
  58. return ((((ps[0] & 0xF800) >> 11) * 255) / 31) + (((((ps[0] & 0x07E0) >> 5) * 255) / 63) << 16) + ((uint64_t)(((ps[0] & 0x001F) * 255) / 31) << 32);
  59. }
  60. static void fastBlurMore(int32_t w, int32_t h, int32_t stride, uint8_t *pix, int32_t radius) {
  61. const int32_t r1 = radius + 1;
  62. const int32_t div = radius * 2 + 1;
  63. if (radius > 15 || div >= w || div >= h || w * h > 150 * 150 || stride > w * 4) {
  64. return;
  65. }
  66. uint64_t *rgb = new uint64_t[w * h];
  67. if (rgb == NULL) {
  68. return;
  69. }
  70. int32_t x, y, i;
  71. int32_t yw = 0;
  72. const int32_t we = w - r1;
  73. for (y = 0; y < h; y++) {
  74. uint64_t cur = getColors(&pix[yw]);
  75. uint64_t rgballsum = -radius * cur;
  76. uint64_t rgbsum = cur * ((r1 * (r1 + 1)) >> 1);
  77. for (i = 1; i <= radius; i++) {
  78. cur = getColors(&pix[yw + i * 4]);
  79. rgbsum += cur * (r1 - i);
  80. rgballsum += cur;
  81. }
  82. x = 0;
  83. #define update(start, middle, end) \
  84. rgb[y * w + x] = (rgbsum >> 6) & 0x00FF00FF00FF00FF; \
  85. rgballsum += getColors(&pix[yw + (start) * 4]) - 2 * getColors(&pix[yw + (middle) * 4]) + getColors(&pix[yw + (end) * 4]); \
  86. rgbsum += rgballsum; \
  87. x++; \
  88. while (x < r1) {
  89. update (0, x, x + r1)
  90. }
  91. while (x < we) {
  92. update (x - r1, x, x + r1)
  93. }
  94. while (x < w) {
  95. update (x - r1, x, w - 1)
  96. }
  97. #undef update
  98. yw += stride;
  99. }
  100. const int32_t he = h - r1;
  101. for (x = 0; x < w; x++) {
  102. uint64_t rgballsum = -radius * rgb[x];
  103. uint64_t rgbsum = rgb[x] * ((r1 * (r1 + 1)) >> 1);
  104. for (i = 1; i <= radius; i++) {
  105. rgbsum += rgb[i * w + x] * (r1 - i);
  106. rgballsum += rgb[i * w + x];
  107. }
  108. y = 0;
  109. int32_t yi = x * 4;
  110. #define update(start, middle, end) \
  111. int64_t res = rgbsum >> 6; \
  112. pix[yi] = res; \
  113. pix[yi + 1] = res >> 16; \
  114. pix[yi + 2] = res >> 32; \
  115. pix[yi + 3] = res >> 48; \
  116. rgballsum += rgb[x + (start) * w] - 2 * rgb[x + (middle) * w] + rgb[x + (end) * w]; \
  117. rgbsum += rgballsum; \
  118. y++; \
  119. yi += stride;
  120. while (y < r1) {
  121. update (0, y, y + r1)
  122. }
  123. while (y < he) {
  124. update (y - r1, y, y + r1)
  125. }
  126. while (y < h) {
  127. update (y - r1, y, h - 1)
  128. }
  129. #undef update
  130. }
  131. delete[] rgb;
  132. }
  133. static void fastBlur(int32_t w, int32_t h, int32_t stride, uint8_t *pix, int32_t radius) {
  134. if (pix == nullptr) {
  135. return;
  136. }
  137. const int32_t r1 = radius + 1;
  138. const int32_t div = radius * 2 + 1;
  139. int32_t shift;
  140. if (radius == 1) {
  141. shift = 2;
  142. } else if (radius == 3) {
  143. shift = 4;
  144. } else if (radius == 7) {
  145. shift = 6;
  146. } else if (radius == 15) {
  147. shift = 8;
  148. } else {
  149. return;
  150. }
  151. if (radius > 15 || div >= w || div >= h || w * h > 150 * 150 || stride > w * 4) {
  152. return;
  153. }
  154. uint64_t *rgb = new uint64_t[w * h];
  155. if (rgb == nullptr) {
  156. return;
  157. }
  158. int32_t x, y, i;
  159. int32_t yw = 0;
  160. const int32_t we = w - r1;
  161. for (y = 0; y < h; y++) {
  162. uint64_t cur = getColors(&pix[yw]);
  163. uint64_t rgballsum = -radius * cur;
  164. uint64_t rgbsum = cur * ((r1 * (r1 + 1)) >> 1);
  165. for (i = 1; i <= radius; i++) {
  166. cur = getColors(&pix[yw + i * 4]);
  167. rgbsum += cur * (r1 - i);
  168. rgballsum += cur;
  169. }
  170. x = 0;
  171. #define update(start, middle, end) \
  172. rgb[y * w + x] = (rgbsum >> shift) & 0x00FF00FF00FF00FFLL; \
  173. rgballsum += getColors(&pix[yw + (start) * 4]) - 2 * getColors(&pix[yw + (middle) * 4]) + getColors(&pix[yw + (end) * 4]); \
  174. rgbsum += rgballsum; \
  175. x++; \
  176. while (x < r1) {
  177. update (0, x, x + r1)
  178. }
  179. while (x < we) {
  180. update (x - r1, x, x + r1)
  181. }
  182. while (x < w) {
  183. update (x - r1, x, w - 1)
  184. }
  185. #undef update
  186. yw += stride;
  187. }
  188. const int32_t he = h - r1;
  189. for (x = 0; x < w; x++) {
  190. uint64_t rgballsum = -radius * rgb[x];
  191. uint64_t rgbsum = rgb[x] * ((r1 * (r1 + 1)) >> 1);
  192. for (i = 1; i <= radius; i++) {
  193. rgbsum += rgb[i * w + x] * (r1 - i);
  194. rgballsum += rgb[i * w + x];
  195. }
  196. y = 0;
  197. int32_t yi = x * 4;
  198. #define update(start, middle, end) \
  199. int64_t res = rgbsum >> shift; \
  200. pix[yi] = res; \
  201. pix[yi + 1] = res >> 16; \
  202. pix[yi + 2] = res >> 32; \
  203. pix[yi + 3] = res >> 48; \
  204. rgballsum += rgb[x + (start) * w] - 2 * rgb[x + (middle) * w] + rgb[x + (end) * w]; \
  205. rgbsum += rgballsum; \
  206. y++; \
  207. yi += stride;
  208. while (y < r1) {
  209. update (0, y, y + r1)
  210. }
  211. while (y < he) {
  212. update (y - r1, y, y + r1)
  213. }
  214. while (y < h) {
  215. update (y - r1, y, h - 1)
  216. }
  217. #undef update
  218. }
  219. delete[] rgb;
  220. }
  221. static void fastBlurMore565(int32_t w, int32_t h, int32_t stride, uint8_t *pix, int32_t radius) {
  222. const int32_t r1 = radius + 1;
  223. const int32_t div = radius * 2 + 1;
  224. if (radius > 15 || div >= w || div >= h || w * h > 150 * 150 || stride > w * 2) {
  225. return;
  226. }
  227. uint64_t *rgb = new uint64_t[w * h];
  228. if (rgb == NULL) {
  229. return;
  230. }
  231. int32_t x, y, i;
  232. int32_t yw = 0;
  233. const int32_t we = w - r1;
  234. for (y = 0; y < h; y++) {
  235. uint64_t cur = getColors565(&pix[yw]);
  236. uint64_t rgballsum = -radius * cur;
  237. uint64_t rgbsum = cur * ((r1 * (r1 + 1)) >> 1);
  238. for (i = 1; i <= radius; i++) {
  239. cur = getColors565(&pix[yw + i * 2]);
  240. rgbsum += cur * (r1 - i);
  241. rgballsum += cur;
  242. }
  243. x = 0;
  244. #define update(start, middle, end) \
  245. rgb[y * w + x] = (rgbsum >> 6) & 0x00FF00FF00FF00FF; \
  246. rgballsum += getColors565(&pix[yw + (start) * 2]) - 2 * getColors565(&pix[yw + (middle) * 2]) + getColors565(&pix[yw + (end) * 2]); \
  247. rgbsum += rgballsum; \
  248. x++; \
  249. while (x < r1) {
  250. update (0, x, x + r1)
  251. }
  252. while (x < we) {
  253. update (x - r1, x, x + r1)
  254. }
  255. while (x < w) {
  256. update (x - r1, x, w - 1)
  257. }
  258. #undef update
  259. yw += stride;
  260. }
  261. const int32_t he = h - r1;
  262. for (x = 0; x < w; x++) {
  263. uint64_t rgballsum = -radius * rgb[x];
  264. uint64_t rgbsum = rgb[x] * ((r1 * (r1 + 1)) >> 1);
  265. for (i = 1; i <= radius; i++) {
  266. rgbsum += rgb[i * w + x] * (r1 - i);
  267. rgballsum += rgb[i * w + x];
  268. }
  269. y = 0;
  270. int32_t yi = x * 2;
  271. #define update(start, middle, end) \
  272. int64_t res = rgbsum >> 6; \
  273. pix[yi] = ((res >> 13) & 0xe0) | ((res >> 35) & 0x1f); \
  274. pix[yi + 1] = (res & 0xf8) | ((res >> 21) & 0x7); \
  275. rgballsum += rgb[x + (start) * w] - 2 * rgb[x + (middle) * w] + rgb[x + (end) * w]; \
  276. rgbsum += rgballsum; \
  277. y++; \
  278. yi += stride;
  279. while (y < r1) {
  280. update (0, y, y + r1)
  281. }
  282. while (y < he) {
  283. update (y - r1, y, y + r1)
  284. }
  285. while (y < h) {
  286. update (y - r1, y, h - 1)
  287. }
  288. #undef update
  289. }
  290. delete[] rgb;
  291. }
  292. static void fastBlur565(int32_t w, int32_t h, int32_t stride, uint8_t *pix, int32_t radius) {
  293. if (pix == NULL) {
  294. return;
  295. }
  296. const int32_t r1 = radius + 1;
  297. const int32_t div = radius * 2 + 1;
  298. int32_t shift;
  299. if (radius == 1) {
  300. shift = 2;
  301. } else if (radius == 3) {
  302. shift = 4;
  303. } else if (radius == 7) {
  304. shift = 6;
  305. } else if (radius == 15) {
  306. shift = 8;
  307. } else {
  308. return;
  309. }
  310. if (radius > 15 || div >= w || div >= h || w * h > 150 * 150 || stride > w * 2) {
  311. return;
  312. }
  313. uint64_t *rgb = new uint64_t[w * h];
  314. if (rgb == NULL) {
  315. return;
  316. }
  317. int32_t x, y, i;
  318. int32_t yw = 0;
  319. const int32_t we = w - r1;
  320. for (y = 0; y < h; y++) {
  321. uint64_t cur = getColors565(&pix[yw]);
  322. uint64_t rgballsum = -radius * cur;
  323. uint64_t rgbsum = cur * ((r1 * (r1 + 1)) >> 1);
  324. for (i = 1; i <= radius; i++) {
  325. cur = getColors565(&pix[yw + i * 2]);
  326. rgbsum += cur * (r1 - i);
  327. rgballsum += cur;
  328. }
  329. x = 0;
  330. #define update(start, middle, end) \
  331. rgb[y * w + x] = (rgbsum >> shift) & 0x00FF00FF00FF00FFLL; \
  332. rgballsum += getColors565(&pix[yw + (start) * 2]) - 2 * getColors565(&pix[yw + (middle) * 2]) + getColors565(&pix[yw + (end) * 2]); \
  333. rgbsum += rgballsum; \
  334. x++;
  335. while (x < r1) {
  336. update(0, x, x + r1)
  337. }
  338. while (x < we) {
  339. update(x - r1, x, x + r1)
  340. }
  341. while (x < w) {
  342. update(x - r1, x, w - 1)
  343. }
  344. #undef update
  345. yw += stride;
  346. }
  347. const int32_t he = h - r1;
  348. for (x = 0; x < w; x++) {
  349. uint64_t rgballsum = -radius * rgb[x];
  350. uint64_t rgbsum = rgb[x] * ((r1 * (r1 + 1)) >> 1);
  351. for (i = 1; i <= radius; i++) {
  352. rgbsum += rgb[i * w + x] * (r1 - i);
  353. rgballsum += rgb[i * w + x];
  354. }
  355. y = 0;
  356. int32_t yi = x * 2;
  357. #define update(start, middle, end) \
  358. uint64_t res = rgbsum >> shift; \
  359. pix[yi] = ((res >> 13) & 0xe0) | ((res >> 35) & 0x1f); \
  360. pix[yi + 1] = (res & 0xf8) | ((res >> 21) & 0x7); \
  361. rgballsum += rgb[x + (start) * w] - 2 * rgb[x + (middle) * w] + rgb[x + (end) * w]; \
  362. rgbsum += rgballsum; \
  363. y++; \
  364. yi += stride;
  365. while (y < r1) {
  366. update (0, y, y + r1)
  367. }
  368. while (y < he) {
  369. update (y - r1, y, y + r1)
  370. }
  371. while (y < h) {
  372. update (y - r1, y, h - 1)
  373. }
  374. #undef update
  375. }
  376. delete[] rgb;
  377. }
  378. JNIEXPORT int Java_org_telegram_messenger_Utilities_needInvert(JNIEnv *env, jclass clazz, jobject bitmap, jint unpin, jint width, jint height, jint stride) {
  379. if (!bitmap) {
  380. return 0;
  381. }
  382. if (!width || !height || !stride || stride != width * 4 || width * height > 150 * 150) {
  383. return 0;
  384. }
  385. void *pixels = nullptr;
  386. if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
  387. return 0;
  388. }
  389. if (pixels == nullptr) {
  390. return 0;
  391. }
  392. uint8_t *pix = (uint8_t *) pixels;
  393. int32_t hasAlpha = 0;
  394. float matching = 0;
  395. float total = 0;
  396. for (int32_t y = 0; y < height; y++) {
  397. for (int32_t x = 0; x < width; x++) {
  398. int32_t index = y * stride + x * 4;
  399. uint8_t a = pix[index + 3];
  400. float alpha = a / 255.0f;
  401. uint8_t r = (uint8_t)(pix[index] * alpha);
  402. uint8_t g = (uint8_t)(pix[index + 1] * alpha);
  403. uint8_t b = (uint8_t)(pix[index + 2] * alpha);
  404. uint8_t cmax = (r > g) ? r : g;
  405. if (b > cmax) {
  406. cmax = b;
  407. }
  408. uint8_t cmin = (r < g) ? r : g;
  409. if (b < cmin) {
  410. cmin = b;
  411. }
  412. float saturation;
  413. float brightness = ((float) cmax) / 255.0f;
  414. if (cmax != 0) {
  415. saturation = ((float) (cmax - cmin)) / ((float) cmax);
  416. } else {
  417. saturation = 0;
  418. }
  419. if (alpha < 1.0) {
  420. hasAlpha = 1;
  421. }
  422. if (alpha > 0.0) {
  423. total += 1;
  424. if (saturation < 0.1f && brightness < 0.25f) {
  425. matching += 1;
  426. }
  427. }
  428. }
  429. }
  430. if (unpin) {
  431. AndroidBitmap_unlockPixels(env, bitmap);
  432. }
  433. return hasAlpha && matching / total > 0.85;
  434. }
  435. JNIEXPORT void Java_org_telegram_messenger_Utilities_blurBitmap(JNIEnv *env, jclass clazz, jobject bitmap, jint radius, jint unpin, jint width, jint height, jint stride) {
  436. if (!bitmap) {
  437. return;
  438. }
  439. if (!width || !height || !stride) {
  440. return;
  441. }
  442. void *pixels = nullptr;
  443. if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
  444. return;
  445. }
  446. if (stride == width * 2) {
  447. if (radius <= 3) {
  448. fastBlur565(width, height, stride, (uint8_t *) pixels, radius);
  449. } else {
  450. fastBlurMore565(width, height, stride, (uint8_t *) pixels, radius);
  451. }
  452. } else {
  453. if (radius <= 3) {
  454. fastBlur(width, height, stride, (uint8_t *) pixels, radius);
  455. } else {
  456. fastBlurMore(width, height, stride, (uint8_t *) pixels, radius);
  457. }
  458. }
  459. if (unpin) {
  460. AndroidBitmap_unlockPixels(env, bitmap);
  461. }
  462. }
  463. const uint32_t PGPhotoEnhanceHistogramBins = 256;
  464. const uint32_t PGPhotoEnhanceSegments = 4;
  465. JNIEXPORT void Java_org_telegram_messenger_Utilities_calcCDT(JNIEnv *env, jclass clazz, jobject hsvBuffer, jint width, jint height, jobject buffer, jobject calcBuffer) {
  466. float imageWidth = width;
  467. float imageHeight = height;
  468. float _clipLimit = 1.25f;
  469. uint32_t totalSegments = PGPhotoEnhanceSegments * PGPhotoEnhanceSegments;
  470. uint32_t tileArea = (uint32_t) (floorf(imageWidth / PGPhotoEnhanceSegments) * floorf(imageHeight / PGPhotoEnhanceSegments));
  471. uint32_t clipLimit = (uint32_t) MAX(1, _clipLimit * tileArea / (float) PGPhotoEnhanceHistogramBins);
  472. float scale = 255.0f / (float) tileArea;
  473. unsigned char *bytes = (unsigned char *) env->GetDirectBufferAddress(hsvBuffer);
  474. uint32_t *calcBytes = (uint32_t *) env->GetDirectBufferAddress(calcBuffer);
  475. unsigned char *result = (unsigned char *) env->GetDirectBufferAddress(buffer);
  476. uint32_t *cdfsMin = calcBytes;
  477. calcBytes += totalSegments;
  478. uint32_t *cdfsMax = calcBytes;
  479. calcBytes += totalSegments;
  480. uint32_t *cdfs = calcBytes;
  481. calcBytes += totalSegments * PGPhotoEnhanceHistogramBins;
  482. uint32_t *hist = calcBytes;
  483. memset(hist, 0, sizeof(uint32_t) * totalSegments * PGPhotoEnhanceHistogramBins);
  484. float xMul = PGPhotoEnhanceSegments / imageWidth;
  485. float yMul = PGPhotoEnhanceSegments / imageHeight;
  486. uint32_t i, j;
  487. for (i = 0; i < imageHeight; i++) {
  488. uint32_t yOffset = i * width * 4;
  489. for (j = 0; j < imageWidth; j++) {
  490. uint32_t index = j * 4 + yOffset;
  491. uint32_t tx = (uint32_t)(j * xMul);
  492. uint32_t ty = (uint32_t)(i * yMul);
  493. uint32_t t = ty * PGPhotoEnhanceSegments + tx;
  494. hist[t * PGPhotoEnhanceHistogramBins + bytes[index + 2]]++;
  495. }
  496. }
  497. for (i = 0; i < totalSegments; i++) {
  498. if (clipLimit > 0) {
  499. uint32_t clipped = 0;
  500. for (j = 0; j < PGPhotoEnhanceHistogramBins; j++) {
  501. if (hist[i * PGPhotoEnhanceHistogramBins + j] > clipLimit) {
  502. clipped += hist[i * PGPhotoEnhanceHistogramBins + j] - clipLimit;
  503. hist[i * PGPhotoEnhanceHistogramBins + j] = clipLimit;
  504. }
  505. }
  506. uint32_t redistBatch = clipped / PGPhotoEnhanceHistogramBins;
  507. uint32_t residual = clipped - redistBatch * PGPhotoEnhanceHistogramBins;
  508. for (j = 0; j < PGPhotoEnhanceHistogramBins; j++) {
  509. hist[i * PGPhotoEnhanceHistogramBins + j] += redistBatch;
  510. if (j < residual) {
  511. hist[i * PGPhotoEnhanceHistogramBins + j]++;
  512. }
  513. }
  514. }
  515. memcpy(cdfs + i * PGPhotoEnhanceHistogramBins, hist + i * PGPhotoEnhanceHistogramBins, PGPhotoEnhanceHistogramBins * sizeof(uint32_t));
  516. uint32_t hMin = PGPhotoEnhanceHistogramBins - 1;
  517. for (j = 0; j < hMin; ++j) {
  518. if (cdfs[i * PGPhotoEnhanceHistogramBins + j] != 0) {
  519. hMin = j;
  520. }
  521. }
  522. uint32_t cdf = 0;
  523. for (j = hMin; j < PGPhotoEnhanceHistogramBins; j++) {
  524. cdf += cdfs[i * PGPhotoEnhanceHistogramBins + j];
  525. cdfs[i * PGPhotoEnhanceHistogramBins + j] = (uint8_t) MIN(255, cdf * scale);
  526. }
  527. cdfsMin[i] = cdfs[i * PGPhotoEnhanceHistogramBins + hMin];
  528. cdfsMax[i] = cdfs[i * PGPhotoEnhanceHistogramBins + PGPhotoEnhanceHistogramBins - 1];
  529. }
  530. for (j = 0; j < totalSegments; j++) {
  531. uint32_t yOffset = j * PGPhotoEnhanceHistogramBins * 4;
  532. for (i = 0; i < PGPhotoEnhanceHistogramBins; i++) {
  533. uint32_t index = i * 4 + yOffset;
  534. result[index] = (uint8_t) cdfs[j * PGPhotoEnhanceHistogramBins + i];
  535. result[index + 1] = (uint8_t) cdfsMin[j];
  536. result[index + 2] = (uint8_t) cdfsMax[j];
  537. result[index + 3] = 255;
  538. }
  539. }
  540. }
  541. JNIEXPORT jint Java_org_telegram_messenger_Utilities_pinBitmap(JNIEnv *env, jclass clazz, jobject bitmap) {
  542. if (bitmap == nullptr) {
  543. return 0;
  544. }
  545. void *pixels;
  546. return AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0 ? 1 : 0;
  547. }
  548. JNIEXPORT void Java_org_telegram_messenger_Utilities_unpinBitmap(JNIEnv *env, jclass clazz, jobject bitmap) {
  549. if (bitmap == nullptr) {
  550. return;
  551. }
  552. AndroidBitmap_unlockPixels(env, bitmap);
  553. }
  554. JNIEXPORT jboolean Java_org_telegram_messenger_Utilities_loadWebpImage(JNIEnv *env, jclass clazz, jobject outputBitmap, jobject buffer, jint len, jobject options, jboolean unpin) {
  555. if (!buffer) {
  556. env->ThrowNew(jclass_NullPointerException, "Input buffer can not be null");
  557. return 0;
  558. }
  559. jbyte *inputBuffer = (jbyte *) env->GetDirectBufferAddress(buffer);
  560. int32_t bitmapWidth = 0;
  561. int32_t bitmapHeight = 0;
  562. if (!WebPGetInfo((uint8_t *)inputBuffer, len, &bitmapWidth, &bitmapHeight)) {
  563. env->ThrowNew(jclass_RuntimeException, "Invalid WebP format");
  564. return 0;
  565. }
  566. if (options && env->GetBooleanField(options, jclass_Options_inJustDecodeBounds) == JNI_TRUE) {
  567. env->SetIntField(options, jclass_Options_outWidth, bitmapWidth);
  568. env->SetIntField(options, jclass_Options_outHeight, bitmapHeight);
  569. return 1;
  570. }
  571. if (!outputBitmap) {
  572. env->ThrowNew(jclass_NullPointerException, "output bitmap can not be null");
  573. return 0;
  574. }
  575. AndroidBitmapInfo bitmapInfo;
  576. if (AndroidBitmap_getInfo(env, outputBitmap, &bitmapInfo) != ANDROID_BITMAP_RESUT_SUCCESS) {
  577. env->ThrowNew(jclass_RuntimeException, "Failed to get Bitmap information");
  578. return 0;
  579. }
  580. void *bitmapPixels = nullptr;
  581. if (AndroidBitmap_lockPixels(env, outputBitmap, &bitmapPixels) != ANDROID_BITMAP_RESUT_SUCCESS) {
  582. env->ThrowNew(jclass_RuntimeException, "Failed to lock Bitmap pixels");
  583. return 0;
  584. }
  585. if (!WebPDecodeRGBAInto((uint8_t *) inputBuffer, len, (uint8_t *) bitmapPixels, bitmapInfo.height * bitmapInfo.stride, bitmapInfo.stride)) {
  586. AndroidBitmap_unlockPixels(env, outputBitmap);
  587. env->ThrowNew(jclass_RuntimeException, "Failed to decode webp image");
  588. return 0;
  589. }
  590. if (unpin && AndroidBitmap_unlockPixels(env, outputBitmap) != ANDROID_BITMAP_RESUT_SUCCESS) {
  591. env->ThrowNew(jclass_RuntimeException, "Failed to unlock Bitmap pixels");
  592. return 0;
  593. }
  594. return 1;
  595. }
  596. #define SQUARE(i) ((i)*(i))
  597. inline static void zeroClearInt(int *p, size_t count) {
  598. memset(p, 0, sizeof(int) * count);
  599. }
  600. JNIEXPORT void Java_org_telegram_messenger_Utilities_stackBlurBitmap(JNIEnv *env, jclass clazz, jobject bitmap, jint radius) {
  601. if (radius < 1) {
  602. return;
  603. }
  604. AndroidBitmapInfo info;
  605. if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS) {
  606. return;
  607. }
  608. if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
  609. return;
  610. }
  611. int w = info.width;
  612. int h = info.height;
  613. int stride = info.stride;
  614. unsigned char *pixels = nullptr;
  615. AndroidBitmap_lockPixels(env, bitmap, (void **) &pixels);
  616. if (!pixels) {
  617. return;
  618. }
  619. // Constants
  620. //const int radius = (int)inradius; // Transform unsigned into signed for further operations
  621. const int wm = w - 1;
  622. const int hm = h - 1;
  623. const int wh = w * h;
  624. const int div = radius + radius + 1;
  625. const int r1 = radius + 1;
  626. const int divsum = SQUARE((div + 1) >> 1);
  627. // Small buffers
  628. int stack[div * 4];
  629. zeroClearInt(stack, div * 4);
  630. int vmin[MAX(w, h)];
  631. zeroClearInt(vmin, MAX(w, h));
  632. // Large buffers
  633. int *r = new int[wh];
  634. int *g = new int[wh];
  635. int *b = new int[wh];
  636. int *a = new int[wh];
  637. zeroClearInt(r, wh);
  638. zeroClearInt(g, wh);
  639. zeroClearInt(b, wh);
  640. zeroClearInt(a, wh);
  641. const size_t dvcount = 256 * divsum;
  642. int *dv = new int[dvcount];
  643. int i;
  644. for (i = 0; (size_t) i < dvcount; i++) {
  645. dv[i] = (i / divsum);
  646. }
  647. // Variables
  648. int x, y;
  649. int *sir;
  650. int routsum, goutsum, boutsum, aoutsum;
  651. int rinsum, ginsum, binsum, ainsum;
  652. int rsum, gsum, bsum, asum, p, yp;
  653. int stackpointer;
  654. int stackstart;
  655. int rbs;
  656. int yw = 0, yi = 0;
  657. for (y = 0; y < h; y++) {
  658. ainsum = aoutsum = asum = rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
  659. for (i = -radius; i <= radius; i++) {
  660. sir = &stack[(i + radius) * 4];
  661. int offset = (y * stride + (MIN(wm, MAX(i, 0))) * 4);
  662. sir[0] = pixels[offset];
  663. sir[1] = pixels[offset + 1];
  664. sir[2] = pixels[offset + 2];
  665. sir[3] = pixels[offset + 3];
  666. rbs = r1 - abs(i);
  667. rsum += sir[0] * rbs;
  668. gsum += sir[1] * rbs;
  669. bsum += sir[2] * rbs;
  670. asum += sir[3] * rbs;
  671. if (i > 0) {
  672. rinsum += sir[0];
  673. ginsum += sir[1];
  674. binsum += sir[2];
  675. ainsum += sir[3];
  676. } else {
  677. routsum += sir[0];
  678. goutsum += sir[1];
  679. boutsum += sir[2];
  680. aoutsum += sir[3];
  681. }
  682. }
  683. stackpointer = radius;
  684. for (x = 0; x < w; x++) {
  685. r[yi] = dv[rsum];
  686. g[yi] = dv[gsum];
  687. b[yi] = dv[bsum];
  688. a[yi] = dv[asum];
  689. rsum -= routsum;
  690. gsum -= goutsum;
  691. bsum -= boutsum;
  692. asum -= aoutsum;
  693. stackstart = stackpointer - radius + div;
  694. sir = &stack[(stackstart % div) * 4];
  695. routsum -= sir[0];
  696. goutsum -= sir[1];
  697. boutsum -= sir[2];
  698. aoutsum -= sir[3];
  699. if (y == 0) {
  700. vmin[x] = MIN(x + radius + 1, wm);
  701. }
  702. int offset = (y * stride + vmin[x] * 4);
  703. sir[0] = pixels[offset];
  704. sir[1] = pixels[offset + 1];
  705. sir[2] = pixels[offset + 2];
  706. sir[3] = pixels[offset + 3];
  707. rinsum += sir[0];
  708. ginsum += sir[1];
  709. binsum += sir[2];
  710. ainsum += sir[3];
  711. rsum += rinsum;
  712. gsum += ginsum;
  713. bsum += binsum;
  714. asum += ainsum;
  715. stackpointer = (stackpointer + 1) % div;
  716. sir = &stack[(stackpointer % div) * 4];
  717. routsum += sir[0];
  718. goutsum += sir[1];
  719. boutsum += sir[2];
  720. aoutsum += sir[3];
  721. rinsum -= sir[0];
  722. ginsum -= sir[1];
  723. binsum -= sir[2];
  724. ainsum -= sir[3];
  725. yi++;
  726. }
  727. yw += w;
  728. }
  729. for (x = 0; x < w; x++) {
  730. ainsum = aoutsum = asum = rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
  731. yp = -radius * w;
  732. for (i = -radius; i <= radius; i++) {
  733. yi = MAX(0, yp) + x;
  734. sir = &stack[(i + radius) * 4];
  735. sir[0] = r[yi];
  736. sir[1] = g[yi];
  737. sir[2] = b[yi];
  738. sir[3] = a[yi];
  739. rbs = r1 - abs(i);
  740. rsum += r[yi] * rbs;
  741. gsum += g[yi] * rbs;
  742. bsum += b[yi] * rbs;
  743. asum += a[yi] * rbs;
  744. if (i > 0) {
  745. rinsum += sir[0];
  746. ginsum += sir[1];
  747. binsum += sir[2];
  748. ainsum += sir[3];
  749. } else {
  750. routsum += sir[0];
  751. goutsum += sir[1];
  752. boutsum += sir[2];
  753. aoutsum += sir[3];
  754. }
  755. if (i < hm) {
  756. yp += w;
  757. }
  758. }
  759. stackpointer = radius;
  760. for (y = 0; y < h; y++) {
  761. int offset = stride * y + x * 4;
  762. pixels[offset] = dv[rsum];
  763. pixels[offset + 1] = dv[gsum];
  764. pixels[offset + 2] = dv[bsum];
  765. pixels[offset + 3] = dv[asum];
  766. rsum -= routsum;
  767. gsum -= goutsum;
  768. bsum -= boutsum;
  769. asum -= aoutsum;
  770. stackstart = stackpointer - radius + div;
  771. sir = &stack[(stackstart % div) * 4];
  772. routsum -= sir[0];
  773. goutsum -= sir[1];
  774. boutsum -= sir[2];
  775. aoutsum -= sir[3];
  776. if (x == 0) {
  777. vmin[y] = (MIN(y + r1, hm)) * w;
  778. }
  779. p = x + vmin[y];
  780. sir[0] = r[p];
  781. sir[1] = g[p];
  782. sir[2] = b[p];
  783. sir[3] = a[p];
  784. rinsum += sir[0];
  785. ginsum += sir[1];
  786. binsum += sir[2];
  787. ainsum += sir[3];
  788. rsum += rinsum;
  789. gsum += ginsum;
  790. bsum += binsum;
  791. asum += ainsum;
  792. stackpointer = (stackpointer + 1) % div;
  793. sir = &stack[stackpointer * 4];
  794. routsum += sir[0];
  795. goutsum += sir[1];
  796. boutsum += sir[2];
  797. aoutsum += sir[3];
  798. rinsum -= sir[0];
  799. ginsum -= sir[1];
  800. binsum -= sir[2];
  801. ainsum -= sir[3];
  802. yi += w;
  803. }
  804. }
  805. delete[] r;
  806. delete[] g;
  807. delete[] b;
  808. delete[] a;
  809. delete[] dv;
  810. AndroidBitmap_unlockPixels(env, bitmap);
  811. }
  812. JNIEXPORT void Java_org_telegram_messenger_Utilities_drawDitheredGradient(JNIEnv *env, jclass clazz, jobject bitmap, jintArray colors, jint startX, jint startY, jint endX, jint endY) {
  813. AndroidBitmapInfo info;
  814. void *pixelsBuffer;
  815. int reason;
  816. if ((reason = AndroidBitmap_getInfo(env, bitmap, &info)) != ANDROID_BITMAP_RESULT_SUCCESS) {
  817. env->ThrowNew(jclass_RuntimeException, "AndroidBitmap_getInfo failed with a reason: " + reason);
  818. return;
  819. }
  820. if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
  821. env->ThrowNew(jclass_RuntimeException, "Bitmap must be in ARGB_8888 format");
  822. return;
  823. }
  824. if ((reason = AndroidBitmap_lockPixels(env, bitmap, &pixelsBuffer)) != ANDROID_BITMAP_RESULT_SUCCESS) {
  825. env->ThrowNew(jclass_RuntimeException, "AndroidBitmap_lockPixels failed with a reason: " + reason);
  826. return;
  827. }
  828. uint8_t i, j, n;
  829. // gradient colors extracting
  830. jint *colorsBuffer = env->GetIntArrayElements(colors, 0);
  831. uint8_t *colorsComponents = (uint8_t *) colorsBuffer;
  832. float colorsF[4][2];
  833. for (i = 0; i < 4; i++) {
  834. // swap red and green channels
  835. n = (uint8_t) (i == 0 ? 2 : (i == 2 ? 0 : i));
  836. for (j = 0; j < 2; j++) {
  837. colorsF[n][j] = colorsComponents[j * 4 + i] / 255.F;
  838. }
  839. }
  840. env->ReleaseIntArrayElements(colors, colorsBuffer, JNI_ABORT);
  841. // gradient vector
  842. const int32_t vx = endX - startX;
  843. const int32_t vy = endY - startY;
  844. const float vSquaredMag = vx * vx + vy * vy;
  845. float noise, fraction, error, componentF;
  846. float *pixelsComponentsF = new float[info.height * info.stride * 4];
  847. memset(pixelsComponentsF, 0, info.height * info.stride * 4 * sizeof(float));
  848. uint8_t * bitmapPixelsComponents = (uint8_t * )
  849. pixelsBuffer;
  850. int32_t x, y;
  851. int32_t offset;
  852. int32_t position;
  853. for (y = 0; y < info.height; y++) {
  854. offset = y * info.stride;
  855. for (x = 0; x < info.width; x++) {
  856. // triangular probability density function dither noise
  857. noise = (rand() - rand()) / 255.F / RAND_MAX;
  858. // alpha channel
  859. bitmapPixelsComponents[offset + x * 4 + 3] = 255;
  860. for (i = 0; i < 3; i++) {
  861. position = offset + x * 4 + i;
  862. fraction = (vx * (x - startX) + vy * (y - startY)) / vSquaredMag;
  863. // gradient interpolation and noise
  864. pixelsComponentsF[position] += colorsF[i][0] + fraction * (colorsF[i][1] - colorsF[i][0]) + noise;
  865. // clamp
  866. if (pixelsComponentsF[position] > 1.F) {
  867. pixelsComponentsF[position] = 1.F;
  868. } else if (pixelsComponentsF[position] < 0.F) {
  869. pixelsComponentsF[position] = 0.F;
  870. }
  871. // draw
  872. componentF = roundf(pixelsComponentsF[position] * 255.F);
  873. bitmapPixelsComponents[position] = (uint8_t)
  874. componentF;
  875. // floyd-steinberg dithering
  876. error = pixelsComponentsF[position] - componentF / 255.F;
  877. if (x + 1 < info.width) {
  878. pixelsComponentsF[position + 4] += error * 7.F / 16.F;
  879. if (y + 1 < info.height) {
  880. pixelsComponentsF[position + info.height + 4] += error * 1.F / 16.F;
  881. }
  882. }
  883. if (y + 1 < info.height) {
  884. pixelsComponentsF[position + info.height] += error * 5.F / 16.F;
  885. if (x - 1 >= 0) {
  886. pixelsComponentsF[position + info.height - 4] += error * 3.F / 16.F;
  887. }
  888. }
  889. }
  890. }
  891. }
  892. delete[] pixelsComponentsF;
  893. if ((reason = AndroidBitmap_unlockPixels(env, bitmap)) != ANDROID_BITMAP_RESULT_SUCCESS) {
  894. env->ThrowNew(jclass_RuntimeException, "AndroidBitmap_unlockPixels failed with a reason: " + reason);
  895. return;
  896. }
  897. }
  898. JNIEXPORT jint Java_org_telegram_messenger_Utilities_saveProgressiveJpeg(JNIEnv *env, jclass clazz, jobject bitmap, jint width, jint height, jint stride, jint quality, jstring path) {
  899. if (!bitmap || !path || !width || !height || !stride || stride != width * 4) {
  900. return 0;
  901. }
  902. void *pixels = 0;
  903. if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
  904. return 0;
  905. }
  906. if (pixels == NULL) {
  907. return 0;
  908. }
  909. tjhandle handle = 0;
  910. if ((handle = tjInitCompress()) == NULL) {
  911. return 0;
  912. }
  913. const char *pathStr = env->GetStringUTFChars(path, 0);
  914. std::string filePath = std::string(pathStr);
  915. if (pathStr != 0) {
  916. env->ReleaseStringUTFChars(path, pathStr);
  917. }
  918. const char *enabledValue = "1";
  919. const char *disabledValue = "0";
  920. setenv("TJ_OPTIMIZE", enabledValue, 1);
  921. setenv("TJ_ARITHMETIC", disabledValue, 1);
  922. setenv("TJ_PROGRESSIVE", enabledValue, 1);
  923. setenv("TJ_REVERT", enabledValue, 1);
  924. TJSAMP jpegSubsamp = TJSAMP::TJSAMP_420;
  925. jint buffSize = (jint) tjBufSize(width, height, jpegSubsamp);
  926. unsigned char *jpegBuf = new unsigned char[buffSize];
  927. unsigned char *srcBuf = (unsigned char *) pixels;
  928. int pf = org_libjpegturbo_turbojpeg_TJ_PF_RGBA;
  929. jsize actualPitch = width * tjPixelSize[pf];
  930. jsize arraySize = (height - 1) * actualPitch + (width) * tjPixelSize[pf];
  931. unsigned long jpegSize = tjBufSize(width, height, jpegSubsamp);
  932. if (tjCompress2(handle, srcBuf, width, stride, height, pf, &jpegBuf, &jpegSize, jpegSubsamp, quality, TJFLAG_ACCURATEDCT | TJFLAG_PROGRESSIVE | TJFLAG_NOREALLOC) == 0) {
  933. FILE *f = fopen(filePath.c_str(), "wb");
  934. if (f && fwrite(jpegBuf, sizeof(unsigned char), jpegSize, f) == jpegSize) {
  935. fflush(f);
  936. fsync(fileno(f));
  937. } else {
  938. jpegSize = -1;
  939. }
  940. fclose(f);
  941. } else {
  942. jpegSize = -1;
  943. }
  944. delete[] jpegBuf;
  945. tjDestroy(handle);
  946. AndroidBitmap_unlockPixels(env, bitmap);
  947. return jpegSize;
  948. /*struct jpeg_compress_struct cinfo;
  949. struct jpeg_error_mgr jerr;
  950. cinfo.err = jpeg_std_error(&jerr);
  951. jpeg_create_compress(&cinfo);
  952. const char *pathStr = env->GetStringUTFChars(path, 0);
  953. std::string filePath = std::string(pathStr);
  954. if (pathStr != 0) {
  955. env->ReleaseStringUTFChars(path, pathStr);
  956. }
  957. uint8_t *outBuffer = NULL;
  958. unsigned long outSize = 0;
  959. jpeg_mem_dest(&cinfo, &outBuffer, &outSize);
  960. unsigned char *srcBuf = (unsigned char *) pixels;
  961. cinfo.image_width = (uint32_t) width;
  962. cinfo.image_height = (uint32_t) height;
  963. cinfo.input_components = 4;
  964. cinfo.in_color_space = JCS_EXT_RGBA;
  965. jpeg_c_set_int_param(&cinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST);
  966. jpeg_set_defaults(&cinfo);
  967. cinfo.arith_code = FALSE;
  968. cinfo.dct_method = JDCT_ISLOW;
  969. cinfo.optimize_coding = TRUE;
  970. jpeg_set_quality(&cinfo, 78, 1);
  971. jpeg_simple_progression(&cinfo);
  972. jpeg_start_compress(&cinfo, 1);
  973. JSAMPROW rowPointer[1];
  974. while (cinfo.next_scanline < cinfo.image_height) {
  975. rowPointer[0] = (JSAMPROW) (srcBuf + cinfo.next_scanline * stride);
  976. jpeg_write_scanlines(&cinfo, rowPointer, 1);
  977. }
  978. jpeg_finish_compress(&cinfo);
  979. FILE *f = fopen(filePath.c_str(), "wb");
  980. if (f && fwrite(outBuffer, sizeof(uint8_t), outSize, f) == outSize) {
  981. fflush(f);
  982. fsync(fileno(f));
  983. }
  984. fclose(f);
  985. jpeg_destroy_compress(&cinfo);
  986. return outSize;*/
  987. }
  988. std::vector<std::pair<float, float>> gatherPositions(std::vector<std::pair<float, float>> list, int phase) {
  989. std::vector<std::pair<float, float>> result(4);
  990. for (int i = 0; i < 4; i++) {
  991. int pos = phase + i * 2;
  992. while (pos >= 8) {
  993. pos -= 8;
  994. }
  995. result[i] = list[pos];
  996. result[i].second = 1.0f - result[i].second;
  997. }
  998. return result;
  999. }
  1000. thread_local static float *pixelCache = nullptr;
  1001. JNIEXPORT void Java_org_telegram_messenger_Utilities_generateGradient(JNIEnv *env, jclass clazz, jobject bitmap, jboolean unpin, jint phase, jfloat progress, jint width, jint height, jint stride, jintArray colors) {
  1002. if (!bitmap) {
  1003. return;
  1004. }
  1005. if (!width || !height) {
  1006. return;
  1007. }
  1008. uint8_t *pixels = nullptr;
  1009. if (AndroidBitmap_lockPixels(env, bitmap, (void **) &pixels) < 0) {
  1010. return;
  1011. }
  1012. std::vector<std::pair<float, float>> positions{
  1013. {0.80f, 0.10f},
  1014. {0.60f, 0.20f},
  1015. {0.35f, 0.25f},
  1016. {0.25f, 0.60f},
  1017. {0.20f, 0.90f},
  1018. {0.40f, 0.80f},
  1019. {0.65f, 0.75f},
  1020. {0.75f, 0.40f}
  1021. };
  1022. int32_t previousPhase = phase + 1;
  1023. if (previousPhase > 7) {
  1024. previousPhase = 0;
  1025. }
  1026. std::vector<std::pair<float, float>> previous = gatherPositions(positions, previousPhase);
  1027. std::vector<std::pair<float, float>> current = gatherPositions(positions, phase);
  1028. auto colorsArray = (uint8_t *) env->GetIntArrayElements(colors, nullptr);
  1029. float *newPixelCache = nullptr;
  1030. if (pixelCache == nullptr) {
  1031. newPixelCache = new float[width * height * 2];
  1032. }
  1033. float directPixelY;
  1034. float centerDistanceY;
  1035. float centerDistanceY2;
  1036. int32_t colorsCount = colorsArray[12] == 0 && colorsArray[13] == 0 && colorsArray[14] == 0 && colorsArray[15] == 0 ? 3 : 4;
  1037. for (int y = 0; y < height; y++) {
  1038. if (pixelCache == nullptr) {
  1039. directPixelY = (float) y / (float) height;
  1040. centerDistanceY = directPixelY - 0.5f;
  1041. centerDistanceY2 = centerDistanceY * centerDistanceY;
  1042. }
  1043. uint32_t offset = y * stride;
  1044. for (int x = 0; x < width; x++) {
  1045. float pixelX;
  1046. float pixelY;
  1047. if (pixelCache != nullptr) {
  1048. pixelX = pixelCache[(y * width + x) * 2];
  1049. pixelY = pixelCache[(y * width + x) * 2 + 1];
  1050. } else {
  1051. float directPixelX = (float) x / (float) width;
  1052. float centerDistanceX = directPixelX - 0.5f;
  1053. float centerDistance = sqrtf(centerDistanceX * centerDistanceX + centerDistanceY2);
  1054. float swirlFactor = 0.35f * centerDistance;
  1055. float theta = swirlFactor * swirlFactor * 0.8f * 8.0f;
  1056. float sinTheta = sinf(theta);
  1057. float cosTheta = cosf(theta);
  1058. pixelX = newPixelCache[(y * width + x) * 2] = std::max(0.0f, std::min(1.0f, 0.5f + centerDistanceX * cosTheta - centerDistanceY * sinTheta));
  1059. pixelY = newPixelCache[(y * width + x) * 2 + 1] = std::max(0.0f, std::min(1.0f, 0.5f + centerDistanceX * sinTheta + centerDistanceY * cosTheta));
  1060. }
  1061. float distanceSum = 0.0f;
  1062. float r = 0.0f;
  1063. float g = 0.0f;
  1064. float b = 0.0f;
  1065. for (int i = 0; i < colorsCount; i++) {
  1066. float colorX = previous[i].first + (current[i].first - previous[i].first) * progress;
  1067. float colorY = previous[i].second + (current[i].second - previous[i].second) * progress;
  1068. float distanceX = pixelX - colorX;
  1069. float distanceY = pixelY - colorY;
  1070. float distance = std::max(0.0f, 0.9f - sqrtf(distanceX * distanceX + distanceY * distanceY));
  1071. distance = distance * distance * distance * distance;
  1072. distanceSum += distance;
  1073. r = r + distance * ((float) colorsArray[i * 4] / 255.0f);
  1074. g = g + distance * ((float) colorsArray[i * 4 + 1] / 255.0f);
  1075. b = b + distance * ((float) colorsArray[i * 4 + 2] / 255.0f);
  1076. }
  1077. pixels[offset + x * 4] = (uint8_t) (b / distanceSum * 255.0f);
  1078. pixels[offset + x * 4 + 1] = (uint8_t) (g / distanceSum * 255.0f);
  1079. pixels[offset + x * 4 + 2] = (uint8_t) (r / distanceSum * 255.0f);
  1080. pixels[offset + x * 4 + 3] = 0xff;
  1081. }
  1082. }
  1083. if (newPixelCache != nullptr) {
  1084. delete [] pixelCache;
  1085. pixelCache = newPixelCache;
  1086. }
  1087. env->ReleaseIntArrayElements(colors, (jint *) colorsArray, JNI_ABORT);
  1088. if (unpin) {
  1089. AndroidBitmap_unlockPixels(env, bitmap);
  1090. }
  1091. }
  1092. }