3 * Copyright (c) 2009 Peter Ross <pross@xvid.org>
4 * Copyright (c) 2010 Alex Converse <alex.converse@gmail.com>
5 * Copyright (c) 2010 Vitor Sessak
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25 * @file libavcodec/dct.c
26 * (Inverse) Discrete Cosine Transforms. These are also known as the
27 * type II and type III DCTs respectively.
31 #include "libavutil/mathematics.h"
34 av_cold int ff_dct_init(DCTContext *s, int nbits, int inverse)
42 ff_init_ff_cos_tabs(nbits+2);
44 s->costab = ff_cos_tabs[nbits+2];
46 s->csc2 = av_malloc(n/2 * sizeof(FFTSample));
48 if (ff_rdft_init(&s->rdft, nbits, inverse) < 0) {
53 for (i = 0; i < n/2; i++)
54 s->csc2[i] = 0.5 / sin((M_PI / (2*n) * (2*i + 1)));
59 /* sin((M_PI * x / (2*n)) */
60 #define SIN(s,n,x) (s->costab[(n) - (x)])
62 /* cos((M_PI * x / (2*n)) */
63 #define COS(s,n,x) (s->costab[x])
65 static void ff_dct_calc_c(DCTContext *ctx, FFTSample *data)
67 int n = 1 << ctx->nbits;
71 float next = data[n - 1];
72 float inv_n = 1.0f / n;
74 for (i = n - 2; i >= 2; i -= 2) {
75 float val1 = data[i ];
76 float val2 = data[i - 1] - data[i + 1];
77 float c = COS(ctx, n, i);
78 float s = SIN(ctx, n, i);
80 data[i ] = c * val1 + s * val2;
81 data[i + 1] = s * val1 - c * val2;
86 ff_rdft_calc(&ctx->rdft, data);
88 for (i = 0; i < n / 2; i++) {
89 float tmp1 = data[i ] * inv_n;
90 float tmp2 = data[n - i - 1] * inv_n;
91 float csc = ctx->csc2[i] * (tmp1 - tmp2);
94 data[i ] = tmp1 + csc;
95 data[n - i - 1] = tmp1 - csc;
99 for (i=0; i < n/2; i++) {
100 float tmp1 = data[i ];
101 float tmp2 = data[n - i - 1];
102 float s = SIN(ctx, n, 2*i + 1);
105 tmp1 = (tmp1 + tmp2) * 0.5f;
108 data[n-i-1] = tmp1 - s;
111 ff_rdft_calc(&ctx->rdft, data);
113 next = data[1] * 0.5;
116 for (i = n - 2; i >= 0; i -= 2) {
117 float inr = data[i ];
118 float ini = data[i + 1];
119 float c = COS(ctx, n, i);
120 float s = SIN(ctx, n, i);
122 data[i ] = c * inr + s * ini;
126 next += s * inr - c * ini;
131 void ff_dct_calc(DCTContext *s, FFTSample *data)
133 ff_dct_calc_c(s, data);
136 av_cold void ff_dct_end(DCTContext *s)
138 ff_rdft_end(&s->rdft);