]> git.sesse.net Git - nageru/blob - alsa_input.h
Fix a deadlock issue when shutting down ALSA cards.
[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. The only exception
9 // is in frame_length, where it means the TIMEBASE length of the buffer
10 // as a whole, since that's what AudioMixer::add_audio() wants.
11
12 #include <alsa/asoundlib.h>
13
14 #include <atomic>
15 #include <functional>
16 #include <string>
17 #include <thread>
18 #include <vector>
19
20 #include "bmusb/bmusb.h"
21 #include "timebase.h"
22
23 class ALSAInput {
24 public:
25         typedef std::function<bool(const uint8_t *data, unsigned num_samples, bmusb::AudioFormat audio_format, int64_t frame_length)> audio_callback_t;
26
27         ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback);
28         ~ALSAInput();
29
30         // NOTE: Might very well be different from the sample rate given to the
31         // constructor, since the card might not support the one you wanted.
32         unsigned get_sample_rate() const { return sample_rate; }
33
34         void start_capture_thread();
35         void stop_capture_thread();
36
37         // TODO: Worry about hotplug.
38         struct Device {
39                 std::string address;  // E.g. “hw:0,0”.
40                 std::string name, info;
41                 unsigned num_channels;
42         };
43         static std::vector<Device> enumerate_devices();
44
45 private:
46         void capture_thread_func();
47         int64_t frames_to_pts(uint64_t n) const;
48         void die_on_error(const char *func_name, int err);
49
50         std::string device;
51         unsigned sample_rate, num_channels, num_periods;
52         snd_pcm_uframes_t period_size;
53         snd_pcm_uframes_t buffer_frames;
54         bmusb::AudioFormat audio_format;
55         audio_callback_t audio_callback;
56
57         snd_pcm_t *pcm_handle;
58         std::thread capture_thread;
59         std::atomic<bool> should_quit{false};
60         std::unique_ptr<uint8_t[]> buffer;
61 };
62
63 #endif  // !defined(_ALSA_INPUT_H)