You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

453 lines
13KB

  1. /*
  2. * Copyright (C) 2007 Vitor Sessak <vitor1001@gmail.com>
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * Libav is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with Libav; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * Codebook Generator using the ELBG algorithm
  23. */
  24. #include <string.h>
  25. #include "libavutil/common.h"
  26. #include "libavutil/lfg.h"
  27. #include "elbg.h"
  28. #include "avcodec.h"
  29. #define DELTA_ERR_MAX 0.1 ///< Precision of the ELBG algorithm (as percentage error)
  30. /**
  31. * In the ELBG jargon, a cell is the set of points that are closest to a
  32. * codebook entry. Not to be confused with a RoQ Video cell. */
  33. typedef struct cell_s {
  34. int index;
  35. struct cell_s *next;
  36. } cell;
  37. /**
  38. * ELBG internal data
  39. */
  40. typedef struct elbg_data {
  41. int error;
  42. int dim;
  43. int numCB;
  44. int *codebook;
  45. cell **cells;
  46. int *utility;
  47. int *utility_inc;
  48. int *nearest_cb;
  49. int *points;
  50. AVLFG *rand_state;
  51. int *scratchbuf;
  52. } elbg_data;
  53. static inline int distance_limited(int *a, int *b, int dim, int limit)
  54. {
  55. int i, dist=0;
  56. for (i=0; i<dim; i++) {
  57. dist += (a[i] - b[i])*(a[i] - b[i]);
  58. if (dist > limit)
  59. return INT_MAX;
  60. }
  61. return dist;
  62. }
  63. static inline void vect_division(int *res, int *vect, int div, int dim)
  64. {
  65. int i;
  66. if (div > 1)
  67. for (i=0; i<dim; i++)
  68. res[i] = ROUNDED_DIV(vect[i],div);
  69. else if (res != vect)
  70. memcpy(res, vect, dim*sizeof(int));
  71. }
  72. static int eval_error_cell(elbg_data *elbg, int *centroid, cell *cells)
  73. {
  74. int error=0;
  75. for (; cells; cells=cells->next)
  76. error += distance_limited(centroid, elbg->points + cells->index*elbg->dim, elbg->dim, INT_MAX);
  77. return error;
  78. }
  79. static int get_closest_codebook(elbg_data *elbg, int index)
  80. {
  81. int i, pick=0, diff, diff_min = INT_MAX;
  82. for (i=0; i<elbg->numCB; i++)
  83. if (i != index) {
  84. diff = distance_limited(elbg->codebook + i*elbg->dim, elbg->codebook + index*elbg->dim, elbg->dim, diff_min);
  85. if (diff < diff_min) {
  86. pick = i;
  87. diff_min = diff;
  88. }
  89. }
  90. return pick;
  91. }
  92. static int get_high_utility_cell(elbg_data *elbg)
  93. {
  94. int i=0;
  95. /* Using linear search, do binary if it ever turns to be speed critical */
  96. int r = av_lfg_get(elbg->rand_state)%elbg->utility_inc[elbg->numCB-1] + 1;
  97. while (elbg->utility_inc[i] < r)
  98. i++;
  99. assert(elbg->cells[i]);
  100. return i;
  101. }
  102. /**
  103. * Implementation of the simple LBG algorithm for just two codebooks
  104. */
  105. static int simple_lbg(elbg_data *elbg,
  106. int dim,
  107. int *centroid[3],
  108. int newutility[3],
  109. int *points,
  110. cell *cells)
  111. {
  112. int i, idx;
  113. int numpoints[2] = {0,0};
  114. int *newcentroid[2] = {
  115. elbg->scratchbuf + 3*dim,
  116. elbg->scratchbuf + 4*dim
  117. };
  118. cell *tempcell;
  119. memset(newcentroid[0], 0, 2 * dim * sizeof(*newcentroid[0]));
  120. newutility[0] =
  121. newutility[1] = 0;
  122. for (tempcell = cells; tempcell; tempcell=tempcell->next) {
  123. idx = distance_limited(centroid[0], points + tempcell->index*dim, dim, INT_MAX)>=
  124. distance_limited(centroid[1], points + tempcell->index*dim, dim, INT_MAX);
  125. numpoints[idx]++;
  126. for (i=0; i<dim; i++)
  127. newcentroid[idx][i] += points[tempcell->index*dim + i];
  128. }
  129. vect_division(centroid[0], newcentroid[0], numpoints[0], dim);
  130. vect_division(centroid[1], newcentroid[1], numpoints[1], dim);
  131. for (tempcell = cells; tempcell; tempcell=tempcell->next) {
  132. int dist[2] = {distance_limited(centroid[0], points + tempcell->index*dim, dim, INT_MAX),
  133. distance_limited(centroid[1], points + tempcell->index*dim, dim, INT_MAX)};
  134. int idx = dist[0] > dist[1];
  135. newutility[idx] += dist[idx];
  136. }
  137. return newutility[0] + newutility[1];
  138. }
  139. static void get_new_centroids(elbg_data *elbg, int huc, int *newcentroid_i,
  140. int *newcentroid_p)
  141. {
  142. cell *tempcell;
  143. int *min = newcentroid_i;
  144. int *max = newcentroid_p;
  145. int i;
  146. for (i=0; i< elbg->dim; i++) {
  147. min[i]=INT_MAX;
  148. max[i]=0;
  149. }
  150. for (tempcell = elbg->cells[huc]; tempcell; tempcell = tempcell->next)
  151. for(i=0; i<elbg->dim; i++) {
  152. min[i]=FFMIN(min[i], elbg->points[tempcell->index*elbg->dim + i]);
  153. max[i]=FFMAX(max[i], elbg->points[tempcell->index*elbg->dim + i]);
  154. }
  155. for (i=0; i<elbg->dim; i++) {
  156. int ni = min[i] + (max[i] - min[i])/3;
  157. int np = min[i] + (2*(max[i] - min[i]))/3;
  158. newcentroid_i[i] = ni;
  159. newcentroid_p[i] = np;
  160. }
  161. }
  162. /**
  163. * Add the points in the low utility cell to its closest cell. Split the high
  164. * utility cell, putting the separated points in the (now empty) low utility
  165. * cell.
  166. *
  167. * @param elbg Internal elbg data
  168. * @param indexes {luc, huc, cluc}
  169. * @param newcentroid A vector with the position of the new centroids
  170. */
  171. static void shift_codebook(elbg_data *elbg, int *indexes,
  172. int *newcentroid[3])
  173. {
  174. cell *tempdata;
  175. cell **pp = &elbg->cells[indexes[2]];
  176. while(*pp)
  177. pp= &(*pp)->next;
  178. *pp = elbg->cells[indexes[0]];
  179. elbg->cells[indexes[0]] = NULL;
  180. tempdata = elbg->cells[indexes[1]];
  181. elbg->cells[indexes[1]] = NULL;
  182. while(tempdata) {
  183. cell *tempcell2 = tempdata->next;
  184. int idx = distance_limited(elbg->points + tempdata->index*elbg->dim,
  185. newcentroid[0], elbg->dim, INT_MAX) >
  186. distance_limited(elbg->points + tempdata->index*elbg->dim,
  187. newcentroid[1], elbg->dim, INT_MAX);
  188. tempdata->next = elbg->cells[indexes[idx]];
  189. elbg->cells[indexes[idx]] = tempdata;
  190. tempdata = tempcell2;
  191. }
  192. }
  193. static void evaluate_utility_inc(elbg_data *elbg)
  194. {
  195. int i, inc=0;
  196. for (i=0; i < elbg->numCB; i++) {
  197. if (elbg->numCB*elbg->utility[i] > elbg->error)
  198. inc += elbg->utility[i];
  199. elbg->utility_inc[i] = inc;
  200. }
  201. }
  202. static void update_utility_and_n_cb(elbg_data *elbg, int idx, int newutility)
  203. {
  204. cell *tempcell;
  205. elbg->utility[idx] = newutility;
  206. for (tempcell=elbg->cells[idx]; tempcell; tempcell=tempcell->next)
  207. elbg->nearest_cb[tempcell->index] = idx;
  208. }
  209. /**
  210. * Evaluate if a shift lower the error. If it does, call shift_codebooks
  211. * and update elbg->error, elbg->utility and elbg->nearest_cb.
  212. *
  213. * @param elbg Internal elbg data
  214. * @param idx {luc (low utility cell, huc (high utility cell), cluc (closest cell to low utility cell)}
  215. */
  216. static void try_shift_candidate(elbg_data *elbg, int idx[3])
  217. {
  218. int j, k, olderror=0, newerror, cont=0;
  219. int newutility[3];
  220. int *newcentroid[3] = {
  221. elbg->scratchbuf,
  222. elbg->scratchbuf + elbg->dim,
  223. elbg->scratchbuf + 2*elbg->dim
  224. };
  225. cell *tempcell;
  226. for (j=0; j<3; j++)
  227. olderror += elbg->utility[idx[j]];
  228. memset(newcentroid[2], 0, elbg->dim*sizeof(int));
  229. for (k=0; k<2; k++)
  230. for (tempcell=elbg->cells[idx[2*k]]; tempcell; tempcell=tempcell->next) {
  231. cont++;
  232. for (j=0; j<elbg->dim; j++)
  233. newcentroid[2][j] += elbg->points[tempcell->index*elbg->dim + j];
  234. }
  235. vect_division(newcentroid[2], newcentroid[2], cont, elbg->dim);
  236. get_new_centroids(elbg, idx[1], newcentroid[0], newcentroid[1]);
  237. newutility[2] = eval_error_cell(elbg, newcentroid[2], elbg->cells[idx[0]]);
  238. newutility[2] += eval_error_cell(elbg, newcentroid[2], elbg->cells[idx[2]]);
  239. newerror = newutility[2];
  240. newerror += simple_lbg(elbg, elbg->dim, newcentroid, newutility, elbg->points,
  241. elbg->cells[idx[1]]);
  242. if (olderror > newerror) {
  243. shift_codebook(elbg, idx, newcentroid);
  244. elbg->error += newerror - olderror;
  245. for (j=0; j<3; j++)
  246. update_utility_and_n_cb(elbg, idx[j], newutility[j]);
  247. evaluate_utility_inc(elbg);
  248. }
  249. }
  250. /**
  251. * Implementation of the ELBG block
  252. */
  253. static void do_shiftings(elbg_data *elbg)
  254. {
  255. int idx[3];
  256. evaluate_utility_inc(elbg);
  257. for (idx[0]=0; idx[0] < elbg->numCB; idx[0]++)
  258. if (elbg->numCB*elbg->utility[idx[0]] < elbg->error) {
  259. if (elbg->utility_inc[elbg->numCB-1] == 0)
  260. return;
  261. idx[1] = get_high_utility_cell(elbg);
  262. idx[2] = get_closest_codebook(elbg, idx[0]);
  263. if (idx[1] != idx[0] && idx[1] != idx[2])
  264. try_shift_candidate(elbg, idx);
  265. }
  266. }
  267. #define BIG_PRIME 433494437LL
  268. int ff_init_elbg(int *points, int dim, int numpoints, int *codebook,
  269. int numCB, int max_steps, int *closest_cb,
  270. AVLFG *rand_state)
  271. {
  272. int i, k, ret = 0;
  273. if (numpoints > 24*numCB) {
  274. /* ELBG is very costly for a big number of points. So if we have a lot
  275. of them, get a good initial codebook to save on iterations */
  276. int *temp_points = av_malloc(dim*(numpoints/8)*sizeof(int));
  277. if (!temp_points)
  278. return AVERROR(ENOMEM);
  279. for (i=0; i<numpoints/8; i++) {
  280. k = (i*BIG_PRIME) % numpoints;
  281. memcpy(temp_points + i*dim, points + k*dim, dim*sizeof(int));
  282. }
  283. ret = ff_init_elbg(temp_points, dim, numpoints / 8, codebook,
  284. numCB, 2 * max_steps, closest_cb, rand_state);
  285. if (ret < 0) {
  286. av_freep(&temp_points);
  287. return ret;
  288. }
  289. ret = ff_do_elbg(temp_points, dim, numpoints / 8, codebook,
  290. numCB, 2 * max_steps, closest_cb, rand_state);
  291. av_free(temp_points);
  292. } else // If not, initialize the codebook with random positions
  293. for (i=0; i < numCB; i++)
  294. memcpy(codebook + i*dim, points + ((i*BIG_PRIME)%numpoints)*dim,
  295. dim*sizeof(int));
  296. return ret;
  297. }
  298. int ff_do_elbg(int *points, int dim, int numpoints, int *codebook,
  299. int numCB, int max_steps, int *closest_cb,
  300. AVLFG *rand_state)
  301. {
  302. int dist;
  303. elbg_data elbg_d;
  304. elbg_data *elbg = &elbg_d;
  305. int i, j, k, last_error, steps = 0, ret = 0;
  306. int *dist_cb = av_malloc(numpoints*sizeof(int));
  307. int *size_part = av_malloc(numCB*sizeof(int));
  308. cell *list_buffer = av_malloc(numpoints*sizeof(cell));
  309. cell *free_cells;
  310. int best_dist, best_idx = 0;
  311. elbg->error = INT_MAX;
  312. elbg->dim = dim;
  313. elbg->numCB = numCB;
  314. elbg->codebook = codebook;
  315. elbg->cells = av_malloc(numCB*sizeof(cell *));
  316. elbg->utility = av_malloc(numCB*sizeof(int));
  317. elbg->nearest_cb = closest_cb;
  318. elbg->points = points;
  319. elbg->utility_inc = av_malloc(numCB*sizeof(int));
  320. elbg->scratchbuf = av_malloc(5*dim*sizeof(int));
  321. if (!dist_cb || !size_part || !list_buffer || !elbg->cells ||
  322. !elbg->utility || !elbg->utility_inc || !elbg->scratchbuf) {
  323. ret = AVERROR(ENOMEM);
  324. goto out;
  325. }
  326. elbg->rand_state = rand_state;
  327. do {
  328. free_cells = list_buffer;
  329. last_error = elbg->error;
  330. steps++;
  331. memset(elbg->utility, 0, numCB*sizeof(int));
  332. memset(elbg->cells, 0, numCB*sizeof(cell *));
  333. elbg->error = 0;
  334. /* This loop evaluate the actual Voronoi partition. It is the most
  335. costly part of the algorithm. */
  336. for (i=0; i < numpoints; i++) {
  337. best_dist = distance_limited(elbg->points + i*elbg->dim, elbg->codebook + best_idx*elbg->dim, dim, INT_MAX);
  338. for (k=0; k < elbg->numCB; k++) {
  339. dist = distance_limited(elbg->points + i*elbg->dim, elbg->codebook + k*elbg->dim, dim, best_dist);
  340. if (dist < best_dist) {
  341. best_dist = dist;
  342. best_idx = k;
  343. }
  344. }
  345. elbg->nearest_cb[i] = best_idx;
  346. dist_cb[i] = best_dist;
  347. elbg->error += dist_cb[i];
  348. elbg->utility[elbg->nearest_cb[i]] += dist_cb[i];
  349. free_cells->index = i;
  350. free_cells->next = elbg->cells[elbg->nearest_cb[i]];
  351. elbg->cells[elbg->nearest_cb[i]] = free_cells;
  352. free_cells++;
  353. }
  354. do_shiftings(elbg);
  355. memset(size_part, 0, numCB*sizeof(int));
  356. memset(elbg->codebook, 0, elbg->numCB*dim*sizeof(int));
  357. for (i=0; i < numpoints; i++) {
  358. size_part[elbg->nearest_cb[i]]++;
  359. for (j=0; j < elbg->dim; j++)
  360. elbg->codebook[elbg->nearest_cb[i]*elbg->dim + j] +=
  361. elbg->points[i*elbg->dim + j];
  362. }
  363. for (i=0; i < elbg->numCB; i++)
  364. vect_division(elbg->codebook + i*elbg->dim,
  365. elbg->codebook + i*elbg->dim, size_part[i], elbg->dim);
  366. } while(((last_error - elbg->error) > DELTA_ERR_MAX*elbg->error) &&
  367. (steps < max_steps));
  368. out:
  369. av_free(dist_cb);
  370. av_free(size_part);
  371. av_free(elbg->utility);
  372. av_free(list_buffer);
  373. av_free(elbg->cells);
  374. av_free(elbg->utility_inc);
  375. av_free(elbg->scratchbuf);
  376. return ret;
  377. }