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.

464 lines
14KB

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