]> git.sesse.net Git - nageru/blob - mixer.h
Rename bmusb_mutex to card_mutex; it is not really bound to bmusb anymore.
[nageru] / mixer.h
1 #ifndef _MIXER_H
2 #define _MIXER_H 1
3
4 // The actual video mixer, running in its own separate background thread.
5
6 #include <assert.h>
7 #include <epoxy/gl.h>
8
9 #undef Success
10
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include <atomic>
14 #include <chrono>
15 #include <condition_variable>
16 #include <cstddef>
17 #include <functional>
18 #include <map>
19 #include <memory>
20 #include <mutex>
21 #include <queue>
22 #include <string>
23 #include <thread>
24 #include <vector>
25
26 #include "audio_mixer.h"
27 #include "bmusb/bmusb.h"
28 #include "defs.h"
29 #include "httpd.h"
30 #include "input_state.h"
31 #include "libusb.h"
32 #include "pbo_frame_allocator.h"
33 #include "ref_counted_frame.h"
34 #include "ref_counted_gl_sync.h"
35 #include "theme.h"
36 #include "timebase.h"
37 #include "video_encoder.h"
38
39 class ALSAOutput;
40 class ChromaSubsampler;
41 class QSurface;
42 class QSurfaceFormat;
43
44 namespace movit {
45 class Effect;
46 class EffectChain;
47 class FlatInput;
48 class ResourcePool;
49 }  // namespace movit
50
51 // For any card that's not the master (where we pick out the frames as they
52 // come, as fast as we can process), there's going to be a queue. The question
53 // is when we should drop frames from that queue (apart from the obvious
54 // dropping if the 16-frame queue should become full), especially given that
55 // the frame rate could be lower or higher than the master (either subtly or
56 // dramatically). We have two (conflicting) demands:
57 //
58 //   1. We want to avoid starving the queue.
59 //   2. We don't want to add more delay than is needed.
60 //
61 // Our general strategy is to drop as many frames as we can (helping for #2)
62 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
63 // where we assume that if we have N frames in the queue, we're always safe from
64 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
65 // more than N frames in the queue after reading out the one we need, we head-drop
66 // them to reduce the queue.
67 //
68 // N is reduced as follows: If the queue has had at least one spare frame for
69 // at least 50 (master) frames (ie., it's been too conservative for a second),
70 // we reduce N by 1 and reset the timers. TODO: Only do this if N ever actually
71 // touched the limit.
72 //
73 // Whenever the queue is starved (we needed a frame but there was none),
74 // and we've been at N since the last starvation, N was obviously too low,
75 // so we increment it. We will never set N above 5, though.
76 class QueueLengthPolicy {
77 public:
78         QueueLengthPolicy() {}
79         void reset(unsigned card_index) {
80                 this->card_index = card_index;
81                 safe_queue_length = 0;
82                 frames_with_at_least_one = 0;
83                 been_at_safe_point_since_last_starvation = false;
84         }
85
86         void update_policy(int queue_length);  // Give in -1 for starvation.
87         unsigned get_safe_queue_length() const { return safe_queue_length; }
88
89 private:
90         unsigned card_index;  // For debugging only.
91         unsigned safe_queue_length = 0;  // Called N in the comments.
92         unsigned frames_with_at_least_one = 0;
93         bool been_at_safe_point_since_last_starvation = false;
94 };
95
96 class Mixer {
97 public:
98         // The surface format is used for offscreen destinations for OpenGL contexts we need.
99         Mixer(const QSurfaceFormat &format, unsigned num_cards);
100         ~Mixer();
101         void start();
102         void quit();
103
104         void transition_clicked(int transition_num);
105         void channel_clicked(int preview_num);
106
107         enum Output {
108                 OUTPUT_LIVE = 0,
109                 OUTPUT_PREVIEW,
110                 OUTPUT_INPUT0,  // 1, 2, 3, up to 15 follow numerically.
111                 NUM_OUTPUTS = 18
112         };
113
114         struct DisplayFrame {
115                 // The chain for rendering this frame. To render a display frame,
116                 // first wait for <ready_fence>, then call <setup_chain>
117                 // to wire up all the inputs, and then finally call
118                 // chain->render_to_screen() or similar.
119                 movit::EffectChain *chain;
120                 std::function<void()> setup_chain;
121
122                 // Asserted when all the inputs are ready; you cannot render the chain
123                 // before this.
124                 RefCountedGLsync ready_fence;
125
126                 // Holds on to all the input frames needed for this display frame,
127                 // so they are not released while still rendering.
128                 std::vector<RefCountedFrame> input_frames;
129
130                 // Textures that should be released back to the resource pool
131                 // when this frame disappears, if any.
132                 // TODO: Refcount these as well?
133                 std::vector<GLuint> temp_textures;
134         };
135         // Implicitly frees the previous one if there's a new frame available.
136         bool get_display_frame(Output output, DisplayFrame *frame) {
137                 return output_channel[output].get_display_frame(frame);
138         }
139
140         typedef std::function<void()> new_frame_ready_callback_t;
141         void set_frame_ready_callback(Output output, new_frame_ready_callback_t callback)
142         {
143                 output_channel[output].set_frame_ready_callback(callback);
144         }
145
146         // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
147         typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
148         void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
149         {
150                 output_channel[output].set_transition_names_updated_callback(callback);
151         }
152
153         typedef std::function<void(const std::string &)> name_updated_callback_t;
154         void set_name_updated_callback(Output output, name_updated_callback_t callback)
155         {
156                 output_channel[output].set_name_updated_callback(callback);
157         }
158
159         typedef std::function<void(const std::string &)> color_updated_callback_t;
160         void set_color_updated_callback(Output output, color_updated_callback_t callback)
161         {
162                 output_channel[output].set_color_updated_callback(callback);
163         }
164
165         std::vector<std::string> get_transition_names()
166         {
167                 return theme->get_transition_names(pts());
168         }
169
170         unsigned get_num_channels() const
171         {
172                 return theme->get_num_channels();
173         }
174
175         std::string get_channel_name(unsigned channel) const
176         {
177                 return theme->get_channel_name(channel);
178         }
179
180         std::string get_channel_color(unsigned channel) const
181         {
182                 return theme->get_channel_color(channel);
183         }
184
185         int get_channel_signal(unsigned channel) const
186         {
187                 return theme->get_channel_signal(channel);
188         }
189
190         int map_signal(unsigned channel)
191         {
192                 return theme->map_signal(channel);
193         }
194
195         unsigned get_master_clock() const
196         {
197                 return master_clock_channel;
198         }
199
200         void set_master_clock(unsigned channel)
201         {
202                 master_clock_channel = channel;
203         }
204
205         void set_signal_mapping(int signal, int card)
206         {
207                 return theme->set_signal_mapping(signal, card);
208         }
209
210         bool get_supports_set_wb(unsigned channel) const
211         {
212                 return theme->get_supports_set_wb(channel);
213         }
214
215         void set_wb(unsigned channel, double r, double g, double b) const
216         {
217                 theme->set_wb(channel, r, g, b);
218         }
219
220         // Note: You can also get this through the global variable global_audio_mixer.
221         AudioMixer *get_audio_mixer() { return &audio_mixer; }
222         const AudioMixer *get_audio_mixer() const { return &audio_mixer; }
223
224         void schedule_cut()
225         {
226                 should_cut = true;
227         }
228
229         unsigned get_num_cards() const { return num_cards; }
230
231         std::string get_card_description(unsigned card_index) const {
232                 assert(card_index < num_cards);
233                 return cards[card_index].capture->get_description();
234         }
235
236         std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
237                 assert(card_index < num_cards);
238                 return cards[card_index].capture->get_available_video_modes();
239         }
240
241         uint32_t get_current_video_mode(unsigned card_index) const {
242                 assert(card_index < num_cards);
243                 return cards[card_index].capture->get_current_video_mode();
244         }
245
246         void set_video_mode(unsigned card_index, uint32_t mode) {
247                 assert(card_index < num_cards);
248                 cards[card_index].capture->set_video_mode(mode);
249         }
250
251         void start_mode_scanning(unsigned card_index);
252
253         std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
254                 assert(card_index < num_cards);
255                 return cards[card_index].capture->get_available_video_inputs();
256         }
257
258         uint32_t get_current_video_input(unsigned card_index) const {
259                 assert(card_index < num_cards);
260                 return cards[card_index].capture->get_current_video_input();
261         }
262
263         void set_video_input(unsigned card_index, uint32_t input) {
264                 assert(card_index < num_cards);
265                 cards[card_index].capture->set_video_input(input);
266         }
267
268         std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
269                 assert(card_index < num_cards);
270                 return cards[card_index].capture->get_available_audio_inputs();
271         }
272
273         uint32_t get_current_audio_input(unsigned card_index) const {
274                 assert(card_index < num_cards);
275                 return cards[card_index].capture->get_current_audio_input();
276         }
277
278         void set_audio_input(unsigned card_index, uint32_t input) {
279                 assert(card_index < num_cards);
280                 cards[card_index].capture->set_audio_input(input);
281         }
282
283         void change_x264_bitrate(unsigned rate_kbit) {
284                 video_encoder->change_x264_bitrate(rate_kbit);
285         }
286
287 private:
288         void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, bool is_fake_capture);
289         void bm_frame(unsigned card_index, uint16_t timecode,
290                 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
291                 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
292         void bm_hotplug_add(libusb_device *dev);
293         void bm_hotplug_remove(unsigned card_index);
294         void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
295         void thread_func();
296         void handle_hotplugged_cards();
297         void schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame);
298         void render_one_frame(int64_t duration);
299         void audio_thread_func();
300         void release_display_frame(DisplayFrame *frame);
301         double pts() { return double(pts_int) / TIMEBASE; }
302
303         HTTPD httpd;
304         unsigned num_cards;
305
306         QSurface *mixer_surface, *h264_encoder_surface;
307         std::unique_ptr<movit::ResourcePool> resource_pool;
308         std::unique_ptr<Theme> theme;
309         std::atomic<unsigned> audio_source_channel{0};
310         std::atomic<unsigned> master_clock_channel{0};
311         std::unique_ptr<movit::EffectChain> display_chain;
312         std::unique_ptr<ChromaSubsampler> chroma_subsampler;
313         std::unique_ptr<VideoEncoder> video_encoder;
314
315         // Effects part of <display_chain>. Owned by <display_chain>.
316         movit::FlatInput *display_input;
317
318         int64_t pts_int = 0;  // In TIMEBASE units.
319
320         // Accumulated errors in number of 1/TIMEBASE audio samples. If OUTPUT_FREQUENCY divided by
321         // frame rate is integer, will always stay zero.
322         unsigned fractional_samples = 0;
323
324         std::mutex card_mutex;
325         bool has_bmusb_thread = false;
326         struct CaptureCard {
327                 bmusb::CaptureInterface *capture = nullptr;
328                 bool is_fake_capture;
329                 std::unique_ptr<PBOFrameAllocator> frame_allocator;
330
331                 // Stuff for the OpenGL context (for texture uploading).
332                 QSurface *surface = nullptr;
333
334                 struct NewFrame {
335                         RefCountedFrame frame;
336                         int64_t length;  // In TIMEBASE units.
337                         bool interlaced;
338                         unsigned field;  // Which field (0 or 1) of the frame to use. Always 0 for progressive.
339                         std::function<void()> upload_func;  // Needs to be called to actually upload the texture to OpenGL.
340                         unsigned dropped_frames = 0;  // Number of dropped frames before this one.
341                         std::chrono::steady_clock::time_point received_timestamp = std::chrono::steady_clock::time_point::min();
342                 };
343                 std::queue<NewFrame> new_frames;
344                 bool should_quit = false;
345                 std::condition_variable new_frames_changed;  // Set whenever new_frames (or should_quit) is changed.
346
347                 QueueLengthPolicy queue_length_policy;  // Refers to the "new_frames" queue.
348
349                 int last_timecode = -1;  // Unwrapped.
350         };
351         CaptureCard cards[MAX_VIDEO_CARDS];  // Protected by <card_mutex>.
352         AudioMixer audio_mixer;  // Same as global_audio_mixer (see audio_mixer.h).
353         struct OutputFrameInfo {
354                 int dropped_frames;  // Since last frame.
355                 int num_samples;  // Audio samples needed for this output frame.
356                 int64_t frame_duration;  // In TIMEBASE units.
357         };
358         OutputFrameInfo get_one_frame_from_each_card(unsigned master_card_index, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS]);
359
360         InputState input_state;
361
362         // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
363         // Protected by its own mutex.
364         std::mutex hotplug_mutex;
365         std::vector<libusb_device *> hotplugged_cards;
366
367         class OutputChannel {
368         public:
369                 ~OutputChannel();
370                 void output_frame(DisplayFrame frame);
371                 bool get_display_frame(DisplayFrame *frame);
372                 void set_frame_ready_callback(new_frame_ready_callback_t callback);
373                 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
374                 void set_name_updated_callback(name_updated_callback_t callback);
375                 void set_color_updated_callback(color_updated_callback_t callback);
376
377         private:
378                 friend class Mixer;
379
380                 unsigned channel;
381                 Mixer *parent = nullptr;  // Not owned.
382                 std::mutex frame_mutex;
383                 DisplayFrame current_frame, ready_frame;  // protected by <frame_mutex>
384                 bool has_current_frame = false, has_ready_frame = false;  // protected by <frame_mutex>
385                 new_frame_ready_callback_t new_frame_ready_callback;
386                 transition_names_updated_callback_t transition_names_updated_callback;
387                 name_updated_callback_t name_updated_callback;
388                 color_updated_callback_t color_updated_callback;
389
390                 std::vector<std::string> last_transition_names;
391                 std::string last_name, last_color;
392         };
393         OutputChannel output_channel[NUM_OUTPUTS];
394
395         std::thread mixer_thread;
396         std::thread audio_thread;
397         std::atomic<bool> should_quit{false};
398         std::atomic<bool> should_cut{false};
399
400         std::unique_ptr<ALSAOutput> alsa;
401
402         struct AudioTask {
403                 int64_t pts_int;
404                 int num_samples;
405                 bool adjust_rate;
406         };
407         std::mutex audio_mutex;
408         std::condition_variable audio_task_queue_changed;
409         std::queue<AudioTask> audio_task_queue;  // Under audio_mutex.
410
411         // For mode scanning.
412         bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
413         std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
414         unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
415         std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
416 };
417
418 extern Mixer *global_mixer;
419 extern bool uses_mlock;
420
421 #endif  // !defined(_MIXER_H)