utils.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // Copyright 2012 Google Inc. All Rights Reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the COPYING file in the root of the source
  5. // tree. An additional intellectual property rights grant can be found
  6. // in the file PATENTS. All contributing project authors may
  7. // be found in the AUTHORS file in the root of the source tree.
  8. // -----------------------------------------------------------------------------
  9. //
  10. // Misc. common utility functions
  11. //
  12. // Author: Skal (pascal.massimino@gmail.com)
  13. #include <stdlib.h>
  14. #include <string.h> // for memcpy()
  15. #include "../webp/decode.h"
  16. #include "../webp/encode.h"
  17. #include "../webp/format_constants.h" // for MAX_PALETTE_SIZE
  18. #include "./color_cache_utils.h"
  19. #include "./utils.h"
  20. // If PRINT_MEM_INFO is defined, extra info (like total memory used, number of
  21. // alloc/free etc) is printed. For debugging/tuning purpose only (it's slow,
  22. // and not multi-thread safe!).
  23. // An interesting alternative is valgrind's 'massif' tool:
  24. // https://valgrind.org/docs/manual/ms-manual.html
  25. // Here is an example command line:
  26. /* valgrind --tool=massif --massif-out-file=massif.out \
  27. --stacks=yes --alloc-fn=WebPSafeMalloc --alloc-fn=WebPSafeCalloc
  28. ms_print massif.out
  29. */
  30. // In addition:
  31. // * if PRINT_MEM_TRAFFIC is defined, all the details of the malloc/free cycles
  32. // are printed.
  33. // * if MALLOC_FAIL_AT is defined, the global environment variable
  34. // $MALLOC_FAIL_AT is used to simulate a memory error when calloc or malloc
  35. // is called for the nth time. Example usage:
  36. // export MALLOC_FAIL_AT=50 && ./examples/cwebp input.png
  37. // * if MALLOC_LIMIT is defined, the global environment variable $MALLOC_LIMIT
  38. // sets the maximum amount of memory (in bytes) made available to libwebp.
  39. // This can be used to emulate environment with very limited memory.
  40. // Example: export MALLOC_LIMIT=64000000 && ./examples/dwebp picture.webp
  41. // #define PRINT_MEM_INFO
  42. // #define PRINT_MEM_TRAFFIC
  43. // #define MALLOC_FAIL_AT
  44. // #define MALLOC_LIMIT
  45. //------------------------------------------------------------------------------
  46. // Checked memory allocation
  47. #if defined(PRINT_MEM_INFO)
  48. #include <stdio.h>
  49. static int num_malloc_calls = 0;
  50. static int num_calloc_calls = 0;
  51. static int num_free_calls = 0;
  52. static int countdown_to_fail = 0; // 0 = off
  53. typedef struct MemBlock MemBlock;
  54. struct MemBlock {
  55. void* ptr_;
  56. size_t size_;
  57. MemBlock* next_;
  58. };
  59. static MemBlock* all_blocks = NULL;
  60. static size_t total_mem = 0;
  61. static size_t total_mem_allocated = 0;
  62. static size_t high_water_mark = 0;
  63. static size_t mem_limit = 0;
  64. static int exit_registered = 0;
  65. static void PrintMemInfo(void) {
  66. fprintf(stderr, "\nMEMORY INFO:\n");
  67. fprintf(stderr, "num calls to: malloc = %4d\n", num_malloc_calls);
  68. fprintf(stderr, " calloc = %4d\n", num_calloc_calls);
  69. fprintf(stderr, " free = %4d\n", num_free_calls);
  70. fprintf(stderr, "total_mem: %u\n", (uint32_t)total_mem);
  71. fprintf(stderr, "total_mem allocated: %u\n", (uint32_t)total_mem_allocated);
  72. fprintf(stderr, "high-water mark: %u\n", (uint32_t)high_water_mark);
  73. while (all_blocks != NULL) {
  74. MemBlock* b = all_blocks;
  75. all_blocks = b->next_;
  76. free(b);
  77. }
  78. }
  79. static void Increment(int* const v) {
  80. if (!exit_registered) {
  81. #if defined(MALLOC_FAIL_AT)
  82. {
  83. const char* const malloc_fail_at_str = getenv("MALLOC_FAIL_AT");
  84. if (malloc_fail_at_str != NULL) {
  85. countdown_to_fail = atoi(malloc_fail_at_str);
  86. }
  87. }
  88. #endif
  89. #if defined(MALLOC_LIMIT)
  90. {
  91. const char* const malloc_limit_str = getenv("MALLOC_LIMIT");
  92. #if MALLOC_LIMIT > 1
  93. mem_limit = (size_t)MALLOC_LIMIT;
  94. #endif
  95. if (malloc_limit_str != NULL) {
  96. mem_limit = atoi(malloc_limit_str);
  97. }
  98. }
  99. #endif
  100. (void)countdown_to_fail;
  101. (void)mem_limit;
  102. atexit(PrintMemInfo);
  103. exit_registered = 1;
  104. }
  105. ++*v;
  106. }
  107. static void AddMem(void* ptr, size_t size) {
  108. if (ptr != NULL) {
  109. MemBlock* const b = (MemBlock*)malloc(sizeof(*b));
  110. if (b == NULL) abort();
  111. b->next_ = all_blocks;
  112. all_blocks = b;
  113. b->ptr_ = ptr;
  114. b->size_ = size;
  115. total_mem += size;
  116. total_mem_allocated += size;
  117. #if defined(PRINT_MEM_TRAFFIC)
  118. #if defined(MALLOC_FAIL_AT)
  119. fprintf(stderr, "fail-count: %5d [mem=%u]\n",
  120. num_malloc_calls + num_calloc_calls, (uint32_t)total_mem);
  121. #else
  122. fprintf(stderr, "Mem: %u (+%u)\n", (uint32_t)total_mem, (uint32_t)size);
  123. #endif
  124. #endif
  125. if (total_mem > high_water_mark) high_water_mark = total_mem;
  126. }
  127. }
  128. static void SubMem(void* ptr) {
  129. if (ptr != NULL) {
  130. MemBlock** b = &all_blocks;
  131. // Inefficient search, but that's just for debugging.
  132. while (*b != NULL && (*b)->ptr_ != ptr) b = &(*b)->next_;
  133. if (*b == NULL) {
  134. fprintf(stderr, "Invalid pointer free! (%p)\n", ptr);
  135. abort();
  136. }
  137. {
  138. MemBlock* const block = *b;
  139. *b = block->next_;
  140. total_mem -= block->size_;
  141. #if defined(PRINT_MEM_TRAFFIC)
  142. fprintf(stderr, "Mem: %u (-%u)\n",
  143. (uint32_t)total_mem, (uint32_t)block->size_);
  144. #endif
  145. free(block);
  146. }
  147. }
  148. }
  149. #else
  150. #define Increment(v) do {} while (0)
  151. #define AddMem(p, s) do {} while (0)
  152. #define SubMem(p) do {} while (0)
  153. #endif
  154. // Returns 0 in case of overflow of nmemb * size.
  155. static int CheckSizeArgumentsOverflow(uint64_t nmemb, size_t size) {
  156. const uint64_t total_size = nmemb * size;
  157. if (nmemb == 0) return 1;
  158. if ((uint64_t)size > WEBP_MAX_ALLOCABLE_MEMORY / nmemb) return 0;
  159. if (!CheckSizeOverflow(total_size)) return 0;
  160. #if defined(PRINT_MEM_INFO) && defined(MALLOC_FAIL_AT)
  161. if (countdown_to_fail > 0 && --countdown_to_fail == 0) {
  162. return 0; // fake fail!
  163. }
  164. #endif
  165. #if defined(PRINT_MEM_INFO) && defined(MALLOC_LIMIT)
  166. if (mem_limit > 0) {
  167. const uint64_t new_total_mem = (uint64_t)total_mem + total_size;
  168. if (!CheckSizeOverflow(new_total_mem) ||
  169. new_total_mem > mem_limit) {
  170. return 0; // fake fail!
  171. }
  172. }
  173. #endif
  174. return 1;
  175. }
  176. void* WebPSafeMalloc(uint64_t nmemb, size_t size) {
  177. void* ptr;
  178. Increment(&num_malloc_calls);
  179. if (!CheckSizeArgumentsOverflow(nmemb, size)) return NULL;
  180. assert(nmemb * size > 0);
  181. ptr = malloc((size_t)(nmemb * size));
  182. AddMem(ptr, (size_t)(nmemb * size));
  183. return ptr;
  184. }
  185. void* WebPSafeCalloc(uint64_t nmemb, size_t size) {
  186. void* ptr;
  187. Increment(&num_calloc_calls);
  188. if (!CheckSizeArgumentsOverflow(nmemb, size)) return NULL;
  189. assert(nmemb * size > 0);
  190. ptr = calloc((size_t)nmemb, size);
  191. AddMem(ptr, (size_t)(nmemb * size));
  192. return ptr;
  193. }
  194. void WebPSafeFree(void* const ptr) {
  195. if (ptr != NULL) {
  196. Increment(&num_free_calls);
  197. SubMem(ptr);
  198. }
  199. free(ptr);
  200. }
  201. // Public API functions.
  202. void* WebPMalloc(size_t size) {
  203. return WebPSafeMalloc(1, size);
  204. }
  205. void WebPFree(void* ptr) {
  206. WebPSafeFree(ptr);
  207. }
  208. //------------------------------------------------------------------------------
  209. void WebPCopyPlane(const uint8_t* src, int src_stride,
  210. uint8_t* dst, int dst_stride, int width, int height) {
  211. assert(src != NULL && dst != NULL);
  212. assert(abs(src_stride) >= width && abs(dst_stride) >= width);
  213. while (height-- > 0) {
  214. memcpy(dst, src, width);
  215. src += src_stride;
  216. dst += dst_stride;
  217. }
  218. }
  219. void WebPCopyPixels(const WebPPicture* const src, WebPPicture* const dst) {
  220. assert(src != NULL && dst != NULL);
  221. assert(src->width == dst->width && src->height == dst->height);
  222. assert(src->use_argb && dst->use_argb);
  223. WebPCopyPlane((uint8_t*)src->argb, 4 * src->argb_stride, (uint8_t*)dst->argb,
  224. 4 * dst->argb_stride, 4 * src->width, src->height);
  225. }
  226. //------------------------------------------------------------------------------
  227. #define COLOR_HASH_SIZE (MAX_PALETTE_SIZE * 4)
  228. #define COLOR_HASH_RIGHT_SHIFT 22 // 32 - log2(COLOR_HASH_SIZE).
  229. int WebPGetColorPalette(const WebPPicture* const pic, uint32_t* const palette) {
  230. int i;
  231. int x, y;
  232. int num_colors = 0;
  233. uint8_t in_use[COLOR_HASH_SIZE] = { 0 };
  234. uint32_t colors[COLOR_HASH_SIZE];
  235. const uint32_t* argb = pic->argb;
  236. const int width = pic->width;
  237. const int height = pic->height;
  238. uint32_t last_pix = ~argb[0]; // so we're sure that last_pix != argb[0]
  239. assert(pic != NULL);
  240. assert(pic->use_argb);
  241. for (y = 0; y < height; ++y) {
  242. for (x = 0; x < width; ++x) {
  243. int key;
  244. if (argb[x] == last_pix) {
  245. continue;
  246. }
  247. last_pix = argb[x];
  248. key = VP8LHashPix(last_pix, COLOR_HASH_RIGHT_SHIFT);
  249. while (1) {
  250. if (!in_use[key]) {
  251. colors[key] = last_pix;
  252. in_use[key] = 1;
  253. ++num_colors;
  254. if (num_colors > MAX_PALETTE_SIZE) {
  255. return MAX_PALETTE_SIZE + 1; // Exact count not needed.
  256. }
  257. break;
  258. } else if (colors[key] == last_pix) {
  259. break; // The color is already there.
  260. } else {
  261. // Some other color sits here, so do linear conflict resolution.
  262. ++key;
  263. key &= (COLOR_HASH_SIZE - 1); // Key mask.
  264. }
  265. }
  266. }
  267. argb += pic->argb_stride;
  268. }
  269. if (palette != NULL) { // Fill the colors into palette.
  270. num_colors = 0;
  271. for (i = 0; i < COLOR_HASH_SIZE; ++i) {
  272. if (in_use[i]) {
  273. palette[num_colors] = colors[i];
  274. ++num_colors;
  275. }
  276. }
  277. }
  278. return num_colors;
  279. }
  280. #undef COLOR_HASH_SIZE
  281. #undef COLOR_HASH_RIGHT_SHIFT
  282. //------------------------------------------------------------------------------
  283. #if defined(WEBP_NEED_LOG_TABLE_8BIT)
  284. const uint8_t WebPLogTable8bit[256] = { // 31 ^ clz(i)
  285. 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
  286. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  287. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  288. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  289. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  290. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  291. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  292. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  293. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  294. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  295. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  296. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  297. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  298. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  299. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  300. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
  301. };
  302. #endif
  303. //------------------------------------------------------------------------------