opusenc_utils.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Opus encoder
  3. * Copyright (c) 2017 Rostislav Pehlivanov <atomnuker@gmail.com>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #ifndef AVCODEC_OPUSENC_UTILS_H
  22. #define AVCODEC_OPUSENC_UTILS_H
  23. #include "opus.h"
  24. typedef struct FFBesselFilter {
  25. float a[3];
  26. float b[2];
  27. float x[3];
  28. float y[3];
  29. } FFBesselFilter;
  30. /* Fills the coefficients, returns 1 if filter will be unstable */
  31. static inline int bessel_reinit(FFBesselFilter *s, float n, float f0, float fs,
  32. int highpass)
  33. {
  34. int unstable;
  35. float c, cfreq, w0, k1, k2;
  36. if (!highpass) {
  37. c = (1.0f/sqrtf(sqrtf(pow(2.0f, 1.0f/n) - 3.0f/4.0f) - 0.5f))/sqrtf(3.0f);
  38. cfreq = c*f0/fs;
  39. unstable = (cfreq <= 0.0f || cfreq >= 1.0f/4.0f);
  40. } else {
  41. c = sqrtf(3.0f)*sqrtf(sqrtf(pow(2.0f, 1.0f/n) - 3.0f/4.0f) - 0.5f);
  42. cfreq = 0.5f - c*f0/fs;
  43. unstable = (cfreq <= 3.0f/8.0f || cfreq >= 1.0f/2.0f);
  44. }
  45. w0 = tanf(M_PI*cfreq);
  46. k1 = 3.0f * w0;
  47. k2 = 3.0f * w0;
  48. s->a[0] = k2/(1.0f + k1 + k2);
  49. s->a[1] = 2.0f * s->a[0];
  50. s->a[2] = s->a[0];
  51. s->b[0] = 2.0f * s->a[0] * (1.0f/k2 - 1.0f);
  52. s->b[1] = 1.0f - (s->a[0] + s->a[1] + s->a[2] + s->b[0]);
  53. if (highpass) {
  54. s->a[1] *= -1;
  55. s->b[0] *= -1;
  56. }
  57. return unstable;
  58. }
  59. static inline int bessel_init(FFBesselFilter *s, float n, float f0, float fs,
  60. int highpass)
  61. {
  62. memset(s, 0, sizeof(FFBesselFilter));
  63. return bessel_reinit(s, n, f0, fs, highpass);
  64. }
  65. static inline float bessel_filter(FFBesselFilter *s, float x)
  66. {
  67. s->x[2] = s->x[1];
  68. s->x[1] = s->x[0];
  69. s->x[0] = x;
  70. s->y[2] = s->y[1];
  71. s->y[1] = s->y[0];
  72. s->y[0] = s->a[0]*s->x[0] + s->a[1]*s->x[1] + s->a[2]*s->x[2] + s->b[0]*s->y[1] + s->b[1]*s->y[2];
  73. return s->y[0];
  74. }
  75. #endif /* AVCODEC_OPUSENC_UTILS_H */