2 * Copyright (C) 2007 Vitor Sessak <vitor1001@gmail.com>
4 * This file is part of FFmpeg.
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.
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.
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
23 * Codebook Generator using the ELBG algorithm
28 #include "libavutil/avassert.h"
29 #include "libavutil/common.h"
30 #include "libavutil/lfg.h"
33 #define DELTA_ERR_MAX 0.1 ///< Precision of the ELBG algorithm (as percentage error)
36 * In the ELBG jargon, a cell is the set of points that are closest to a
37 * codebook entry. Not to be confused with a RoQ Video cell. */
38 typedef struct cell_s {
46 typedef struct ELBGContext {
62 /* Sizes for the buffers above. Pointers without such a field
63 * are not allocated by us and only valid for the duration
64 * of a single call to avpriv_elbg_do(). */
65 unsigned utility_allocated;
66 unsigned utility_inc_allocated;
67 unsigned size_part_allocated;
68 unsigned cells_allocated;
69 unsigned scratchbuf_allocated;
70 unsigned cell_buffer_allocated;
71 unsigned temp_points_allocated;
74 static inline int distance_limited(int *a, int *b, int dim, int limit)
77 for (i=0; i<dim; i++) {
78 int64_t distance = a[i] - b[i];
81 if (dist >= limit - distance)
89 static inline void vect_division(int *res, int *vect, int div, int dim)
94 res[i] = ROUNDED_DIV(vect[i],div);
96 memcpy(res, vect, dim*sizeof(int));
100 static int eval_error_cell(ELBGContext *elbg, int *centroid, cell *cells)
103 for (; cells; cells=cells->next) {
104 int distance = distance_limited(centroid, elbg->points + cells->index*elbg->dim, elbg->dim, INT_MAX);
105 if (error >= INT_MAX - distance)
113 static int get_closest_codebook(ELBGContext *elbg, int index)
116 for (int i = 0, diff_min = INT_MAX; i < elbg->num_cb; i++)
119 diff = distance_limited(elbg->codebook + i*elbg->dim, elbg->codebook + index*elbg->dim, elbg->dim, diff_min);
120 if (diff < diff_min) {
128 static int get_high_utility_cell(ELBGContext *elbg)
131 /* Using linear search, do binary if it ever turns to be speed critical */
134 if (elbg->utility_inc[elbg->num_cb - 1] < INT_MAX) {
135 r = av_lfg_get(elbg->rand_state) % (unsigned int)elbg->utility_inc[elbg->num_cb - 1] + 1;
137 r = av_lfg_get(elbg->rand_state);
138 r = (av_lfg_get(elbg->rand_state) + (r<<32)) % elbg->utility_inc[elbg->num_cb - 1] + 1;
141 while (elbg->utility_inc[i] < r) {
145 av_assert2(elbg->cells[i]);
151 * Implementation of the simple LBG algorithm for just two codebooks
153 static int simple_lbg(ELBGContext *elbg,
161 int numpoints[2] = {0,0};
162 int *newcentroid[2] = {
163 elbg->scratchbuf + 3*dim,
164 elbg->scratchbuf + 4*dim
168 memset(newcentroid[0], 0, 2 * dim * sizeof(*newcentroid[0]));
173 for (tempcell = cells; tempcell; tempcell=tempcell->next) {
174 idx = distance_limited(centroid[0], points + tempcell->index*dim, dim, INT_MAX)>=
175 distance_limited(centroid[1], points + tempcell->index*dim, dim, INT_MAX);
177 for (i=0; i<dim; i++)
178 newcentroid[idx][i] += points[tempcell->index*dim + i];
181 vect_division(centroid[0], newcentroid[0], numpoints[0], dim);
182 vect_division(centroid[1], newcentroid[1], numpoints[1], dim);
184 for (tempcell = cells; tempcell; tempcell=tempcell->next) {
185 int dist[2] = {distance_limited(centroid[0], points + tempcell->index*dim, dim, INT_MAX),
186 distance_limited(centroid[1], points + tempcell->index*dim, dim, INT_MAX)};
187 int idx = dist[0] > dist[1];
188 if (newutility[idx] >= INT_MAX - dist[idx])
189 newutility[idx] = INT_MAX;
191 newutility[idx] += dist[idx];
194 return (newutility[0] >= INT_MAX - newutility[1]) ? INT_MAX : newutility[0] + newutility[1];
197 static void get_new_centroids(ELBGContext *elbg, int huc, int *newcentroid_i,
201 int *min = newcentroid_i;
202 int *max = newcentroid_p;
205 for (i=0; i< elbg->dim; i++) {
210 for (tempcell = elbg->cells[huc]; tempcell; tempcell = tempcell->next)
211 for(i=0; i<elbg->dim; i++) {
212 min[i]=FFMIN(min[i], elbg->points[tempcell->index*elbg->dim + i]);
213 max[i]=FFMAX(max[i], elbg->points[tempcell->index*elbg->dim + i]);
216 for (i=0; i<elbg->dim; i++) {
217 int ni = min[i] + (max[i] - min[i])/3;
218 int np = min[i] + (2*(max[i] - min[i]))/3;
219 newcentroid_i[i] = ni;
220 newcentroid_p[i] = np;
225 * Add the points in the low utility cell to its closest cell. Split the high
226 * utility cell, putting the separated points in the (now empty) low utility
229 * @param elbg Internal elbg data
230 * @param indexes {luc, huc, cluc}
231 * @param newcentroid A vector with the position of the new centroids
233 static void shift_codebook(ELBGContext *elbg, int *indexes,
237 cell **pp = &elbg->cells[indexes[2]];
242 *pp = elbg->cells[indexes[0]];
244 elbg->cells[indexes[0]] = NULL;
245 tempdata = elbg->cells[indexes[1]];
246 elbg->cells[indexes[1]] = NULL;
249 cell *tempcell2 = tempdata->next;
250 int idx = distance_limited(elbg->points + tempdata->index*elbg->dim,
251 newcentroid[0], elbg->dim, INT_MAX) >
252 distance_limited(elbg->points + tempdata->index*elbg->dim,
253 newcentroid[1], elbg->dim, INT_MAX);
255 tempdata->next = elbg->cells[indexes[idx]];
256 elbg->cells[indexes[idx]] = tempdata;
257 tempdata = tempcell2;
261 static void evaluate_utility_inc(ELBGContext *elbg)
265 for (int i = 0; i < elbg->num_cb; i++) {
266 if (elbg->num_cb * (int64_t)elbg->utility[i] > elbg->error)
267 inc += elbg->utility[i];
268 elbg->utility_inc[i] = FFMIN(inc, INT_MAX);
273 static void update_utility_and_n_cb(ELBGContext *elbg, int idx, int newutility)
277 elbg->utility[idx] = newutility;
278 for (tempcell=elbg->cells[idx]; tempcell; tempcell=tempcell->next)
279 elbg->nearest_cb[tempcell->index] = idx;
283 * Evaluate if a shift lower the error. If it does, call shift_codebooks
284 * and update elbg->error, elbg->utility and elbg->nearest_cb.
286 * @param elbg Internal elbg data
287 * @param idx {luc (low utility cell, huc (high utility cell), cluc (closest cell to low utility cell)}
289 static void try_shift_candidate(ELBGContext *elbg, int idx[3])
291 int j, k, cont=0, tmp;
292 int64_t olderror=0, newerror;
294 int *newcentroid[3] = {
296 elbg->scratchbuf + elbg->dim,
297 elbg->scratchbuf + 2*elbg->dim
302 olderror += elbg->utility[idx[j]];
304 memset(newcentroid[2], 0, elbg->dim*sizeof(int));
307 for (tempcell=elbg->cells[idx[2*k]]; tempcell; tempcell=tempcell->next) {
309 for (j=0; j<elbg->dim; j++)
310 newcentroid[2][j] += elbg->points[tempcell->index*elbg->dim + j];
313 vect_division(newcentroid[2], newcentroid[2], cont, elbg->dim);
315 get_new_centroids(elbg, idx[1], newcentroid[0], newcentroid[1]);
317 newutility[2] = eval_error_cell(elbg, newcentroid[2], elbg->cells[idx[0]]);
318 tmp = eval_error_cell(elbg, newcentroid[2], elbg->cells[idx[2]]);
319 newutility[2] = (tmp >= INT_MAX - newutility[2]) ? INT_MAX : newutility[2] + tmp;
321 newerror = newutility[2];
323 tmp = simple_lbg(elbg, elbg->dim, newcentroid, newutility, elbg->points,
324 elbg->cells[idx[1]]);
325 if (tmp >= INT_MAX - newerror)
330 if (olderror > newerror) {
331 shift_codebook(elbg, idx, newcentroid);
333 elbg->error += newerror - olderror;
336 update_utility_and_n_cb(elbg, idx[j], newutility[j]);
338 evaluate_utility_inc(elbg);
343 * Implementation of the ELBG block
345 static void do_shiftings(ELBGContext *elbg)
349 evaluate_utility_inc(elbg);
351 for (idx[0]=0; idx[0] < elbg->num_cb; idx[0]++)
352 if (elbg->num_cb * (int64_t)elbg->utility[idx[0]] < elbg->error) {
353 if (elbg->utility_inc[elbg->num_cb - 1] == 0)
356 idx[1] = get_high_utility_cell(elbg);
357 idx[2] = get_closest_codebook(elbg, idx[0]);
359 if (idx[1] != idx[0] && idx[1] != idx[2])
360 try_shift_candidate(elbg, idx);
364 static void do_elbg(ELBGContext *av_restrict elbg, int *points, int numpoints,
367 int *const size_part = elbg->size_part;
372 elbg->error = INT_MAX;
373 elbg->points = points;
376 cell *free_cells = elbg->cell_buffer;
377 last_error = elbg->error;
379 memset(elbg->utility, 0, elbg->num_cb * sizeof(*elbg->utility));
380 memset(elbg->cells, 0, elbg->num_cb * sizeof(*elbg->cells));
384 /* This loop evaluate the actual Voronoi partition. It is the most
385 costly part of the algorithm. */
386 for (i=0; i < numpoints; i++) {
387 int best_dist = distance_limited(elbg->points + i * elbg->dim,
388 elbg->codebook + best_idx * elbg->dim,
390 for (int k = 0; k < elbg->num_cb; k++) {
391 int dist = distance_limited(elbg->points + i * elbg->dim,
392 elbg->codebook + k * elbg->dim,
393 elbg->dim, best_dist);
394 if (dist < best_dist) {
399 elbg->nearest_cb[i] = best_idx;
400 elbg->error = (elbg->error >= INT_MAX - best_dist) ? INT_MAX : elbg->error + best_dist;
401 elbg->utility[elbg->nearest_cb[i]] = (elbg->utility[elbg->nearest_cb[i]] >= INT_MAX - best_dist) ?
402 INT_MAX : elbg->utility[elbg->nearest_cb[i]] + best_dist;
403 free_cells->index = i;
404 free_cells->next = elbg->cells[elbg->nearest_cb[i]];
405 elbg->cells[elbg->nearest_cb[i]] = free_cells;
411 memset(size_part, 0, elbg->num_cb * sizeof(*size_part));
413 memset(elbg->codebook, 0, elbg->num_cb * elbg->dim * sizeof(*elbg->codebook));
415 for (i=0; i < numpoints; i++) {
416 size_part[elbg->nearest_cb[i]]++;
417 for (j=0; j < elbg->dim; j++)
418 elbg->codebook[elbg->nearest_cb[i]*elbg->dim + j] +=
419 elbg->points[i*elbg->dim + j];
422 for (int i = 0; i < elbg->num_cb; i++)
423 vect_division(elbg->codebook + i*elbg->dim,
424 elbg->codebook + i*elbg->dim, size_part[i], elbg->dim);
426 } while(((last_error - elbg->error) > DELTA_ERR_MAX*elbg->error) &&
427 (steps < max_steps));
430 #define BIG_PRIME 433494437LL
433 * Initialize the codebook vector for the elbg algorithm.
434 * If numpoints <= 24 * num_cb this function fills codebook with random numbers.
435 * If not, it calls do_elbg for a (smaller) random sample of the points in
438 static void init_elbg(ELBGContext *av_restrict elbg, int *points, int *temp_points,
439 int numpoints, int max_steps)
443 if (numpoints > 24LL * elbg->num_cb) {
444 /* ELBG is very costly for a big number of points. So if we have a lot
445 of them, get a good initial codebook to save on iterations */
446 for (int i = 0; i < numpoints / 8; i++) {
447 int k = (i*BIG_PRIME) % numpoints;
448 memcpy(temp_points + i*dim, points + k*dim, dim * sizeof(*temp_points));
451 /* If anything is changed in the recursion parameters,
452 * the allocated size of temp_points will also need to be updated. */
453 init_elbg(elbg, temp_points, temp_points + numpoints / 8 * dim,
454 numpoints / 8, 2 * max_steps);
455 do_elbg(elbg, temp_points, numpoints / 8, 2 * max_steps);
456 } else // If not, initialize the codebook with random positions
457 for (int i = 0; i < elbg->num_cb; i++)
458 memcpy(elbg->codebook + i * dim, points + ((i*BIG_PRIME)%numpoints)*dim,
459 dim * sizeof(*elbg->codebook));
462 int avpriv_elbg_do(ELBGContext **elbgp, int *points, int dim, int numpoints,
463 int *codebook, int num_cb, int max_steps,
464 int *closest_cb, AVLFG *rand_state, uintptr_t flags)
466 ELBGContext *const av_restrict elbg = *elbgp ? *elbgp : av_mallocz(sizeof(*elbg));
469 return AVERROR(ENOMEM);
472 elbg->nearest_cb = closest_cb;
473 elbg->rand_state = rand_state;
474 elbg->codebook = codebook;
475 elbg->num_cb = num_cb;
478 #define ALLOCATE_IF_NECESSARY(field, new_elements, multiplicator) \
479 if (elbg->field ## _allocated < new_elements) { \
480 av_freep(&elbg->field); \
481 elbg->field = av_malloc_array(new_elements, \
482 multiplicator * sizeof(*elbg->field)); \
483 if (!elbg->field) { \
484 elbg->field ## _allocated = 0; \
485 return AVERROR(ENOMEM); \
487 elbg->field ## _allocated = new_elements; \
489 /* Allocating the buffers for do_elbg() here once relies
490 * on their size being always the same even when do_elbg()
491 * is called from init_elbg(). It also relies on do_elbg()
492 * never calling itself recursively. */
493 ALLOCATE_IF_NECESSARY(cells, num_cb, 1)
494 ALLOCATE_IF_NECESSARY(utility, num_cb, 1)
495 ALLOCATE_IF_NECESSARY(utility_inc, num_cb, 1)
496 ALLOCATE_IF_NECESSARY(size_part, num_cb, 1)
497 ALLOCATE_IF_NECESSARY(cell_buffer, numpoints, 1)
498 ALLOCATE_IF_NECESSARY(scratchbuf, dim, 5)
499 if (numpoints > 24LL * elbg->num_cb) {
500 /* The first step in the recursion in init_elbg() needs a buffer with
501 * (numpoints / 8) * dim elements; the next step needs numpoints / 8 / 8
502 * * dim elements etc. The geometric series leads to an upper bound of
503 * numpoints / 8 * 8 / 7 * dim elements. */
504 uint64_t prod = dim * (uint64_t)(numpoints / 7U);
506 return AVERROR(ERANGE);
507 ALLOCATE_IF_NECESSARY(temp_points, prod, 1)
510 init_elbg(elbg, points, elbg->temp_points, numpoints, max_steps);
511 do_elbg (elbg, points, numpoints, max_steps);
515 av_cold void avpriv_elbg_free(ELBGContext **elbgp)
517 ELBGContext *elbg = *elbgp;
521 av_freep(&elbg->size_part);
522 av_freep(&elbg->utility);
523 av_freep(&elbg->cell_buffer);
524 av_freep(&elbg->cells);
525 av_freep(&elbg->utility_inc);
526 av_freep(&elbg->scratchbuf);
527 av_freep(&elbg->temp_points);