fft_util.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/fft_util.h"
  13. #include <stdio.h>
  14. #define FIXED_POINT 16
  15. #include "kiss_fft.h"
  16. #include "tools/kiss_fftr.h"
  17. int FftPopulateState(struct FftState* state, size_t input_size) {
  18. state->input_size = input_size;
  19. state->fft_size = 1;
  20. while (state->fft_size < state->input_size) {
  21. state->fft_size <<= 1;
  22. }
  23. state->input = reinterpret_cast<int16_t*>(
  24. malloc(state->fft_size * sizeof(*state->input)));
  25. if (state->input == nullptr) {
  26. fprintf(stderr, "Failed to alloc fft input buffer\n");
  27. return 0;
  28. }
  29. state->output = reinterpret_cast<complex_int16_t*>(
  30. malloc((state->fft_size / 2 + 1) * sizeof(*state->output) * 2));
  31. if (state->output == nullptr) {
  32. fprintf(stderr, "Failed to alloc fft output buffer\n");
  33. return 0;
  34. }
  35. // Ask kissfft how much memory it wants.
  36. size_t scratch_size = 0;
  37. kiss_fftr_cfg kfft_cfg = kiss_fftr_alloc(
  38. state->fft_size, 0, nullptr, &scratch_size);
  39. if (kfft_cfg != nullptr) {
  40. fprintf(stderr, "Kiss memory sizing failed.\n");
  41. return 0;
  42. }
  43. state->scratch = malloc(scratch_size);
  44. if (state->scratch == nullptr) {
  45. fprintf(stderr, "Failed to alloc fft scratch buffer\n");
  46. return 0;
  47. }
  48. state->scratch_size = scratch_size;
  49. // Let kissfft configure the scratch space we just allocated
  50. kfft_cfg = kiss_fftr_alloc(state->fft_size, 0,
  51. state->scratch, &scratch_size);
  52. if (kfft_cfg != state->scratch) {
  53. fprintf(stderr, "Kiss memory preallocation strategy failed.\n");
  54. return 0;
  55. }
  56. return 1;
  57. }
  58. void FftFreeStateContents(struct FftState* state) {
  59. free(state->input);
  60. free(state->output);
  61. free(state->scratch);
  62. }