Debian Codegraph @

libtwolame/psycho_1.c

raw
1 /*
2 * TwoLAME: an optimized MPEG Audio Layer Two encoder
3 *
4 * Copyright (C) 2001-2004 Michael Cheng
5 * Copyright (C) 2004-2018 The TwoLAME Project
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 *
21 */
22
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <math.h>
27
28 #include "twolame.h"
29 #include "common.h"
30 #include "mem.h"
31 #include "fft.h"
32 #include "psycho_1.h"
33
34 /**********************************************************************
35
36 This module implements the psychoacoustic model I for the
37 MPEG encoder layer II. It uses simplified tonal and noise masking
38 threshold analysis to generate SMR for the encoder bit allocation
39 routine.
40
41 **********************************************************************/
42
43
44 static int *psycho_1_read_cbound(int lay, int freq, int *crit_band)
45 /* this function reads in critical band boundaries */
46 {
47
48 #include "psycho_1_critband.h"
49 int *cbound;
50 int i, k;
51
52 if ((lay < 1) || (lay > 2)) {
53 fprintf(stderr, "Internal error (read_cbound())\n");
54 return (NULL);
55 }
56 if ((freq < 0) || (freq > 6) || (freq == 3)) {
57 fprintf(stderr, "Internal error (read_cbound())\n");
58 return (NULL);
59 }
60
61 *crit_band = SecondCriticalBand[freq][0];
62 cbound = (int *) TWOLAME_MALLOC(sizeof(int) * *crit_band);
63 for (i = 0; i < *crit_band; i++) {
64 k = SecondCriticalBand[freq][i + 1];
65 if (k != 0) {
66 cbound[i] = k;
67 } else {
68 fprintf(stderr, "Internal error (read_cbound())\n");
69 return (NULL);
70 }
71 }
72 return (cbound);
73 }
74
75 /* reads in the frequency bands and bark values */
76 static void psycho_1_read_freq_band(g_ptr * ltg, int lay, int freq, int *sub_size)
77 {
78
79 #include "psycho_1_freqtable.h"
80
81 int i, k;
82
83 if ((freq < 0) || (freq > 6) || (freq == 3)) {
84 fprintf(stderr, "Internal error (read_freq_band())\n");
85 return;
86 }
87
88 /* read input for freq. subbands */
89
90 *sub_size = SecondFreqEntries[freq] + 1;
91 *ltg = (g_ptr) TWOLAME_MALLOC(sizeof(g_thres) * *sub_size);
92 (*ltg)[0].line = 0; /* initialize global masking threshold */
93 (*ltg)[0].bark = 0.0;
94 (*ltg)[0].hear = 0.0;
95 for (i = 1; i < *sub_size; i++) {
96 k = SecondFreqSubband[freq][i - 1].line;
97 if (k != 0) {
98 (*ltg)[i].line = k;
99 (*ltg)[i].bark = SecondFreqSubband[freq][i - 1].bark;
100 (*ltg)[i].hear = SecondFreqSubband[freq][i - 1].hear;
101 } else {
102 fprintf(stderr, "Internal error (read_freq_band())\n");
103 return;
104 }
105 }
106 }
107
108
109 static void psycho_1_make_map(int sub_size, mask power[HAN_SIZE], g_thres * ltg)
110 /* this function calculates the global masking threshold */
111 {
112 int i, j;
113
114 for (i = 1; i < sub_size; i++)
115 for (j = ltg[i - 1].line; j <= ltg[i].line; j++)
116 power[j].map = i;
117 }
118
119 static void psycho_1_init_add_db(psycho_1_mem * mem)
120 {
121 int i;
122 FLOAT x;
123 for (i = 0; i < DBTAB; i++) {
124 x = (FLOAT) i / 10.0;
125 mem->dbtable[i] = 10 * log10(1 + pow(10.0, x / 10.0)) - x;
126 }
127 }
128
129 static inline FLOAT add_db(psycho_1_mem * mem, FLOAT a, FLOAT b)
130 {
131 /* MFC - if the difference between a and b is large (>99), then just return the largest one.
132 (about 10% of the time) - For differences between 0 and 99, return the largest value, but
133 add in a pre-calculated difference value. - the value 99 was chosen arbitarily. - maximum
134 (a-b) i've seen is 572 */
135 FLOAT fdiff;
136 int idiff;
137 fdiff = (10.0 * (a - b));
138
139 if (fdiff > 990.0) {
140 return a;
141 }
142 if (fdiff < -990.0) {
143 return (b);
144 }
145
146 idiff = (int) fdiff;
147 if (idiff >= 0) {
148 return (a + mem->dbtable[idiff]);
149 }
150
151 return (b + mem->dbtable[-idiff]);
152 }
153
154 /****************************************************************
155 * Window the samples then,
156 * Fast Fourier transform of the input samples.
157 *
158 * ( call the FHT-based fft() in fft.c )
159 *
160 *
161 ****************************************************************/
162 static void psycho_1_hann_fft_pickmax(FLOAT sample[FFT_SIZE], mask power[HAN_SIZE],
163 FLOAT spike[SBLIMIT], FLOAT energy[FFT_SIZE])
164 {
165 FLOAT x_real[FFT_SIZE];
166 register int i, j;
167 register FLOAT sqrt_8_over_3;
168 static int init = 0;
169 static FLOAT window[FFT_SIZE];
170 FLOAT sum;
171
172 if (!init) {
173 /* calculate window function for the Fourier transform */
174 /* These values need only be initiliased once, regardless of the caller */
175 sqrt_8_over_3 = pow(8.0 / 3.0, 0.5);
176 for (i = 0; i < FFT_SIZE; i++) {
177 /* Hann window formula */
178 window[i] = sqrt_8_over_3 * 0.5 * (1 - cos(2.0 * PI * i / (FFT_SIZE))) / FFT_SIZE;
179 }
180 init = 1;
181 }
182 for (i = 0; i < FFT_SIZE; i++)
183 x_real[i] = (FLOAT) (sample[i] * window[i]);
184
185 twolame_psycho_1_fft(x_real, energy, FFT_SIZE);
186
187 for (i = 0; i < HAN_SIZE; i++) { /* calculate power density spectrum */
188 if (energy[i] < 1E-20)
189 power[i].x = -200.0 + POWERNORM;
190 else
191 power[i].x = 10 * log10(energy[i]) + POWERNORM;
192 power[i].next = STOP;
193 power[i].type = FALSE;
194 }
195
196 /* Calculate the sum of spectral component in each subband from bound 4-16 */
197
198 #define CF 1073741824 /* pow(10, 0.1*POWERNORM) */
199 #define DBM 1E-20 /* pow(10.0, 0.1*DBMIN */
200 for (i = 0; i < HAN_SIZE; spike[i >> 4] = 10.0 * log10(sum), i += 16) {
201 for (j = 0, sum = DBM; j < 16; j++)
202 sum += CF * energy[i + j];
203 }
204 }
205
206 /****************************************************************
207 *
208 * This function labels the tonal component in the power
209 * spectrum.
210 *
211 ****************************************************************/
212
213 static void psycho_1_tonal_label(psycho_1_mem * mem, int *tone)
214 /* this function extracts (tonal) sinusoidals from the spectrum */
215 {
216 int i, j, last = LAST, first, run, last_but_one = LAST; /* dpwe */
217 FLOAT max;
218 mask *power = mem->power;
219
220 *tone = LAST;
221 for (i = 2; i < HAN_SIZE - 12; i++) {
222 if (power[i].x > power[i - 1].x && power[i].x >= power[i + 1].x) {
223 power[i].type = TONE;
224 power[i].next = LAST;
225 if (last != LAST)
226 power[last].next = i;
227 else
228 first = *tone = i;
229 last = i;
230 }
231 }
232 last = LAST;
233 first = *tone;
234 *tone = LAST;
235 while ((first != LAST) && (first != STOP)) { /* the conditions for the tonal */
236 if (first < 3 || first > 500)
237 run = 0; /* otherwise k+/-j will be out of bounds */
238 else if (first < 63)
239 run = 2; /* components in layer II, which */
240 else if (first < 127)
241 run = 3; /* are the boundaries for calc. */
242 else if (first < 255)
243 run = 6; /* the tonal components */
244 else
245 run = 12;
246 max = power[first].x - 7; /* after calculation of tonal */
247 for (j = 2; j <= run; j++) /* components, set to local max */
248 if (max < power[first - j].x || max < power[first + j].x) {
249 power[first].type = FALSE;
250 break;
251 }
252 if (power[first].type == TONE) { /* extract tonal components */
253 int help = first;
254 if (*tone == LAST)
255 *tone = first;
256 while ((power[help].next != LAST) && (power[help].next - first) <= run)
257 help = power[help].next;
258 help = power[help].next;
259 power[first].next = help;
260 if ((first - last) <= run) {
261 if (last_but_one != LAST)
262 power[last_but_one].next = first;
263 }
264 if (first > 1 && first < 500) { /* calculate the sum of the */
265 FLOAT tmp; /* powers of the components */
266 tmp = add_db(mem, power[first - 1].x, power[first + 1].x);
267 power[first].x = add_db(mem, power[first].x, tmp);
268 }
269 for (j = 1; j <= run; j++) {
270 power[first - j].x = power[first + j].x = DBMIN;
271 power[first - j].next = power[first + j].next = STOP;
272 power[first - j].type = power[first + j].type = FALSE;
273 }
274 last_but_one = last;
275 last = first;
276 first = power[first].next;
277 } else {
278 int ll;
279 if (last == LAST); /* *tone = power[first].next; dpwe */
280 else
281 power[last].next = power[first].next;
282 ll = first;
283 first = power[first].next;
284 power[ll].next = STOP;
285 }
286 }
287 }
288
289 /****************************************************************
290 *
291 * This function groups all the remaining non-tonal
292 * spectral lines into critical band where they are replaced by
293 * one single line.
294 *
295 ****************************************************************/
296
297 static void psycho_1_noise_label(psycho_1_mem * mem, int *noise, FLOAT energy[FFT_SIZE])
298 {
299 int i, j, centre, last = LAST;
300 FLOAT index, weight, sum;
301 int crit_band = mem->crit_band;
302 int *cbound = mem->cbound;
303 mask *power = mem->power;
304 /* calculate the remaining spectral */
305 for (i = 0; i < crit_band - 1; i++) { /* lines for non-tonal components */
306 for (j = cbound[i], weight = 0.0, sum = DBMIN; j < cbound[i + 1]; j++) {
307 if (power[j].type != TONE) {
308 if (power[j].x != DBMIN) {
309 sum = add_db(mem, power[j].x, sum);
310 /* Weight is used in finding the geometric mean of the noise energy within a
311 subband */
312 weight += CF * energy[j] * (FLOAT) (j - cbound[i]) / (FLOAT) (cbound[i + 1] - cbound[i]); /* correction
313 */
314 power[j].x = DBMIN;
315 }
316 } /* check to see if the spectral line is low dB, and if */
317 } /* so replace the center of the critical band, which is */
318 /* the center freq. of the noise component */
319
320 if (sum <= DBMIN)
321 centre = (cbound[i + 1] + cbound[i]) / 2;
322 else {
323 /* fprintf(stderr, "%i [%f %f] -", count++,weight/pow(10.0,0.1*sum),
324 weight*pow(10.0,-0.1*sum)); */
325 index = weight * pow(10.0, -0.1 * sum);
326 centre = cbound[i] + (int) (index * (FLOAT) (cbound[i + 1] - cbound[i]));
327 }
328
329
330 /* locate next non-tonal component until finished; */
331 /* add to list of non-tonal components */
332
333 /* Masahiro Iwadare's fix for infinite looping problem? */
334 if (power[centre].type == TONE) {
335 if (power[centre + 1].type == TONE) {
336 centre++;
337 } else
338 centre--;
339 }
340
341 if (last == LAST)
342 *noise = centre;
343 else {
344 power[centre].next = LAST;
345 power[last].next = centre;
346 }
347 power[centre].x = sum;
348 power[centre].type = NOISE;
349 last = centre;
350 }
351 }
352
353 /****************************************************************
354 *
355 * This function reduces the number of noise and tonal
356 * component for further threshold analysis.
357 *
358 ****************************************************************/
359
360 static void psycho_1_subsampling(mask power[HAN_SIZE], g_thres * ltg, int *tone, int *noise)
361 {
362 int i, old;
363
364 i = *tone;
365 old = STOP; /* calculate tonal components for */
366
367 while ((i != LAST) && (i != STOP)) { /* reduction of spectral lines */
368 if (power[i].x < ltg[power[i].map].hear) {
369 power[i].type = FALSE;
370 power[i].x = DBMIN;
371 if (old == STOP)
372 *tone = power[i].next;
373 else
374 power[old].next = power[i].next;
375 } else
376 old = i;
377 i = power[i].next;
378 }
379 i = *noise;
380 old = STOP; /* calculate non-tonal components for */
381 while ((i != LAST) && (i != STOP)) { /* reduction of spectral lines */
382 if (power[i].x < ltg[power[i].map].hear) {
383 power[i].type = FALSE;
384 power[i].x = DBMIN;
385 if (old == STOP)
386 *noise = power[i].next;
387 else
388 power[old].next = power[i].next;
389 } else
390 old = i;
391 i = power[i].next;
392 }
393 i = *tone;
394 old = STOP;
395 while ((i != LAST) && (i != STOP)) { /* if more than one */
396 if (power[i].next == LAST)
397 break; /* tonal component */
398 if (ltg[power[power[i].next].map].bark - /* is less than .5 */
399 ltg[power[i].map].bark < 0.5) { /* bark, take the */
400 if (power[power[i].next].x > power[i].x) { /* maximum */
401 if (old == STOP)
402 *tone = power[i].next;
403 else
404 power[old].next = power[i].next;
405 power[i].type = FALSE;
406 power[i].x = DBMIN;
407 i = power[i].next;
408 } else {
409 power[power[i].next].type = FALSE;
410 power[power[i].next].x = DBMIN;
411 power[i].next = power[power[i].next].next;
412 old = i;
413 }
414 } else {
415 old = i;
416 i = power[i].next;
417 }
418 }
419 }
420
421 /****************************************************************
422 *
423 * This function calculates the individual threshold and
424 * sum with the quiet threshold to find the global threshold.
425 *
426 ****************************************************************/
427
428 /* mainly just changed the way range checking was done MFC Nov 1999 */
429 static void psycho_1_threshold(psycho_1_mem * mem, int *tone, int *noise, int bit_rate)
430 {
431 int sub_size = mem->sub_size;
432 mask *power = mem->power;
433 g_thres *ltg = mem->ltg;
434 int k, t;
435 FLOAT dz, tmps, vf;
436
437 for (k = 1; k < sub_size; k++) {
438 ltg[k].x = DBMIN;
439 t = *tone; /* calculate individual masking threshold for */
440 while ((t != LAST) && (t != STOP)) { /* components in order to find the global */
441 dz = ltg[k].bark - ltg[power[t].map].bark; /* distance of bark value */
442 if (dz >= -3.0 && dz < 8.0) {
443 tmps = -1.525 - 0.275 * ltg[power[t].map].bark - 4.5 + power[t].x;
444 /* masking function for lower & upper slopes */
445 if (dz < -1)
446 vf = 17 * (dz + 1) - (0.4 * power[t].x + 6);
447 else if (dz < 0)
448 vf = (0.4 * power[t].x + 6) * dz;
449 else if (dz < 1)
450 vf = (-17 * dz);
451 else
452 vf = -(dz - 1) * (17 - 0.15 * power[t].x) - 17;
453 ltg[k].x = add_db(mem, ltg[k].x, tmps + vf);
454 }
455 t = power[t].next;
456 }
457
458 t = *noise; /* calculate individual masking threshold */
459 while ((t != LAST) && (t != STOP)) { /* for non-tonal components to find LTG */
460 dz = ltg[k].bark - ltg[power[t].map].bark; /* distance of bark value */
461 if (dz >= -3.0 && dz < 8.0) {
462 tmps = -1.525 - 0.175 * ltg[power[t].map].bark - 0.5 + power[t].x;
463 /* masking function for lower & upper slopes */
464 if (dz < -1)
465 vf = 17 * (dz + 1) - (0.4 * power[t].x + 6);
466 else if (dz < 0)
467 vf = (0.4 * power[t].x + 6) * dz;
468 else if (dz < 1)
469 vf = (-17 * dz);
470 else
471 vf = -(dz - 1) * (17 - 0.15 * power[t].x) - 17;
472 ltg[k].x = add_db(mem, ltg[k].x, tmps + vf);
473 }
474 t = power[t].next;
475 }
476 if (bit_rate < 96)
477 ltg[k].x = add_db(mem, ltg[k].hear, ltg[k].x);
478 else
479 ltg[k].x = add_db(mem, ltg[k].hear - 12.0, ltg[k].x);
480 }
481
482 }
483
484 /****************************************************************
485 *
486 * This function finds the minimum masking threshold and
487 * return the value to the encoder.
488 *
489 ****************************************************************/
490
491 static void psycho_1_minimum_mask(int sub_size, g_thres * ltg, FLOAT ltmin[SBLIMIT], int sblimit)
492 {
493 FLOAT min;
494 int i, j;
495
496 j = 1;
497 for (i = 0; i < sblimit; i++)
498 if (j >= sub_size - 1) /* check subband limit, and */
499 ltmin[i] = ltg[sub_size - 1].hear; /* calculate the minimum masking */
500 else { /* level of LTMIN for each subband */
501 min = ltg[j].x;
502 while (ltg[j].line >> 4 == i && j < sub_size) {
503 if (min > ltg[j].x)
504 min = ltg[j].x;
505 j++;
506 }
507 ltmin[i] = min;
508 }
509 }
510
511 /*****************************************************************
512 *
513 * This procedure is called in musicin to pick out the
514 * smaller of the scalefactor or threshold.
515 *
516 *****************************************************************/
517
518 static void psycho_1_smr(FLOAT ltmin[SBLIMIT], FLOAT spike[SBLIMIT], FLOAT scale[SBLIMIT],
519 int sblimit)
520 {
521 int i;
522 FLOAT max;
523
524 for (i = 0; i < sblimit; i++) { /* determine the signal */
525 max = 20 * log10(scale[i] * 32768) - 10; /* level for each subband */
526 if (spike[i] > max)
527 max = spike[i]; /* for the maximum scale */
528 max -= ltmin[i]; /* factors */
529 ltmin[i] = max;
530 }
531 }
532
533
534 /*
535 static void psycho_1_dump(mask power[HAN_SIZE], int *tone, int *noise) {
536 int t;
537
538 fprintf(stderr,"1 Ton: ");
539 t=*tone;
540 while (t!=LAST && t!=STOP) {
541 fprintf(stderr,"[%i] %3.0f ",t, power[t].x);
542 t = power[t].next;
543 }
544 fprintf(stderr,"\n");
545
546 fprintf(stderr,"1 Nos: ");
547 t=*noise;
548 while (t!=LAST && t!=STOP) {
549 fprintf(stderr,"[%i] %3.0f ",t, power[t].x);
550 t = power[t].next;
551 }
552 fprintf(stderr,"\n");
553 }
554 */
555
556
557 void twolame_psycho_1(twolame_options * glopts, short buffer[2][1152], FLOAT scale[2][SBLIMIT],
558 FLOAT ltmin[2][SBLIMIT])
559 {
560 psycho_1_mem *mem;
561 frame_header *header = &glopts->header;
562 int nch = glopts->num_channels_out;
563 int sblimit = glopts->sblimit;
564 int k, i, tone = 0, noise = 0;
565 FLOAT sample[FFT_SIZE];
566 FLOAT spike[2][SBLIMIT];
567 FLOAT *fft_buf[2];
568 FLOAT energy[FFT_SIZE];
569
570 /* call functions for critical boundaries, freq. */
571 if (!glopts->p1mem) { /* bands, bark values, and mapping */
572 mem = (psycho_1_mem *) TWOLAME_MALLOC(sizeof(psycho_1_mem));
573
574 mem->power = (mask_ptr) TWOLAME_MALLOC(sizeof(mask) * HAN_SIZE);
575 if (header->version == TWOLAME_MPEG1) {
576 mem->cbound =
577 psycho_1_read_cbound(header->lay, header->samplerate_idx, &mem->crit_band);
578 psycho_1_read_freq_band(&mem->ltg, header->lay, header->samplerate_idx, &mem->sub_size);
579 } else {
580 mem->cbound =
581 psycho_1_read_cbound(header->lay, header->samplerate_idx + 4, &mem->crit_band);
582 psycho_1_read_freq_band(&mem->ltg, header->lay, header->samplerate_idx + 4,
583 &mem->sub_size);
584 }
585 psycho_1_make_map(mem->sub_size, mem->power, mem->ltg);
586 for (i = 0; i < 1408; i++)
587 mem->fft_buf[0][i] = mem->fft_buf[1][i] = 0;
588
589 psycho_1_init_add_db(mem); /* create the add_db table */
590
591 mem->off[0] = 256;
592 mem->off[1] = 256;
593
594 glopts->p1mem = mem;
595 }
596 {
597 mem = glopts->p1mem;
598
599 fft_buf[0] = mem->fft_buf[0];
600 fft_buf[1] = mem->fft_buf[1];
601 }
602
603
604 for (k = 0; k < nch; k++) {
605 /* check pcm input for 3 blocks of 384 samples */
606 /* sami's speedup, added in 02j saves about 4% overall during an encode */
607 int ok = mem->off[k] % 1408;
608 for (i = 0; i < 1152; i++) {
609 fft_buf[k][ok++] = (FLOAT) buffer[k][i] / SCALE;
610 if (ok >= 1408)
611 ok = 0;
612 }
613 ok = (mem->off[k] + 1216) % 1408;
614 for (i = 0; i < FFT_SIZE; i++) {
615 sample[i] = fft_buf[k][ok++];
616 if (ok >= 1408)
617 ok = 0;
618 }
619 mem->off[k] += 1152;
620 mem->off[k] %= 1408;
621
622 psycho_1_hann_fft_pickmax(sample, mem->power, &spike[k][0], energy);
623 psycho_1_tonal_label(mem, &tone);
624 psycho_1_noise_label(mem, &noise, energy);
625 // psycho_1_dump(power, &tone, &noise) ;
626 psycho_1_subsampling(mem->power, mem->ltg, &tone, &noise);
627 psycho_1_threshold(mem, &tone, &noise, glopts->bitrate / nch);
628 psycho_1_minimum_mask(mem->sub_size, mem->ltg, &ltmin[k][0], sblimit);
629 psycho_1_smr(&ltmin[k][0], &spike[k][0], &scale[k][0], sblimit);
630 }
631
632 }
633
634 void twolame_psycho_1_deinit(psycho_1_mem ** mem)
635 {
636
637 if (mem == NULL || *mem == NULL)
638 return;
639
640 TWOLAME_FREE((*mem)->cbound);
641 TWOLAME_FREE((*mem)->ltg);
642 TWOLAME_FREE((*mem)->power);
643 TWOLAME_FREE((*mem));
644 }
645
646
647 // vim:ts=4:sw=4:nowrap: