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