]> git.sesse.net Git - nageru/blob - alsa_input.h
Make it possible to load/save input mappings.
[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 <unordered_map>
19 #include <vector>
20
21 #include "bmusb/bmusb.h"
22 #include "timebase.h"
23
24 class ALSAPool;
25 class DeviceSpecProto;
26
27 class ALSAInput {
28 public:
29         typedef std::function<bool(const uint8_t *data, unsigned num_samples, bmusb::AudioFormat audio_format, int64_t frame_length)> audio_callback_t;
30
31         ALSAInput(const char *device, unsigned sample_rate, unsigned num_channels, audio_callback_t audio_callback, ALSAPool *parent_pool, unsigned internal_dev_index);
32         ~ALSAInput();
33
34         // If not called before start_capture_thread(), the capture thread
35         // will call it until it succeeds.
36         bool open_device();
37
38         // Not valid before the device has been successfully opened.
39         // NOTE: Might very well be different from the sample rate given to the
40         // constructor, since the card might not support the one you wanted.
41         unsigned get_sample_rate() const { return sample_rate; }
42
43         void start_capture_thread();
44         void stop_capture_thread();
45
46 private:
47         void capture_thread_func();
48         int64_t frames_to_pts(uint64_t n) const;
49
50         enum class CaptureEndReason {
51                 REQUESTED_QUIT,
52                 DEVICE_GONE,
53                 OTHER_ERROR
54         };
55         CaptureEndReason do_capture();
56
57         std::string device;
58         unsigned sample_rate, num_channels, num_periods;
59         snd_pcm_uframes_t period_size;
60         snd_pcm_uframes_t buffer_frames;
61         bmusb::AudioFormat audio_format;
62         audio_callback_t audio_callback;
63
64         snd_pcm_t *pcm_handle = nullptr;
65         std::thread capture_thread;
66         std::atomic<bool> should_quit{false};
67         std::unique_ptr<uint8_t[]> buffer;
68         ALSAPool *parent_pool;
69         unsigned internal_dev_index;
70 };
71
72 // The class dealing with the collective of all ALSA cards in the system.
73 // In particular, it deals with enumeration of cards, and hotplug of new ones.
74 class ALSAPool {
75 public:
76         ~ALSAPool();
77
78         struct Device {
79                 enum class State {
80                         // There is no card here. (There probably used to be one,
81                         // but it got removed.) We don't insert a card before
82                         // we've actually probed it, ie., we know whether it
83                         // can be captured from at all, and what its name is.
84                         EMPTY,
85
86                         // This card is ready for capture, as far as we know.
87                         // (It could still be used by someone else; we don't know
88                         // until we try to open it.)
89                         READY,
90
91                         // We are trying to start capture from this card, but we are not
92                         // streaming yet. Note that this could in theory go on forever,
93                         // if the card is in use by some other process; in the UI,
94                         // we will show this state as “(busy)”.
95                         STARTING,
96
97                         // The card is capturing and sending data. If there's a fatal error,
98                         // it could go back to STARTING, or it could go to DEAD
99                         // (depending on the error).
100                         RUNNING,
101
102                         // The card is gone (e.g., unplugged). However, since there's
103                         // still a bus using it, we can't just remove the entry.
104                         // If the card comes back (ie., a new card is plugged in,
105                         // and we believe it has the same configuration), it could be
106                         // installed in place of this card, and then presumably be put
107                         // back into STARTING or RUNNING.
108                         DEAD
109                 } state = State::EMPTY;
110
111                 std::string address;  // E.g. “hw:0,0”.
112                 std::string name, info;
113                 unsigned num_channels;
114                 ALSAInput *input = nullptr;  // nullptr iff EMPTY or DEAD.
115
116                 // Whether the AudioMixer is interested in this card or not.
117                 // “Interested” could mean either of two things: Either it is part of
118                 // a bus mapping, or it is in the process of enumerating devices
119                 // (to show to the user). A card that is _not_ held can disappear
120                 // at any given time as a result of an error or hotplug event;
121                 // a card that is held will go to the DEAD state instead.
122                 bool held = false;
123
124                 std::string display_name() const { return name + " (" + info + ")"; }
125         };
126
127         void init();
128
129         // Get the list of all current devices. Note that this will implicitly mark
130         // all of the returned devices as held, since the input mapping UI needs
131         // some kind of stability when the user is to choose. Thus, when you are done
132         // with the list and have set a new mapping, you must go through all the devices
133         // you don't want and release them using release_device().
134         std::vector<Device> get_devices();
135
136         void hold_device(unsigned index);
137         void release_device(unsigned index);  // Note: index is allowed to go out of bounds.
138
139         // If device is held, start or restart capture. If device is not held,
140         // stop capture if it isn't already.
141         void reset_device(unsigned index);
142
143         // Note: The card must be held. Returns OUTPUT_FREQUENCY if the card is in EMPTY or DEAD.
144         unsigned get_capture_frequency(unsigned index);
145
146         // Note: The card must be held.
147         Device::State get_card_state(unsigned index);
148
149         // Only for ALSAInput.
150         void set_card_state(unsigned index, Device::State state);
151
152         // Just a short form for taking <mu> and then moving the card to
153         // EMPTY or DEAD state. Only for ALSAInput and for internal use.
154         void free_card(unsigned index);
155
156         // Create a new card, mark it immediately as DEAD and hold it.
157         // Returns the new index.
158         unsigned create_dead_card(const std::string &name, const std::string &info, unsigned num_channels);
159
160         // Make a protobuf representation of the given card, so that it can be
161         // matched against at a later stage. For AudioMixer only.
162         // The given card must be held.
163         void serialize_device(unsigned index, DeviceSpecProto *serialized);
164
165 private:
166         mutable std::mutex mu;
167         std::vector<Device> devices;  // Under mu.
168         std::vector<std::unique_ptr<ALSAInput>> inputs;  // Under mu, corresponds 1:1 to devices.
169
170         // Keyed on device address (e.g. “hw:0,0”). If there's an entry here,
171         // it means we already have a thread doing retries, so we shouldn't
172         // start a new one.
173         std::unordered_map<std::string, unsigned> add_device_tries_left;  // Under add_device_mutex.
174         std::mutex add_device_mutex;
175
176         static constexpr int num_retries = 10;
177
178         void inotify_thread_func();
179         void enumerate_devices();
180
181         // Try to add an input at the given card/device. If it succeeds, return
182         // synchronously. If not, fire off a background thread to try up to
183         // <num_retries> times.
184         void probe_device_with_retry(unsigned card_index, unsigned dev_index);
185         void probe_device_retry_thread_func(unsigned card_index, unsigned dev_index);
186
187         enum class ProbeResult {
188                 SUCCESS,
189                 DEFER,
190                 FAILURE
191         };
192         ProbeResult probe_device_once(unsigned card_index, unsigned dev_index);
193
194         void unplug_device(unsigned card_index, unsigned dev_index);
195
196         // Must be called with <mu> held. Will allocate a new entry if needed.
197         // The returned entry will be set to READY state.
198         unsigned find_free_device_index(const std::string &name,
199                                         const std::string &info,
200                                         unsigned num_channels,
201                                         const std::string &address);
202
203         friend class ALSAInput;
204 };
205
206 #endif  // !defined(_ALSA_INPUT_H)