]> git.sesse.net Git - bmusb/blob - bmusb/bmusb.h
22a6655b21da12792d9a4069bf415b7bfdb521ec
[bmusb] / bmusb / bmusb.h
1 #ifndef _BMUSB_H
2 #define _BMUSB_H
3
4 #include <libusb.h>
5 #include <stdint.h>
6 #include <atomic>
7 #include <condition_variable>
8 #include <deque>
9 #include <functional>
10 #include <map>
11 #include <mutex>
12 #include <stack>
13 #include <string>
14 #include <thread>
15 #include <vector>
16
17 namespace bmusb {
18
19 class BMUSBCapture;
20
21 // An interface for frame allocators; if you do not specify one
22 // (using set_video_frame_allocator), a default one that pre-allocates
23 // a freelist of eight frames using new[] will be used. Specifying
24 // your own can be useful if you have special demands for where you want the
25 // frame to end up and don't want to spend the extra copy to get it there, for
26 // instance GPU memory.
27 class FrameAllocator {
28  public:
29         struct Frame {
30                 uint8_t *data = nullptr;
31                 uint8_t *data2 = nullptr;  // Only if interleaved == true.
32                 size_t len = 0;  // Number of bytes we actually have.
33                 size_t size = 0;  // Number of bytes we have room for.
34                 size_t overflow = 0;
35                 void *userdata = nullptr;
36                 FrameAllocator *owner = nullptr;
37
38                 // If set to true, every other byte will go to data and to data2.
39                 // If so, <len> and <size> are still about the number of total bytes
40                 // so if size == 1024, there's 512 bytes in data and 512 in data2.
41                 bool interleaved = false;
42         };
43
44         virtual ~FrameAllocator();
45
46         // Request a video frame. Note that this is called from the
47         // USB thread, which runs with realtime priority and is
48         // very sensitive to delays. Thus, you should not do anything
49         // here that might sleep, including calling malloc().
50         // (Taking a mutex is borderline.)
51         //
52         // The Frame object will be given to the frame callback,
53         // which is responsible for releasing the video frame back
54         // once it is usable for new frames (ie., it will no longer
55         // be read from). You can use the "userdata" pointer for
56         // whatever you want to identify this frame if you need to.
57         //
58         // Returning a Frame with data==nullptr is allowed;
59         // if so, the frame in progress will be dropped.
60         virtual Frame alloc_frame() = 0;
61
62         virtual void release_frame(Frame frame) = 0;
63 };
64
65 // Audio is more important than video, and also much cheaper.
66 // By having many more audio frames available, hopefully if something
67 // starts to drop, we'll have CPU load go down (from not having to
68 // process as much video) before we have to drop audio.
69 #define NUM_QUEUED_VIDEO_FRAMES 16
70 #define NUM_QUEUED_AUDIO_FRAMES 64
71
72 class MallocFrameAllocator : public FrameAllocator {
73 public:
74         MallocFrameAllocator(size_t frame_size, size_t num_queued_frames);
75         Frame alloc_frame() override;
76         void release_frame(Frame frame) override;
77
78 private:
79         size_t frame_size;
80
81         std::mutex freelist_mutex;
82         std::stack<std::unique_ptr<uint8_t[]>> freelist;  // All of size <frame_size>.
83 };
84
85 // Represents an input mode you can tune a card to.
86 struct VideoMode {
87         std::string name;
88         bool autodetect = false;  // If true, all the remaining fields are irrelevant.
89         unsigned width = 0, height = 0;
90         unsigned frame_rate_num = 0, frame_rate_den = 0;
91         bool interlaced = false;
92 };
93
94 // Represents the format of an actual frame coming in.
95 // Note: Frame rate is _frame_ rate, not field rate. So 1080i60 gets 30/1, _not_ 60/1.
96 // "second_field_start" is only valid for interlaced modes; it signifies
97 // how many lines from the very top of the frame there are before the second field
98 // starts (so it will always be >= height/2 + extra_lines_top).
99 struct VideoFormat {
100         uint16_t id = 0;  // For debugging/logging only.
101         unsigned width = 0, height = 0, second_field_start = 0;
102         unsigned extra_lines_top = 0, extra_lines_bottom = 0;
103         unsigned frame_rate_nom = 0, frame_rate_den = 0;
104         bool interlaced = false;
105         bool has_signal = false;
106         bool is_connected = true;  // If false, then has_signal makes no sense.
107 };
108
109 struct AudioFormat {
110         uint16_t id = 0;  // For debugging/logging only.
111         unsigned bits_per_sample = 0;
112         unsigned num_channels = 0;
113 };
114
115 typedef std::function<void(uint16_t timecode,
116                            FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
117                            FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)>
118         frame_callback_t;
119
120 typedef std::function<void(libusb_device *dev)> card_connected_callback_t;
121 typedef std::function<void()> card_disconnected_callback_t;
122
123 class CaptureInterface {
124  public:
125         virtual ~CaptureInterface() {}
126
127         virtual std::map<uint32_t, VideoMode> get_available_video_modes() const = 0;
128         virtual uint32_t get_current_video_mode() const = 0;
129         virtual void set_video_mode(uint32_t video_mode_id) = 0;
130
131         virtual std::map<uint32_t, std::string> get_available_video_inputs() const = 0;
132         virtual void set_video_input(uint32_t video_input_id) = 0;
133         virtual uint32_t get_current_video_input() const = 0;
134
135         virtual std::map<uint32_t, std::string> get_available_audio_inputs() const = 0;
136         virtual void set_audio_input(uint32_t audio_input_id) = 0;
137         virtual uint32_t get_current_audio_input() const = 0;
138
139         // Does not take ownership.
140         virtual void set_video_frame_allocator(FrameAllocator *allocator) = 0;
141
142         virtual FrameAllocator *get_video_frame_allocator() = 0;
143
144         // Does not take ownership.
145         virtual void set_audio_frame_allocator(FrameAllocator *allocator) = 0;
146
147         virtual FrameAllocator *get_audio_frame_allocator() = 0;
148
149         virtual void set_frame_callback(frame_callback_t callback) = 0;
150
151         // Needs to be run before configure_card().
152         virtual void set_dequeue_thread_callbacks(std::function<void()> init, std::function<void()> cleanup) = 0;
153
154         // Only valid after configure_card().
155         virtual std::string get_description() const = 0;
156
157         virtual void configure_card() = 0;
158
159         virtual void start_bm_capture() = 0;
160
161         virtual void stop_dequeue_thread() = 0;
162
163         // If a card is disconnected, it cannot come back; you should call stop_dequeue_thread()
164         // and delete it.
165         virtual bool get_disconnected() const = 0;
166 };
167
168 // The actual capturing class, representing capture from a single card.
169 class BMUSBCapture : public CaptureInterface {
170  public:
171         BMUSBCapture(int card_index, libusb_device *dev = nullptr)
172                 : card_index(card_index), dev(dev)
173         {
174         }
175
176         ~BMUSBCapture() {}
177
178         // Note: Cards could be unplugged and replugged between this call and
179         // actually opening the card (in configure_card()).
180         static int num_cards();
181
182         std::map<uint32_t, VideoMode> get_available_video_modes() const override;
183         uint32_t get_current_video_mode() const override;
184         void set_video_mode(uint32_t video_mode_id) override;
185
186         virtual std::map<uint32_t, std::string> get_available_video_inputs() const override;
187         virtual void set_video_input(uint32_t video_input_id) override;
188         virtual uint32_t get_current_video_input() const override { return current_video_input; }
189
190         virtual std::map<uint32_t, std::string> get_available_audio_inputs() const override;
191         virtual void set_audio_input(uint32_t audio_input_id) override;
192         virtual uint32_t get_current_audio_input() const override { return current_audio_input; }
193
194         // Does not take ownership.
195         void set_video_frame_allocator(FrameAllocator *allocator) override
196         {
197                 video_frame_allocator = allocator;
198                 if (owned_video_frame_allocator.get() != allocator) {
199                         owned_video_frame_allocator.reset();
200                 }
201         }
202
203         FrameAllocator *get_video_frame_allocator() override
204         {
205                 return video_frame_allocator;
206         }
207
208         // Does not take ownership.
209         void set_audio_frame_allocator(FrameAllocator *allocator) override
210         {
211                 audio_frame_allocator = allocator;
212                 if (owned_audio_frame_allocator.get() != allocator) {
213                         owned_audio_frame_allocator.reset();
214                 }
215         }
216
217         FrameAllocator *get_audio_frame_allocator() override
218         {
219                 return audio_frame_allocator;
220         }
221
222         void set_frame_callback(frame_callback_t callback) override
223         {
224                 frame_callback = callback;
225         }
226
227         // Needs to be run before configure_card().
228         void set_dequeue_thread_callbacks(std::function<void()> init, std::function<void()> cleanup) override
229         {
230                 dequeue_init_callback = init;
231                 dequeue_cleanup_callback = cleanup;
232                 has_dequeue_callbacks = true;
233         }
234
235         // Only valid after configure_card().
236         std::string get_description() const override {
237                 return description;
238         }
239
240         void configure_card() override;
241         void start_bm_capture() override;
242         void stop_dequeue_thread() override;
243         bool get_disconnected() const override { return disconnected; }
244
245         // TODO: It's rather messy to have these outside the interface.
246         static void start_bm_thread();
247         static void stop_bm_thread();
248
249         // Hotplug event (for devices being inserted between start_bm_thread()
250         // and stop_bm_thread()); entirely optional, but must be set before
251         // start_bm_capture(). Note that your callback should do as little work
252         // as possible, since the callback comes from the main USB handling
253         // thread, which is very time-sensitive.
254         //
255         // The callback function transfers ownership. If you don't want to hold
256         // on to the device given to you in the callback, you need to call
257         // libusb_unref_device().
258         static void set_card_connected_callback(card_connected_callback_t callback,
259                                                 bool hotplug_existing_devices_arg = false)
260         {
261                 card_connected_callback = callback;
262                 hotplug_existing_devices = hotplug_existing_devices_arg;
263         }
264
265         // Similar to set_card_connected_callback(), with the same caveats.
266         // (Note that this is set per-card and not global, as it is logically
267         // connected to an existing BMUSBCapture object.)
268         void set_card_disconnected_callback(card_disconnected_callback_t callback)
269         {
270                 card_disconnected_callback = callback;
271         }
272
273  private:
274         struct QueuedFrame {
275                 uint16_t timecode;
276                 uint16_t format;
277                 FrameAllocator::Frame frame;
278         };
279
280         void start_new_audio_block(const uint8_t *start);
281         void start_new_frame(const uint8_t *start);
282
283         void queue_frame(uint16_t format, uint16_t timecode, FrameAllocator::Frame frame, std::deque<QueuedFrame> *q);
284         void dequeue_thread_func();
285
286         static void usb_thread_func();
287         static void cb_xfr(struct libusb_transfer *xfr);
288         static int cb_hotplug(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data);
289
290         void update_capture_mode();
291
292         std::string description;
293
294         FrameAllocator::Frame current_video_frame;
295         FrameAllocator::Frame current_audio_frame;
296
297         std::mutex queue_lock;
298         std::condition_variable queues_not_empty;
299         std::deque<QueuedFrame> pending_video_frames;
300         std::deque<QueuedFrame> pending_audio_frames;
301
302         FrameAllocator *video_frame_allocator = nullptr;
303         FrameAllocator *audio_frame_allocator = nullptr;
304         std::unique_ptr<FrameAllocator> owned_video_frame_allocator;
305         std::unique_ptr<FrameAllocator> owned_audio_frame_allocator;
306         frame_callback_t frame_callback = nullptr;
307         static card_connected_callback_t card_connected_callback;
308         static bool hotplug_existing_devices;
309         card_disconnected_callback_t card_disconnected_callback = nullptr;
310
311         std::thread dequeue_thread;
312         std::atomic<bool> dequeue_thread_should_quit;
313         bool has_dequeue_callbacks = false;
314         std::function<void()> dequeue_init_callback = nullptr;
315         std::function<void()> dequeue_cleanup_callback = nullptr;
316
317         int current_register = 0;
318
319         static constexpr int NUM_BMUSB_REGISTERS = 60;
320         uint8_t register_file[NUM_BMUSB_REGISTERS];
321
322         // If <dev> is nullptr, will choose device number <card_index> from the list
323         // of available devices on the system. <dev> is not used after configure_card()
324         // (it will be unref-ed).
325         int card_index = -1;
326         libusb_device *dev = nullptr;
327
328         std::vector<libusb_transfer *> iso_xfrs;
329         int assumed_frame_width = 1280;
330
331         libusb_device_handle *devh = nullptr;
332         uint32_t current_video_input = 0x00000000;  // HDMI/SDI.
333         uint32_t current_audio_input = 0x00000000;  // Embedded.
334
335         bool disconnected = false;
336 };
337
338 }  // namespace bmusb
339
340 #endif