]> git.sesse.net Git - nageru/blob - nageru/alsa_input.h
IWYU-fix nageru/*.h.
[nageru] / nageru / alsa_input.h
1 #ifndef _ALSA_INPUT_H
2 #define _ALSA_INPUT_H 1
3
4 // ALSA sound input, running in a separate thread and sending audio back
5 // in callbacks.
6 //
7 // Note: “frame” here generally refers to the ALSA definition of frame,
8 // which is a set of samples, exactly one for each channel.
9
10 #include <alsa/asoundlib.h>
11 #include <stdint.h>
12 #include <chrono>
13 #include <functional>
14 #include <memory>
15 #include <string>
16 #include <thread>
17
18 #include "bmusb/bmusb.h"
19 #include "quittable_sleeper.h"
20
21 class ALSAPool;
22
23 class ALSAInput {
24 public:
25         typedef std::function<bool(const uint8_t *data, unsigned num_samples, bmusb::AudioFormat audio_format, std::chrono::steady_clock::time_point ts)> audio_callback_t;
26
27         ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index);
28         ~ALSAInput();
29
30         // If not called before start_capture_thread(), the capture thread
31         // will call it until it succeeds.
32         bool open_device();
33
34         // Not valid before the device has been successfully opened.
35         // NOTE: Might very well be different from the sample rate given to the
36         // constructor, since the card might not support the one you wanted.
37         unsigned get_sample_rate() const { return sample_rate; }
38
39         void start_capture_thread();
40         void stop_capture_thread();
41
42         // Set access, sample rate and format parameters on the given ALSA PCM handle.
43         // Returns the computed parameter set and the chosen sample rate. Note that
44         // sample_rate is an in/out parameter; you send in the desired rate,
45         // and ALSA picks one as close to that as possible.
46         static bool set_base_params(const char *device_name, snd_pcm_t *pcm_handle, snd_pcm_hw_params_t *hw_params, unsigned *sample_rate);
47
48 private:
49         bool done_init = false;
50         void capture_thread_func();
51
52         enum class CaptureEndReason {
53                 REQUESTED_QUIT,
54                 DEVICE_GONE,
55                 OTHER_ERROR
56         };
57         CaptureEndReason do_capture();
58
59         std::string device;
60         unsigned sample_rate, num_channels, num_periods;
61         snd_pcm_uframes_t period_size;
62         snd_pcm_uframes_t buffer_frames;
63         bmusb::AudioFormat audio_format;
64         audio_callback_t audio_callback;
65
66         snd_pcm_t *pcm_handle = nullptr;
67         std::thread capture_thread;
68         QuittableSleeper should_quit;
69         std::unique_ptr<uint8_t[]> buffer;
70         ALSAPool *parent_pool;
71         unsigned internal_dev_index;
72 };
73
74 #endif  // !defined(_ALSA_INPUT_H)