-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdct.c
95 lines (78 loc) · 3.13 KB
/
dct.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define DCT_SIZE 8
#define PI 3.14159265358979323846
void forward_dct(float* block, float* result) {
for (int u = 0; u < DCT_SIZE; u++) {
for (int v = 0; v < DCT_SIZE; v++) {
float sum = 0.0;
for (int x = 0; x < DCT_SIZE; x++) {
for (int y = 0; y < DCT_SIZE; y++) {
sum += block[y * DCT_SIZE + x] *
cosf((2 * x + 1) * u * PI / (2 * DCT_SIZE)) *
cosf((2 * y + 1) * v * PI / (2 * DCT_SIZE));
}
}
float cu = (u == 0) ? 1.0f / sqrtf(2) : 1.0f;
float cv = (v == 0) ? 1.0f / sqrtf(2) : 1.0f;
result[v * DCT_SIZE + u] = 0.25f * cu * cv * sum;
}
}
}
void inverse_dct(float* dct_block, float* result) {
for (int x = 0; x < DCT_SIZE; x++) {
for (int y = 0; y < DCT_SIZE; y++) {
float sum = 0.0;
for (int u = 0; u < DCT_SIZE; u++) {
for (int v = 0; v < DCT_SIZE; v++) {
float cu = (u == 0) ? 1.0f / sqrtf(2) : 1.0f;
float cv = (v == 0) ? 1.0f / sqrtf(2) : 1.0f;
sum += cu * cv * dct_block[v * DCT_SIZE + u] *
cosf((2 * x + 1) * u * PI / (2 * DCT_SIZE)) *
cosf((2 * y + 1) * v * PI / (2 * DCT_SIZE));
}
}
result[y * DCT_SIZE + x] = 0.25f * sum;
}
}
}
const int jpeg_luma_quant[DCT_SIZE * DCT_SIZE] = {
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99
};
const int jpeg_chroma_quant[DCT_SIZE * DCT_SIZE] = {
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
};
void scale_quant_matrix(const int* base_matrix, int* result, int quality) {
if (quality < 1) quality = 1;
if (quality > 100) quality = 100;
int scale = quality < 50 ? 5000 / quality : 200 - quality * 2;
for (int i = 0; i < DCT_SIZE * DCT_SIZE; i++) {
int value = (base_matrix[i] * scale + 50) / 100;
result[i] = (value < 1) ? 1 : ((value > 255) ? 255 : value);
}
}
void quantize_block(float* dct_block, int* quant_matrix, int* result) {
for (int i = 0; i < DCT_SIZE * DCT_SIZE; i++) {
result[i] = (int)roundf(dct_block[i] / quant_matrix[i]);
}
}
void dequantize_block(int* quant_block, int* quant_matrix, float* result) {
for (int i = 0; i < DCT_SIZE * DCT_SIZE; i++) {
result[i] = quant_block[i] * quant_matrix[i];
}
}