utils.c 9.1 KB

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