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