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