Debian Codegraph @

src/filter/curves/curves.c

raw symbols SCIP
1 /* curves.c
2 * Copyright (C) 2009 Maksim Golovkin ([email protected])
3 * Copyright (C) 2010 Till Theato ([email protected])
4 * This file is a Frei0r plugin.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program 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
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #ifndef _GNU_SOURCE
22 #define _GNU_SOURCE
23 #endif
24 #include <stdlib.h>
25 #include <assert.h>
26 #include <math.h>
27 #include <string.h>
28 #include <stdio.h>
29
30 #include "frei0r.h"
31 #include "frei0r/math.h"
32
33 #define MAX3(a, b, c) ( ( a > b && a > c) ? a : (b > c ? b : c) )
34 #define MIN3(a, b, c) ( ( a < b && a < c) ? a : (b < c ? b : c) )
35
36 #define POS_TOP_LEFT 0
37 #define POS_TOP_RIGHT 1
38 #define POS_BOTTOM_LEFT 2
39 #define POS_BOTTOM_RIGHT 3
40
41 #define POINT "Point "
42 #define INPUT_VALUE " input value"
43 #define OUTPUT_VALUE " output value"
44
45 enum CHANNELS { CHANNEL_RED = 0, CHANNEL_GREEN, CHANNEL_BLUE, CHANNEL_ALPHA, CHANNEL_LUMA, CHANNEL_RGB, CHANNEL_HUE, CHANNEL_SATURATION };
46
47 typedef struct position
48 {
49 double x;
50 double y;
51 } position;
52
53 typedef position bspline_point[3]; // [0] = handle1, [1] = point, [2] = handle2
54
55
56 typedef struct curves_instance
57 {
58 unsigned int width;
59 unsigned int height;
60 enum CHANNELS channel;
61 double pointNumber;
62 double points[10];
63 double drawCurves;
64 double curvesPosition;
65 double formula;
66
67 char *bspline;
68 double *bsplineMap;
69 double *csplineMap;
70 float *curveMap;
71 } curves_instance_t;
72
73
74 // color conversion functions taken from:
75 // http://www.cs.rit.edu/~ncs/color/t_convert.html
76 // slightly modified
77
78 // r,g,b values are from 0 to 255
79 // h = [0,360], s = [0,1], v = [0,1]
80 // if s == 0, then h = -1 (undefined)
81 void RGBtoHSV(double r, double g, double b, double *h, double *s, double *v)
82 {
83 double min = MIN3(r, g, b);
84 double max = MAX3(r, g, b);
85 *v = max / 255.;
86
87 double delta = max - min;
88
89 if (delta != 0) {
90 *s = delta / max; // s
91 } else {
92 // r = g = b // s = 0
93 *s = 0;
94 *h = -1;
95 return;
96 }
97
98 if (r == max)
99 *h = (g - b) / delta; // between yellow & magenta
100 else if (g == max)
101 *h = 2 + (b - r) / delta; // between cyan & yellow
102 else
103 *h = 4 + (r - g) / delta; // between magenta & cyan
104
105 *h *= 60; // degrees
106 if (*h < 0)
107 *h += 360;
108 }
109
110 // r,g,b values are from 0 to 1
111 // h = [0,360], s = [0,1], v = [0,1]
112 void HSVtoRGB(double *r, double *g, double *b, double h, double s, double v)
113 {
114 if (s == 0) {
115 // achromatic (grey)
116 *r = *g = *b = v;
117 return;
118 }
119
120 h /= 60; // sector 0 to 5
121 int i = (int)h;
122 double f = h - i; // factorial part of h
123 double p = v * (1 - s);
124
125 if (i & 1) {
126 double q = v * (1 - s * f);
127 switch (i) {
128 case 1:
129 *r = q;
130 *g = v;
131 *b = p;
132 break;
133 case 3:
134 *r = p;
135 *g = q;
136 *b = v;
137 break;
138 case 5:
139 *r = v;
140 *g = p;
141 *b = q;
142 break;
143 }
144 } else {
145 double t = v * (1 - s * (1 - f));
146 switch (i) {
147 case 0:
148 *r = v;
149 *g = t;
150 *b = p;
151 break;
152 case 2:
153 *r = p;
154 *g = v;
155 *b = t;
156 break;
157 case 4:
158 *r = t;
159 *g = p;
160 *b = v;
161 break;
162 }
163 }
164 }
165
166 void updateBsplineMap(f0r_instance_t instance);
167 void updateCsplineMap(f0r_instance_t instance);
168
169 char **param_names = NULL;
170 int f0r_init()
171 {
172 param_names = (char**)calloc(10, sizeof(char *));
173 for(int i = 0; i < 10; i++) {
174 char *val = i % 2 == 0?INPUT_VALUE:OUTPUT_VALUE;
175 param_names[i] = (char*)calloc(strlen(POINT) + 2 + strlen(val), sizeof(char));
176 sprintf(param_names[i], "%s%d%s", POINT, i / 2 + 1, val);
177 }
178 return 1;
179 }
180
181 void f0r_deinit()
182 {
183 for(int i = 0; i < 10; i++)
184 free(param_names[i]);
185 free(param_names);
186 }
187
188 void f0r_get_plugin_info(f0r_plugin_info_t* curves_info)
189 {
190 curves_info->name = "Curves";
191 curves_info->author = "Maksim Golovkin, Till Theato";
192 curves_info->plugin_type = F0R_PLUGIN_TYPE_FILTER;
193 curves_info->color_model = F0R_COLOR_MODEL_RGBA8888;
194 curves_info->frei0r_version = FREI0R_MAJOR_VERSION;
195 curves_info->major_version = 0;
196 curves_info->minor_version = 4;
197 curves_info->num_params = 16;
198 curves_info->explanation = "Adjust luminance or color channel intensity with curve level mapping";
199 }
200
201 char *get_param_name(int param_index) {
202 return param_names[param_index];
203 }
204
205 void f0r_get_param_info(f0r_param_info_t* info, int param_index)
206 {
207 switch(param_index)
208 {
209 case 0:
210 info->name = "Channel";
211 info->type = F0R_PARAM_DOUBLE;
212 info->explanation = "Channel to adjust (0 = red, 0.1 = green, 0.2 = blue, 0.3 = alpha, 0.4 = luma, 0.5 = rgb, 0.6 = hue, 0.7 = saturation)";
213 break;
214 case 1:
215 info->name = "Show curves";
216 info->type = F0R_PARAM_BOOL;
217 info->explanation = "Draw curve graph on output image";
218 break;
219 case 2:
220 info->name = "Graph position";
221 info->type = F0R_PARAM_DOUBLE;
222 info->explanation = "Output image corner where curve graph will be drawn (0.1 = TOP,LEFT; 0.2 = TOP,RIGHT; 0.3 = BOTTOM,LEFT; 0.4 = BOTTOM, RIGHT)";
223 break;
224 case 3:
225 info->name = "Curve point number";
226 info->type = F0R_PARAM_DOUBLE;
227 info->explanation = "Number of points to use to build curve (/10 to fit [0,1] parameter range). Minimum 2 (0.2), Maximum 5 (0.5). Not relevant for Bézier spline.";
228 break;
229 case 4:
230 info->name = "Luma formula";
231 info->type = F0R_PARAM_BOOL;
232 info->explanation = "Use Rec. 601 (false) or Rec. 709 (true)";
233 break;
234 case 5:
235 info->name = "Bézier spline";
236 info->type = F0R_PARAM_STRING;
237 info->explanation = "Use cubic Bézier spline. Has to be a sorted list of points in the format 'handle1x;handle1y#pointx;pointy#handle2x;handle2y'(pointx = in, pointy = out). Points are separated by a '|'.The values can have 'double' precision. x, y for points should be in the range 0-1. x,y for handles might also be out of this range.";
238 default:
239 if (param_index > 5) {
240 info->name = get_param_name(param_index - 6);
241 info->type = F0R_PARAM_DOUBLE;
242 info->explanation = get_param_name(param_index - 6);
243 }
244 break;
245 }
246 }
247
248 f0r_instance_t f0r_construct(unsigned int width, unsigned int height)
249 {
250 curves_instance_t* inst = (curves_instance_t*)calloc(1, sizeof(*inst));
251 inst->width = width; inst->height = height;
252 inst->channel = CHANNEL_RGB;
253 inst->drawCurves = 1;
254 inst->curvesPosition = 3;
255 inst->pointNumber = 2;
256 inst->formula = 1;
257 inst->bspline = calloc(1, sizeof(char));
258 inst->bsplineMap = NULL;
259 inst->csplineMap = NULL;
260 inst->curveMap = NULL;
261 inst->points[0] = 0;
262 inst->points[1] = 0;
263 inst->points[2] = 1;
264 inst->points[3] = 1;
265 inst->points[4] = 0;
266 inst->points[5] = 0;
267 inst->points[6] = 0;
268 inst->points[7] = 0;
269 inst->points[8] = 0;
270 inst->points[9] = 0;
271 return (f0r_instance_t)inst;
272 }
273
274 void f0r_destruct(f0r_instance_t instance)
275 {
276 curves_instance_t* inst = (curves_instance_t*)instance;
277 free(inst->bspline);
278 free(inst->bsplineMap);
279 free(inst->csplineMap);
280 free(inst->curveMap);
281 free(inst);
282 }
283
284 void f0r_set_param_value(f0r_instance_t instance,
285 f0r_param_t param, int param_index)
286 {
287 assert(instance);
288 curves_instance_t* inst = (curves_instance_t*)instance;
289
290 double tmp;
291 f0r_param_string bspline;
292
293 switch(param_index)
294 {
295 case 0:
296 tmp = *((f0r_param_double *)param);
297 if (tmp >= 1) {
298 // legacy support
299 if (tmp == 3) {
300 if (inst->channel != CHANNEL_LUMA) {
301 inst->channel = CHANNEL_LUMA;
302 if (strlen(inst->bspline))
303 updateBsplineMap(instance);
304 else
305 updateCsplineMap(instance);
306 }
307 } else {
308 if ((int)inst->channel != (int)tmp) {
309 inst->channel = (enum CHANNELS)((int)tmp);
310 if (strlen(inst->bspline))
311 updateBsplineMap(instance);
312 else
313 updateCsplineMap(instance);
314 }
315 }
316 } else {
317 if ((int)inst->channel != (int)(tmp * 10)) {
318 inst->channel = (enum CHANNELS)(tmp * 10);
319 if (strlen(inst->bspline))
320 updateBsplineMap(instance);
321 else
322 updateCsplineMap(instance);
323 }
324 }
325 break;
326 case 1:
327 inst->drawCurves = *((f0r_param_double *)param);
328 break;
329 case 2:
330 inst->curvesPosition = floor(*((f0r_param_double *)param) * 10);
331 break;
332 case 3:
333 inst->pointNumber = floor(*((f0r_param_double *)param) * 10);
334 inst->pointNumber = MIN(inst->pointNumber, 5);
335 break;
336 case 4:
337 inst->formula = *((f0r_param_double *)param);
338 break;
339 case 5:
340 bspline = *((f0r_param_string *)param);
341 if (strcmp(inst->bspline, bspline) != 0) {
342 free(inst->bspline);
343 inst->bspline = strdup(bspline);
344 updateBsplineMap(instance);
345 }
346 break;
347 default:
348 if (param_index > 5){
349 inst->points[param_index - 6] = *((f0r_param_double *)param); //Assigning value to curve point
350 updateCsplineMap(instance);
351 }
352
353 break;
354 }
355 }
356
357 void f0r_get_param_value(f0r_instance_t instance,
358 f0r_param_t param, int param_index)
359 {
360 assert(instance);
361 curves_instance_t* inst = (curves_instance_t*)instance;
362
363 switch(param_index)
364 {
365 case 0:
366 *((f0r_param_double *)param) = inst->channel / 10.;
367 break;
368 case 1:
369 *((f0r_param_double *)param) = inst->drawCurves;
370 break;
371 case 2:
372 *((f0r_param_double *)param) = inst->curvesPosition / 10.;
373 break;
374 case 3:
375 *((f0r_param_double *)param) = inst->pointNumber / 10.;
376 break;
377 case 4:
378 *((f0r_param_double *)param) = inst->formula;
379 break;
380 case 5:
381 *((f0r_param_string *)param) = inst->bspline;
382 break;
383 default:
384 if (param_index > 5)
385 *((f0r_param_double *)param) = inst->points[param_index - 6]; //Fetch curve point value
386 break;
387 }
388 }
389
390 double* gaussSLESolve(size_t size, double* A) {
391 int extSize = size + 1;
392 //direct way: transform matrix A to triangular form
393 for(int row = 0; row < size; row++) {
394 int col = row;
395 int lastRowToSwap = size - 1;
396 while (A[row * extSize + col] == 0 && lastRowToSwap > row) { //checking if current and lower rows can be swapped
397 for(int i = 0; i < extSize; i++) {
398 double tmp = A[row * extSize + i];
399 A[row * extSize + i] = A[lastRowToSwap * extSize + i];
400 A[lastRowToSwap * extSize + i] = tmp;
401 }
402 lastRowToSwap--;
403 }
404 double coeff = A[row * extSize + col];
405 for(int j = 0; j < extSize; j++)
406 A[row * extSize + j] /= coeff;
407 if (lastRowToSwap > row) {
408 for(int i = row + 1; i < size; i++) {
409 double rowCoeff = -A[i * extSize + col];
410 for(int j = col; j < extSize; j++)
411 A[i * extSize + j] += A[row * extSize + j] * rowCoeff;
412 }
413 }
414 }
415 //backward way: find solution from last to first
416 double *solution = (double*)calloc(size, sizeof(double));
417 for(int i = size - 1; i >= 0; i--) {
418 solution[i] = A[i * extSize + size];//
419 for(int j = size - 1; j > i; j--) {
420 solution[i] -= solution[j] * A[i * extSize + j];
421 }
422 }
423 return solution;
424 }
425
426
427
428 double* calcSplineCoeffs(double* points, size_t pointsSize) {
429 double* coeffs = NULL;
430 int size = pointsSize;
431 int mxSize = size > 3?4:size;
432 int extMxSize = mxSize + 1;
433 if (size == 2) { //coefficients of linear function Ax + B = y
434 double *m = (double*)calloc(mxSize * extMxSize, sizeof(double));
435 for(int i = 0; i < size; i++) {
436 int offset = i * 2;
437 m[i * extMxSize] = points[offset];
438 m[i * extMxSize + 1] = 1;
439 m[i * extMxSize + 2] = points[offset + 1];
440 }
441 coeffs = gaussSLESolve(size, m);
442 free(m);
443 } else if (size == 3) { //coefficients of quadrant function Ax^2 + Bx + C = y
444 double *m = (double*)calloc(mxSize * extMxSize, sizeof(double));
445 for(int i = 0; i < size; i++) {
446 int offset = i * 2;
447 m[i * extMxSize] = points[offset]*points[offset];
448 m[i * extMxSize + 1] = points[offset];
449 m[i * extMxSize + 2] = 1;
450 m[i * extMxSize + 3] = points[offset + 1];
451 }
452 coeffs = gaussSLESolve(size, m);
453 free(m);
454 } else if (size > 3) { //coefficients of cubic spline Ax^3 + Bx^2 + Cx + D = y
455 coeffs = (double*)calloc(5 * size,sizeof(double));
456 for(int i = 0; i < size; i++) {
457 int offset = i * 5;
458 int srcOffset = i * 2;
459 coeffs[offset] = points[srcOffset];
460 coeffs[offset + 1] = points[srcOffset + 1];
461 }
462 coeffs[3] = coeffs[(size - 1) * 5 + 3] = 0;
463 double *alpha = (double*)calloc(size - 1,sizeof(double));
464 double *beta = (double*)calloc(size - 1,sizeof(double));
465 alpha[0] = beta[0] = 0;
466 for(int i = 1; i < size - 1; i++) {
467 int srcI = i * 2;
468 int srcI_1 = (i - 1) * 2;
469 int srcI1 = (i + 1) * 2;
470 double h_i = points[srcI] - points[srcI_1],
471 h_i1 = points[srcI1] - points[srcI];
472 double A = h_i;
473 double C = 2. * (h_i + h_i1);
474 double B = h_i1;
475 double F = 6. * ((points[srcI1 + 1] - points[srcI + 1]) / h_i1 - (points[srcI + 1] - points[srcI_1 + 1]) / h_i);
476 double z = (A * alpha[i - 1] + C);
477 alpha[i] = -B / z;
478 beta[i] = (F - A * beta[i - 1]) / z;
479 }
480 for (int i = size - 2; i > 0; --i)
481 coeffs[i * 5 + 3] = alpha[i] * coeffs[(i + 1) * 5 + 3] + beta[i];
482 free(beta);
483 free(alpha);
484
485 for (int i = size - 1; i > 0; --i){
486 int srcI = i * 2;
487 int srcI_1 = (i - 1) * 2;
488 double h_i = points[srcI] - points[srcI_1];
489 int offset = i * 5;
490 coeffs[offset + 4] = (coeffs[offset + 3] - coeffs[offset - 2]) / h_i;
491 coeffs[offset + 2] = h_i * (2. * coeffs[offset + 3] + coeffs[offset - 2]) / 6. + (points[srcI + 1] - points[srcI_1 + 1]) / h_i;
492 }
493 }
494 return coeffs;
495 }
496
497 double spline(double x, double* points, size_t pointSize, double* coeffs) {
498 int size = pointSize;
499 if (size == 2) {
500 return coeffs[0] * x + coeffs[1];
501 } else if (size == 3) {
502 return (coeffs[0] * x + coeffs[1]) * x + coeffs[2];
503 } else if (size > 3) {
504 int offset = 5;
505 if (x <= points[0]) //find valid interval of cubic spline
506 offset = 1;
507 else if (x >= points[(size - 1) * 2])
508 offset = size - 1;
509 else {
510 int i = 0, j = size - 1;
511 while (i + 1 < j) {
512 int k = i + (j - i) / 2;
513 if (x <= points[k * 2])
514 j = k;
515 else
516 i = k;
517 }
518 offset = j;
519 }
520 offset *= 5;
521 double dx = x - coeffs[offset];
522 return ((coeffs[offset + 4] * dx / 6. + coeffs[offset + 3] / 2.) * dx + coeffs[offset + 2]) * dx + coeffs[offset + 1];
523 }
524 /* This should never be reached, statement passifies the compiler*/
525 return -1.0;
526 }
527
528 void swap(double *points, int i, int j) {
529 int offsetX = i * 2, offsetY = j * 2;
530 double tempX = points[offsetX], tempY = points[offsetX + 1];
531 points[offsetX] = points[offsetY];
532 points[offsetX + 1] = points[offsetY + 1];
533 points[offsetY] = tempX;
534 points[offsetY + 1] = tempY;
535 }
536
537
538 /**
539 * Calculates a x,y pair for \param t on the cubic Bézier curve defined by \param points.
540 * \param t "time" in the range 0-1
541 * \param points points[0] = point1, point[1] = handle1, point[2] = handle2, point[3] = point2
542 */
543 position pointOnBezier(double t, position points[4])
544 {
545 position pos;
546
547 /*
548 * Calculating a point on the bezier curve using the coefficients from Bernstein basis polynomial of degree 3.
549 * Using the De Casteljau algorithm would be slightly faster when calculating a lot of values
550 * but the difference is far from noticeable here since we update the spline only when the parameter changes
551 */
552 double c1 = (1-t) * (1-t) * (1-t);
553 double c2 = 3 * t * (1-t) * (1-t);
554 double c3 = 3 * t * t * (1-t);
555 double c4 = t * t * t;
556 pos.x = points[0].x*c1 + points[1].x*c2 + points[2].x*c3 + points[3].x*c4;
557 pos.y = points[0].y*c1 + points[1].y*c2 + points[2].y*c3 + points[3].y*c4;
558 return pos;
559 }
560
561 #if defined(_WIN32) || defined(_WIN64)
562 # define strtok_r strtok_s
563 #endif
564
565 /**
566 * Splits given string into sub-strings at given delimiter.
567 * \param string input string
568 * \param delimiter delimiter
569 * \param tokens pointer to array of strings, will be filled with sub-strings
570 * \return Number of sub-strings
571 */
572 int tokenise(char *string, const char *delimiter, char ***tokens)
573 {
574 int count = 0;
575 char *input = strdup(string);
576 char *result = NULL;
577 char *saveptr;
578 result = strtok_r(input, delimiter, &saveptr);
579 while (result != NULL) {
580 *tokens = realloc(*tokens, (count + 1) * sizeof(char *));
581 (*tokens)[count++] = strdup(result);
582 result = strtok_r(NULL, delimiter, &saveptr);
583 }
584 free(input);
585 return count;
586 }
587
588 /**
589 * Updates the color map according to the bézier spline described in the "Bézier spline" parameter.
590 */
591 void updateBsplineMap(f0r_instance_t instance)
592 {
593 assert(instance);
594 curves_instance_t* inst = (curves_instance_t*)instance;
595
596 int range = inst->channel == CHANNEL_HUE ? 361 : 256;
597 free(inst->bsplineMap);
598 inst->bsplineMap = malloc(range * sizeof(double));
599 // fill with default values, in case the spline does not cover the whole range
600 if (inst->channel == CHANNEL_HUE) {
601 for(int i = 0; i < 361; ++i)
602 inst->bsplineMap[i] = i;
603 } else if (inst->channel == CHANNEL_LUMA || inst->channel == CHANNEL_SATURATION) {
604 for(int i = 0; i < 256; ++i)
605 inst->bsplineMap[i] = inst->channel == CHANNEL_LUMA ? 1 : i / 255.;
606 } else {
607 for(int i = 0; i < 256; ++i)
608 inst->bsplineMap[i] = i;
609 }
610
611 /*
612 * string -> list of points
613 */
614 char **pointStr = calloc(1, sizeof(char *));
615 int count = tokenise(inst->bspline, "|", &pointStr);
616
617 bspline_point *points = (bspline_point *) malloc(count * sizeof(bspline_point));
618
619 for (int i = 0; i < count; ++i) {
620 char **positionsStr = calloc(1, sizeof(char *));
621 int positionsNum = tokenise(pointStr[i], "#", &positionsStr);
622 if (positionsNum == 3) { // h1, p, h2
623 for (int j = 0; j < positionsNum; ++j) {
624 char **coords = calloc(1, sizeof(char *));
625 int coordsNum = tokenise(positionsStr[j], ";", &coords);
626 if (coordsNum == 2) { // x, y
627 points[i][j].x = atof(coords[0]);
628 points[i][j].y = atof(coords[1]);
629 }
630 for (int k = 0; k < coordsNum; ++k)
631 free(coords[k]);
632 free(coords);
633 }
634 }
635 for(int j = 0; j < positionsNum; ++j)
636 free(positionsStr[j]);
637 free(positionsStr);
638 }
639
640 for (int i = 0; i < count; ++i)
641 free(pointStr[i]);
642 free(pointStr);
643
644 /*
645 * Actual work: calculate curves between points and fill map
646 */
647 position p[4];
648 double t, step, diff, y;
649 int pn, c, k;
650 for (int i = 0; i < count - 1; ++i) {
651 p[0] = points[i][1];
652 p[1] = points[i][2];
653 p[2] = points[i+1][0];
654 p[3] = points[i+1][1];
655
656 // make sure points are in correct order
657 if (p[0].x > p[3].x)
658 continue;
659
660 // try to avoid loops and other cases of one x having multiple y
661 p[1].x = CLAMP(p[1].x, p[0].x, p[3].x);
662 p[2].x = CLAMP(p[2].x, p[0].x, p[3].x);
663
664 t = 0;
665 pn = 0;
666 // number of points calculated for this curve
667 // x range * 10 should give enough points
668 c = (int)((p[3].x - p[0].x) * range * 10);
669 if (c == 0) {
670 // points have same x value -> will result in a jump in the curve
671 // calculate anyways, in case we only have these two points (with more points this x value will be calculated three times)
672 c = 1;
673 }
674 step = 1 / (double)c;
675 position *curve = (position *) malloc((c + 1) * sizeof(position));
676 while (t <= 1) {
677 curve[pn++] = pointOnBezier(t, p);
678 t += step;
679 }
680
681 // Fill the map in range this curve provides
682 k = 0;
683 // connection points will be written twice (but therefore no special case for the last point is required)
684 for (int j = (int)(p[0].x * (range-1)); j <= (int)(p[3].x * (range-1)); ++j) {
685 if (k > 0)
686 --k;
687 diff = fabs(j / ((double)(range-1)) - curve[k].x);
688 y = curve[k].y;
689 // Find point closest to the one needed (integers 0 - range)
690 while (++k < pn) {
691 if (fabs(j / ((double)(range-1)) - curve[k].x) > diff)
692 break;
693 diff = fabs(j / ((double)(range-1)) - curve[k].x);
694 y = curve[k++].y;
695 }
696
697 if (inst->channel == CHANNEL_HUE)
698 inst->bsplineMap[j] = CLAMP(y * 360, 0, 360);
699 else if (inst->channel == CHANNEL_LUMA)
700 inst->bsplineMap[j] = y / (j == 0 ? 1 : j / 255.);
701 else if (inst->channel == CHANNEL_SATURATION)
702 inst->bsplineMap[j] = CLAMP(y, 0, 1);
703 else
704 inst->bsplineMap[j] = CLAMP0255(ROUND(y * 255));
705 }
706
707 free(curve);
708 }
709
710 free(points);
711 }
712
713 /**
714 * Updates the color map according to the cubic spline described in the "Curve Point" parameter.
715 */
716 void updateCsplineMap(f0r_instance_t instance)
717 {
718 assert(instance);
719 curves_instance_t* inst = (curves_instance_t*)instance;
720
721 int range = inst->channel == CHANNEL_HUE ? 361 : 256;
722 free(inst->csplineMap);
723 inst->csplineMap = malloc(range * sizeof(double));
724 // fill with default values, in case the spline does not cover the whole range
725 if (inst->channel == CHANNEL_HUE) {
726 for(int i = 0; i < 361; ++i)
727 inst->csplineMap[i] = i;
728 } else if (inst->channel == CHANNEL_LUMA || inst->channel == CHANNEL_SATURATION) {
729 for(int i = 0; i < 256; ++i)
730 inst->csplineMap[i] = inst->channel == CHANNEL_LUMA ? 1 : i / 255.;
731 } else {
732 for(int i = 0; i < 256; ++i)
733 inst->csplineMap[i] = i;
734 }
735
736 /*
737 * Retrieve points
738 */
739 double *points = (double*)calloc(inst->pointNumber * 2, sizeof(double));
740 int i = inst->pointNumber * 2;
741 //copy point values
742 while(--i >= 0)
743 points[i] = inst->points[i];
744 //sort point values by X component
745 for(i = 1; i < inst->pointNumber; i++)
746 for(int j = i; j > 0 && points[j * 2] < points[(j - 1) * 2]; j--)
747 swap(points, j, j - 1);
748 //calculating spline coeffincients
749 double *coeffs = calcSplineCoeffs(points, (size_t)inst->pointNumber);
750
751 /*
752 * Actual work: calculate curves between points and fill map
753 */
754 for(int j = 0; j < range; j++) {
755 double x = j / (double)(range - 1);
756 double y = spline(x, points, (size_t)inst->pointNumber, coeffs);
757 if (inst->channel == CHANNEL_HUE)
758 inst->csplineMap[j] = CLAMP(y * 360, 0, 360);
759 else if (inst->channel == CHANNEL_LUMA)
760 inst->csplineMap[j] = y / (j == 0 ? 1 : j / 255.);
761 else if (inst->channel == CHANNEL_SATURATION)
762 inst->csplineMap[j] = CLAMP(y, 0, 1);
763 else
764 inst->csplineMap[j] = CLAMP0255(ROUND(y * 255));
765 }
766 if (inst->drawCurves) {
767 int scale = inst->height / 2;
768 free(inst->curveMap);
769 inst->curveMap = malloc(scale * sizeof(float));
770 for(i = 0; i < scale; i++)
771 inst->curveMap[i] = spline((double)i / scale, points, (size_t)inst->pointNumber, coeffs) * scale;
772 }
773
774 free(coeffs);
775 free(points);
776 }
777
778 void f0r_update(f0r_instance_t instance, double time,
779 const uint32_t* inframe, uint32_t* outframe)
780 {
781 assert(instance);
782 curves_instance_t* inst = (curves_instance_t*)instance;
783 unsigned int len = inst->width * inst->height;
784
785 // test initialization c/b spline
786 double *splinemap = strlen(inst->bspline)>0 ? inst->bsplineMap : inst->csplineMap;
787 if(!splinemap) {
788 memcpy(outframe,inframe,inst->width * inst->height * 4);
789 return;
790 }
791
792 unsigned char* dst = (unsigned char*)outframe;
793 const unsigned char* src = (unsigned char*)inframe;
794
795 int i = 0;
796 double *map = NULL;
797 int scale = inst->height / 2;
798 double *points = NULL;
799 if (strlen(inst->bspline) == 0) {
800 points = (double*)calloc(inst->pointNumber * 2, sizeof(double));
801 i = inst->pointNumber * 2;
802 //copy point values
803 while(--i >= 0)
804 points[i] = inst->points[i];
805 //sort point values by X component
806 for(i = 1; i < inst->pointNumber; i++)
807 for(int j = i; j > 0 && points[j * 2] < points[(j - 1) * 2]; j--)
808 swap(points, j, j - 1);
809
810 map = inst->csplineMap;
811 } else {
812 map = inst->bsplineMap;
813 }
814
815 int r, g, b, luma;
816 double factorR, factorG, factorB, lumaValue;
817 double rf, gf, bf, hue, sat, val;
818
819 switch ((int)inst->channel) {
820 case CHANNEL_RGB:
821 while (len--) {
822 *dst++ = map[*src++]; // r
823 *dst++ = map[*src++]; // g
824 *dst++ = map[*src++]; // b
825 *dst++ = *src++; // a
826 }
827 break;
828 case CHANNEL_RED:
829 memcpy(outframe, inframe, len*sizeof(uint32_t));
830 while (len--) {
831 *dst = map[*dst];
832 dst += 4;
833 }
834 break;
835 case CHANNEL_GREEN:
836 memcpy(outframe, inframe, len*sizeof(uint32_t));
837 dst += 1;
838 while (len--) {
839 *dst = map[*dst];
840 dst += 4;
841 }
842 break;
843 case CHANNEL_BLUE:
844 memcpy(outframe, inframe, len*sizeof(uint32_t));
845 dst += 2;
846 while (len--) {
847 *dst = map[*dst];
848 dst += 4;
849 }
850 break;
851 case CHANNEL_ALPHA:
852 memcpy(outframe, inframe, len*sizeof(uint32_t));
853 dst += 3;
854 while (len--) {
855 *dst = map[*dst];
856 dst += 4;
857 }
858 break;
859 case CHANNEL_LUMA:
860 if (inst->formula) { // Rec.709
861 factorR = .2126;
862 factorG = .7152;
863 factorB = .0722;
864 } else { // Rec. 601
865 factorR = .299;
866 factorG = .587;
867 factorB = .114;
868 }
869 while (len--) {
870 r = *src++;
871 g = *src++;
872 b = *src++;
873 luma = ROUND(factorR * r + factorG * g + factorB * b);
874 lumaValue = map[luma];
875 if (luma == 0) {
876 *dst++ = lumaValue;
877 *dst++ = lumaValue;
878 *dst++ = lumaValue;
879 } else {
880 *dst++ = CLAMP0255((int)(r * lumaValue));
881 *dst++ = CLAMP0255((int)(g * lumaValue));
882 *dst++ = CLAMP0255((int)(b * lumaValue));
883 }
884 *dst++ = *src++;
885 }
886 break;
887 case CHANNEL_HUE:
888 while (len--) {
889 rf = *src++;
890 gf = *src++;
891 bf = *src++;
892 RGBtoHSV(rf, gf, bf, &hue, &sat, &val);
893 if (hue != -1) {
894 HSVtoRGB(&rf, &gf, &bf, map[(int)hue], sat, val);
895 *dst++ = rf * 255;
896 *dst++ = gf * 255;
897 *dst++ = bf * 255;
898 } else {
899 *dst++ = rf;
900 *dst++ = gf;
901 *dst++ = bf;
902 }
903 *dst++ = *src++;
904 }
905 break;
906 case CHANNEL_SATURATION:
907 while (len--) {
908 rf = *src++;
909 gf = *src++;
910 bf = *src++;
911 RGBtoHSV(rf, gf, bf, &hue, &sat, &val);
912 HSVtoRGB(&rf, &gf, &bf, hue, map[(int)(sat * 255)], val);
913 *dst++ = rf * 255;
914 *dst++ = gf * 255;
915 *dst++ = bf * 255;
916 *dst++ = *src++;
917 }
918 }
919
920
921 if (inst->drawCurves && !strlen(inst->bspline)) {
922 unsigned char color[] = {0, 0, 0};
923 if (inst->channel == CHANNEL_RED || inst->channel == CHANNEL_GREEN || inst->channel == CHANNEL_BLUE)
924 color[(int)inst->channel] = 255;
925 //calculating graph offset by given position values
926 int graphXOffset = inst->curvesPosition == POS_TOP_LEFT || inst->curvesPosition == POS_BOTTOM_LEFT?0:inst->width - scale;
927 int graphYOffset = inst->curvesPosition == POS_TOP_LEFT || inst->curvesPosition == POS_TOP_RIGHT?0:inst->height - scale;
928 int maxYvalue = scale - 1;
929 int stride = inst->width;
930 dst = (unsigned char*)outframe;
931 float lineWidth = scale / 254.;
932 int cellSize = floor(lineWidth * 32);
933 //filling up background and drawing grid
934 for(i = 0; i < scale; i++) {
935 if (i % cellSize > lineWidth) //point doesn't aly on the grid
936 for(int j = 0; j < scale; j++) {
937 if (j % cellSize > lineWidth) { //point doesn't aly on the grid
938 int offset = ((maxYvalue - i + graphYOffset) * stride + j + graphXOffset) * 4;
939 dst[offset] = (dst[offset] >> 1) + 0x7F;
940 offset++;
941 dst[offset] = (dst[offset] >> 1) + 0x7F;
942 offset++;
943 dst[offset] = (dst[offset] >> 1) + 0x7F;
944 offset++;
945 }
946 }
947 }
948 float doubleLineWidth = 4 * lineWidth;
949 //drawing points on the graph
950 for(i = 0; i < inst->pointNumber; i++) {
951 int pointOffset = i * 2;
952 int xPoint = points[pointOffset++] * maxYvalue;
953 int yPoint = points[pointOffset] * maxYvalue;
954 for(int x = (int)floor(xPoint - doubleLineWidth); x <= xPoint + doubleLineWidth; x++) {
955 if (x >= 0 && x < scale) {
956 for(int y = (int)floor(yPoint - doubleLineWidth); y <= yPoint + doubleLineWidth; y++) {
957 if (y >= 0 && y < scale) {
958 int offset = ((maxYvalue - y + graphYOffset) * stride + x + graphXOffset) * 4;
959 dst[offset++] = color[0];
960 dst[offset++] = color[1];
961 dst[offset++] = color[2];
962 }
963 }
964 }
965 }
966 }
967 free(points);
968 //drawing curve on the graph
969 float halfLineWidth = lineWidth * .5;
970 float prevY = 0;
971 for(int j = 0; j < scale; j++) {
972 float y = inst->curveMap[j];
973 if (j == 0 || y == prevY) {
974 for(i = (int)floor(y - halfLineWidth); i <= ceil(y + halfLineWidth); i++) {
975 int clampedI = i < 0?0:i >= scale?scale - 1:i;
976 int offset = ((maxYvalue - clampedI + graphYOffset) * stride + j + graphXOffset) * 4;
977 dst[offset++] = color[0];
978 dst[offset++] = color[1];
979 dst[offset++] = color[2];
980 }
981 } else {
982 int factor = prevY > y?-1:1;
983 float gap = halfLineWidth * factor;
984 //medium value between previous value and current value
985 float mid = (y - prevY) * .5 + prevY;
986 //drawing line from previous value to mid point
987 for(i = ROUND(prevY - gap); factor * i < factor * (mid + gap); i += factor) {
988 int clampedI = i < 0?0:i >= scale?scale - 1:i;
989 int offset = ((maxYvalue - clampedI + graphYOffset) * stride + j - 1 + graphXOffset) * 4;
990 dst[offset++] = color[0];
991 dst[offset++] = color[1];
992 dst[offset++] = color[2];
993 }
994 //drawing line from mid point to current value
995 for(i = ROUND(mid - gap); factor * i < factor * ceil(y + gap); i += factor) {
996 int clampedI = i < 0?0:i >= scale?scale - 1:i;
997 int offset = ((maxYvalue - clampedI + graphYOffset) * stride + j + graphXOffset) * 4;
998 dst[offset++] = color[0];
999 dst[offset++] = color[1];
1000 dst[offset++] = color[2];
1001 }
1002 }
1003 prevY = y;
1004 }
1005 }
1006 }