window_util.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #include "tensorflow/lite/experimental/microfrontend/lib/window_util.h"
  13. #include <math.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. // Some platforms don't have M_PI
  18. #ifndef M_PI
  19. #define M_PI 3.14159265358979323846
  20. #endif
  21. void WindowFillConfigWithDefaults(struct WindowConfig* config) {
  22. config->size_ms = 25;
  23. config->step_size_ms = 10;
  24. }
  25. int WindowPopulateState(const struct WindowConfig* config,
  26. struct WindowState* state, int sample_rate) {
  27. state->size = config->size_ms * sample_rate / 1000;
  28. state->step = config->step_size_ms * sample_rate / 1000;
  29. state->coefficients = malloc(state->size * sizeof(*state->coefficients));
  30. if (state->coefficients == NULL) {
  31. fprintf(stderr, "Failed to allocate window coefficients\n");
  32. return 0;
  33. }
  34. // Populate the window values.
  35. const float arg = M_PI * 2.0 / ((float)state->size);
  36. int i;
  37. for (i = 0; i < state->size; ++i) {
  38. float float_value = 0.5 - (0.5 * cos(arg * (i + 0.5)));
  39. // Scale it to fixed point and round it.
  40. state->coefficients[i] =
  41. floor(float_value * (1 << kFrontendWindowBits) + 0.5);
  42. }
  43. state->input_used = 0;
  44. state->input = malloc(state->size * sizeof(*state->input));
  45. if (state->input == NULL) {
  46. fprintf(stderr, "Failed to allocate window input\n");
  47. return 0;
  48. }
  49. state->output = malloc(state->size * sizeof(*state->output));
  50. if (state->output == NULL) {
  51. fprintf(stderr, "Failed to allocate window output\n");
  52. return 0;
  53. }
  54. return 1;
  55. }
  56. void WindowFreeStateContents(struct WindowState* state) {
  57. free(state->coefficients);
  58. free(state->input);
  59. free(state->output);
  60. }