summaryrefslogtreecommitdiffstats
path: root/src/track/beats.cpp
blob: 58d90a9659913468486037fa95a1124f280548a3 (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
#include "track/beats.h"

#include "moc_beats.cpp"

namespace mixxx {

int Beats::numBeatsInRange(double dStartSample, double dEndSample) {
    double dLastCountedBeat = 0.0;
    int iBeatsCounter;
    for (iBeatsCounter = 1; dLastCountedBeat < dEndSample; iBeatsCounter++) {
        dLastCountedBeat = findNthBeat(dStartSample, iBeatsCounter);
        if (dLastCountedBeat == -1) {
            break;
        }
    }
    return iBeatsCounter - 2;
};

double Beats::findNBeatsFromSample(double fromSample, double beats) const {
    double nthBeat;
    double prevBeat;
    double nextBeat;

    if (!findPrevNextBeats(fromSample, &prevBeat, &nextBeat)) {
        return fromSample;
    }
    double fromFractionBeats = (fromSample - prevBeat) / (nextBeat - prevBeat);
    double beatsFromPrevBeat = fromFractionBeats + beats;

    int fullBeats = static_cast<int>(beatsFromPrevBeat);
    double fractionBeats = beatsFromPrevBeat - fullBeats;

    // Add the length between this beat and the fullbeats'th beat
    // to the end position
    if (fullBeats > 0) {
        nthBeat = findNthBeat(nextBeat, fullBeats);
    } else {
        nthBeat = findNthBeat(prevBeat, fullBeats - 1);
    }

    if (nthBeat == -1) {
        return fromSample;
    }

    // Add the fraction of the beat
    if (fractionBeats != 0) {
        nextBeat = findNthBeat(nthBeat, 2);
        if (nextBeat == -1) {
            return fromSample;
        }
        nthBeat += (nextBeat - nthBeat) * fractionBeats;
    }

    return nthBeat;
};

} // namespace mixxx