summaryrefslogtreecommitdiff
path: root/src/tests/test_spectool.cc
blob: 37a74b7f79c466c6db3eb1bd4a39863ae08aa840 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// This file is part of the 64k demo project.
// It performs an end-to-end test of the spectool's analysis capability.
// Generates a test WAV, analyzes it, and verifies the resulting .spec file.

#include "audio/audio.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "miniaudio.h"

// Redefine SpecHeader to avoid including spectool internals if possible,
// but for an E2E test we need to know the format.
struct SpecHeader {
  char magic[4];
  int32_t version;
  int32_t dct_size;
  int32_t num_frames;
};

void generate_test_wav(const char* path, int duration_seconds) {
  ma_encoder_config config =
      ma_encoder_config_init(ma_encoding_format_wav, ma_format_f32, 1, 32000);
  ma_encoder encoder;

  if (ma_encoder_init_file(path, &config, &encoder) != MA_SUCCESS) {
    printf("Failed to create test WAV file.\n");
    exit(1);
  }

  int num_frames = 32000 * duration_seconds;
  for (int i = 0; i < num_frames; ++i) {
    float sample = 0.5f * sinf(2.0f * 3.14159f * 440.0f * i / 32000.0f);
    ma_encoder_write_pcm_frames(&encoder, &sample, 1, NULL);
  }

  ma_encoder_uninit(&encoder);
}

int main() {
  const char* test_wav = "test_input.wav";
  const char* test_spec = "test_output.spec";

  printf("Generating test WAV...\n");
  generate_test_wav(test_wav, 1);

  printf("Running spectool analyze...\n");
  char command[256];
  snprintf(command, sizeof(command), "./spectool analyze %s %s", test_wav,
           test_spec);
  int ret = system(command);
  assert(ret == 0);

  printf("Verifying .spec file...\n");
  FILE* f = fopen(test_spec, "rb");
  assert(f != NULL);

  SpecHeader header;
  size_t read = fread(&header, sizeof(SpecHeader), 1, f);
  assert(read == 1);
  assert(strncmp(header.magic, "SPEC", 4) == 0);
  assert(header.version == 1);
  assert(header.dct_size == 512);
  assert(header.num_frames > 0);

  fclose(f);
  printf("Spectool E2E test PASSED\n");

  // Clean up
  remove(test_wav);
  remove(test_spec);

  return 0;
}