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