RmsHelper.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * RmsHelper.h - helper class for calculating RMS
  3. *
  4. * Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
  5. * Copyright (c) 2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
  6. *
  7. * This file is part of LMMS - https://lmms.io
  8. *
  9. * This program is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2 of the License, or (at your option) any later version.
  13. *
  14. * This program 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. * General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public
  20. * License along with this program (see COPYING); if not, write to the
  21. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  22. * Boston, MA 02110-1301 USA.
  23. *
  24. */
  25. #ifndef RMS_HELPER_H
  26. #define RMS_HELPER_H
  27. #include "lmms_math.h"
  28. class RmsHelper
  29. {
  30. public:
  31. RmsHelper( int size ) :
  32. m_buffer( NULL )
  33. {
  34. setSize( size );
  35. }
  36. virtual ~RmsHelper()
  37. {
  38. if( m_buffer ) delete[] m_buffer;
  39. }
  40. inline void setSize( int size )
  41. {
  42. if( m_buffer )
  43. {
  44. if( m_size < size )
  45. {
  46. delete m_buffer;
  47. m_buffer = new float[ size ];
  48. m_size = size;
  49. reset();
  50. }
  51. else
  52. {
  53. m_size = size;
  54. reset();
  55. }
  56. }
  57. else
  58. {
  59. m_buffer = new float[ size ];
  60. m_size = size;
  61. reset();
  62. }
  63. }
  64. inline void reset()
  65. {
  66. m_sizef = 1.0f / (float) m_size;
  67. m_pos = 0;
  68. m_sum = 0.0f;
  69. memset( m_buffer, 0, m_size * sizeof( float ) );
  70. }
  71. inline float update( const float in )
  72. {
  73. m_sum -= m_buffer[ m_pos ];
  74. m_sum += m_buffer[ m_pos ] = in * in;
  75. ++m_pos %= m_size;
  76. return sqrtf( m_sum * m_sizef );
  77. }
  78. private:
  79. float * m_buffer;
  80. float m_sum;
  81. unsigned int m_pos;
  82. unsigned int m_size;
  83. float m_sizef;
  84. };
  85. #endif