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