Browse code

Codebook generator using the ELBG algorithm patch by Vitor: printf(vitor%d gmail com, 1001) original thread: Re: [FFmpeg-devel] [PATCH] Add a codebook generator (was: [PATCH] RoQ video encoder, take 2) date: 05/28/2007 01:21 PM

Originally committed as revision 9196 to svn://svn.ffmpeg.org/ffmpeg/trunk

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