summaryrefslogtreecommitdiffhomepage
path: root/tuner.cpp
blob: aa78c4c0d38c2352817e4c4d2b578af9dd584338 (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
#include "tuner.h"

#include "autocorrelation.h"
#include "fft.h"
#include "util.h"

#include <algorithm>
#include <cmath>
#include <iostream>

using namespace RIT;

struct RIT::Tuner::Impl {
public:
	Impl(int size, int f_sample): mAC(size), m_f_sample(f_sample), mSize(size) {}
	RIT::AutoCorrelation mAC;
	int m_f_sample;
	int mSize;
};

RIT::Tuner::Tuner(int size, int f_sample): mImpl(std::make_unique<RIT::Tuner::Impl>(size, f_sample))
{
}

RIT::Tuner::~Tuner(){}

namespace {
	const std::vector<std::string> noteNames{ "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#" };
	const double base = std::pow(2.0, 1./12);

	RIT::Pitch getPitch(double f)
	{
		double noteIndexD = std::log(f / 110.0) / std::log(base) + 0.5;

		double noteIndexI{};
		double deviation = std::modf(noteIndexD, &noteIndexI) - 0.5;
		int noteIndex = int(noteIndexI);

		noteIndex %= 12;
		
		return RIT::Pitch {f, deviation, noteNames[noteIndex]};
	}
}

RIT::Pitch RIT::Tuner::operator() (const std::vector<std::complex<double>> &v)
{
	std::vector<double> autoCorrelation = magnitudes(mImpl->mAC(v));

	auto maxElement = std::max_element(std::begin(autoCorrelation) + 1, std::begin(autoCorrelation) + mImpl->mSize / 2);

	int index = maxElement - std::begin(autoCorrelation);

	//std::cout << "DEBUG" << std::endl;
	if (autoCorrelation[index] > autoCorrelation[index - 1] && autoCorrelation[index] > autoCorrelation[index + 1]) {
		double f = double(mImpl->m_f_sample) / index;
		//std::cout << "DEBUG f = " << f << std::endl;
		return getPitch(f);
	}

	return Pitch{};
}

double RIT::Tuner::fMin()
{
	return double(mImpl->m_f_sample) / mImpl->mSize;
}

double RIT::Tuner::fMax()
{
	return double(mImpl->m_f_sample) / 2;
}