]> git.sesse.net Git - nageru/blob - nageru/audio_clip.h
Make an automated delay estimate, by way of cross-correlation.
[nageru] / nageru / audio_clip.h
1 #ifndef AUDIO_CLIP_H
2 #define AUDIO_CLIP_H
3
4 // A short single-channel recording of an audio clip, for the delay analyzer.
5 // Thread safe.
6
7 #include <chrono>
8 #include <memory>
9 #include <mutex>
10 #include <utility>
11 #include <vector>
12
13 class AudioClip
14 {
15 public:
16         void clear();
17         void add_audio(const float *samples, size_t num_samples, double sample_rate, std::chrono::steady_clock::time_point frame_time);
18         double get_length_seconds() const;  // 0.0 if empty().
19         double get_length_seconds_after_base(std::chrono::steady_clock::time_point base) const;
20         bool empty() const;
21
22         // Only valid if not empty.
23         std::chrono::steady_clock::time_point get_first_sample() const;
24
25         struct BestCorrelation {
26                 float delay_ms;  // Positive values means this clip is delayed compared to the reference.
27                 float correlation;  // Between -1 and +1 (+1 is a perfect match, -1 is a perfect inversion).
28         };
29         BestCorrelation find_best_correlation(const AudioClip *reference) const;
30
31         std::unique_ptr<std::pair<float, float>[]> get_min_max_peaks(unsigned width, std::chrono::steady_clock::time_point base) const;
32
33 private:
34         mutable std::mutex mu;
35         std::vector<float> vals;  // Under <mutex>.
36         double sample_rate;  // Under <mutex>.
37         std::chrono::steady_clock::time_point first_sample;  // Under <mutex>.
38 };
39
40 #endif