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