4 // The actual video mixer, running in its own separate background thread.
15 #include <condition_variable>
26 #include "audio_mixer.h"
27 #include "bmusb/bmusb.h"
30 #include "input_state.h"
32 #include "pbo_frame_allocator.h"
33 #include "ref_counted_frame.h"
34 #include "ref_counted_gl_sync.h"
37 #include "video_encoder.h"
40 class ChromaSubsampler;
52 // For any card that's not the master (where we pick out the frames as they
53 // come, as fast as we can process), there's going to be a queue. The question
54 // is when we should drop frames from that queue (apart from the obvious
55 // dropping if the 16-frame queue should become full), especially given that
56 // the frame rate could be lower or higher than the master (either subtly or
57 // dramatically). We have two (conflicting) demands:
59 // 1. We want to avoid starving the queue.
60 // 2. We don't want to add more delay than is needed.
62 // Our general strategy is to drop as many frames as we can (helping for #2)
63 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
64 // where we assume that if we have N frames in the queue, we're always safe from
65 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
66 // more than N frames in the queue after reading out the one we need, we head-drop
67 // them to reduce the queue.
69 // N is reduced as follows: If the queue has had at least one spare frame for
70 // at least 50 (master) frames (ie., it's been too conservative for a second),
71 // we reduce N by 1 and reset the timers.
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 {
78 QueueLengthPolicy() {}
79 void reset(unsigned card_index) {
80 this->card_index = card_index;
81 safe_queue_length = 1;
82 frames_with_at_least_one = 0;
83 been_at_safe_point_since_last_starvation = false;
86 void update_policy(unsigned queue_length); // Call before picking out a frame, so 0 means starvation.
87 unsigned get_safe_queue_length() const { return safe_queue_length; }
90 unsigned card_index; // For debugging only.
91 unsigned safe_queue_length = 1; // Called N in the comments. Can never go below 1.
92 unsigned frames_with_at_least_one = 0;
93 bool been_at_safe_point_since_last_starvation = false;
98 // The surface format is used for offscreen destinations for OpenGL contexts we need.
99 Mixer(const QSurfaceFormat &format, unsigned num_cards);
104 void transition_clicked(int transition_num);
105 void channel_clicked(int preview_num);
110 OUTPUT_INPUT0, // 1, 2, 3, up to 15 follow numerically.
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;
122 // Asserted when all the inputs are ready; you cannot render the chain
124 RefCountedGLsync ready_fence;
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;
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;
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);
140 typedef std::function<void()> new_frame_ready_callback_t;
141 void set_frame_ready_callback(Output output, new_frame_ready_callback_t callback)
143 output_channel[output].set_frame_ready_callback(callback);
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)
150 output_channel[output].set_transition_names_updated_callback(callback);
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)
156 output_channel[output].set_name_updated_callback(callback);
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)
162 output_channel[output].set_color_updated_callback(callback);
165 std::vector<std::string> get_transition_names()
167 return theme->get_transition_names(pts());
170 unsigned get_num_channels() const
172 return theme->get_num_channels();
175 std::string get_channel_name(unsigned channel) const
177 return theme->get_channel_name(channel);
180 std::string get_channel_color(unsigned channel) const
182 return theme->get_channel_color(channel);
185 int get_channel_signal(unsigned channel) const
187 return theme->get_channel_signal(channel);
190 int map_signal(unsigned channel)
192 return theme->map_signal(channel);
195 unsigned get_master_clock() const
197 return master_clock_channel;
200 void set_master_clock(unsigned channel)
202 master_clock_channel = channel;
205 void set_signal_mapping(int signal, int card)
207 return theme->set_signal_mapping(signal, card);
210 bool get_supports_set_wb(unsigned channel) const
212 return theme->get_supports_set_wb(channel);
215 void set_wb(unsigned channel, double r, double g, double b) const
217 theme->set_wb(channel, r, g, b);
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; }
229 unsigned get_num_cards() const { return num_cards; }
231 std::string get_card_description(unsigned card_index) const {
232 assert(card_index < num_cards);
233 return cards[card_index].capture->get_description();
236 // The difference between this and the previous function is that if a card
237 // is used as the current output, get_card_description() will return the
238 // fake card that's replacing it for input, whereas this function will return
239 // the card's actual name.
240 std::string get_output_card_description(unsigned card_index) const {
241 assert(card_can_be_used_as_output(card_index));
242 assert(card_index < num_cards);
243 if (cards[card_index].parked_capture) {
244 return cards[card_index].parked_capture->get_description();
246 return cards[card_index].capture->get_description();
250 bool card_can_be_used_as_output(unsigned card_index) const {
251 assert(card_index < num_cards);
252 return cards[card_index].output != nullptr;
255 std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
256 assert(card_index < num_cards);
257 return cards[card_index].capture->get_available_video_modes();
260 uint32_t get_current_video_mode(unsigned card_index) const {
261 assert(card_index < num_cards);
262 return cards[card_index].capture->get_current_video_mode();
265 void set_video_mode(unsigned card_index, uint32_t mode) {
266 assert(card_index < num_cards);
267 cards[card_index].capture->set_video_mode(mode);
270 void start_mode_scanning(unsigned card_index);
272 std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
273 assert(card_index < num_cards);
274 return cards[card_index].capture->get_available_video_inputs();
277 uint32_t get_current_video_input(unsigned card_index) const {
278 assert(card_index < num_cards);
279 return cards[card_index].capture->get_current_video_input();
282 void set_video_input(unsigned card_index, uint32_t input) {
283 assert(card_index < num_cards);
284 cards[card_index].capture->set_video_input(input);
287 std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
288 assert(card_index < num_cards);
289 return cards[card_index].capture->get_available_audio_inputs();
292 uint32_t get_current_audio_input(unsigned card_index) const {
293 assert(card_index < num_cards);
294 return cards[card_index].capture->get_current_audio_input();
297 void set_audio_input(unsigned card_index, uint32_t input) {
298 assert(card_index < num_cards);
299 cards[card_index].capture->set_audio_input(input);
302 void change_x264_bitrate(unsigned rate_kbit) {
303 video_encoder->change_x264_bitrate(rate_kbit);
306 int get_output_card_index() const { // -1 = no output, just stream.
307 return desired_output_card_index;
310 void set_output_card(int card_index) { // -1 = no output, just stream.
311 desired_output_card_index = card_index;
314 std::map<uint32_t, bmusb::VideoMode> get_available_output_video_modes() const;
316 uint32_t get_output_video_mode() const {
317 return desired_output_video_mode;
320 void set_output_video_mode(uint32_t mode) {
321 desired_output_video_mode = mode;
327 void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, bool is_fake_capture, DeckLinkOutput *output);
328 void set_output_card_internal(int card_index); // Should only be called from the mixer thread.
329 void bm_frame(unsigned card_index, uint16_t timecode,
330 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
331 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
332 void bm_hotplug_add(libusb_device *dev);
333 void bm_hotplug_remove(unsigned card_index);
334 void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
336 void handle_hotplugged_cards();
337 void schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame, bool is_preroll, std::chrono::steady_clock::time_point frame_timestamp);
338 void render_one_frame(int64_t duration);
339 void audio_thread_func();
340 void release_display_frame(DisplayFrame *frame);
341 double pts() { return double(pts_int) / TIMEBASE; }
342 // Call this _before_ trying to pull out a frame from a capture card;
343 // it will update the policy and drop the right amount of frames for you.
344 void trim_queue(CaptureCard *card, unsigned card_index);
349 QSurface *mixer_surface, *h264_encoder_surface, *decklink_output_surface;
350 std::unique_ptr<movit::ResourcePool> resource_pool;
351 std::unique_ptr<Theme> theme;
352 std::atomic<unsigned> audio_source_channel{0};
353 std::atomic<int> master_clock_channel{0}; // Gets overridden by <output_card_index> if set.
354 int output_card_index = -1; // -1 for none.
355 uint32_t output_video_mode = -1;
357 // The mechanics of changing the output card and modes are so intricately connected
358 // with the work the mixer thread is doing. Thus, we don't change it directly,
359 // we just set this variable instead, which signals to the mixer thread that
360 // it should do the change before the next frame. This simplifies locking
361 // considerations immensely.
362 std::atomic<int> desired_output_card_index{-1};
363 std::atomic<uint32_t> desired_output_video_mode{0};
365 std::unique_ptr<movit::EffectChain> display_chain;
366 std::unique_ptr<ChromaSubsampler> chroma_subsampler;
367 std::unique_ptr<VideoEncoder> video_encoder;
369 // Effects part of <display_chain>. Owned by <display_chain>.
370 movit::FlatInput *display_input;
372 int64_t pts_int = 0; // In TIMEBASE units.
374 // Accumulated errors in number of 1/TIMEBASE audio samples. If OUTPUT_FREQUENCY divided by
375 // frame rate is integer, will always stay zero.
376 unsigned fractional_samples = 0;
378 mutable std::mutex card_mutex;
379 bool has_bmusb_thread = false;
381 std::unique_ptr<bmusb::CaptureInterface> capture;
382 bool is_fake_capture;
383 std::unique_ptr<DeckLinkOutput> output;
385 // If this card is used for output (ie., output_card_index points to it),
386 // it cannot simultaneously be uesd for capture, so <capture> gets replaced
387 // by a FakeCapture. However, since reconstructing the real capture object
388 // with all its state can be annoying, it is not being deleted, just stopped
390 std::unique_ptr<bmusb::CaptureInterface> parked_capture;
392 std::unique_ptr<PBOFrameAllocator> frame_allocator;
394 // Stuff for the OpenGL context (for texture uploading).
395 QSurface *surface = nullptr;
398 RefCountedFrame frame;
399 int64_t length; // In TIMEBASE units.
401 unsigned field; // Which field (0 or 1) of the frame to use. Always 0 for progressive.
402 std::function<void()> upload_func; // Needs to be called to actually upload the texture to OpenGL.
403 unsigned dropped_frames = 0; // Number of dropped frames before this one.
404 std::chrono::steady_clock::time_point received_timestamp = std::chrono::steady_clock::time_point::min();
406 std::deque<NewFrame> new_frames;
407 bool should_quit = false;
408 std::condition_variable new_frames_changed; // Set whenever new_frames (or should_quit) is changed.
410 QueueLengthPolicy queue_length_policy; // Refers to the "new_frames" queue.
412 int last_timecode = -1; // Unwrapped.
414 CaptureCard cards[MAX_VIDEO_CARDS]; // Protected by <card_mutex>.
415 AudioMixer audio_mixer; // Same as global_audio_mixer (see audio_mixer.h).
416 bool input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const;
417 struct OutputFrameInfo {
418 int dropped_frames; // Since last frame.
419 int num_samples; // Audio samples needed for this output frame.
420 int64_t frame_duration; // In TIMEBASE units.
422 std::chrono::steady_clock::time_point frame_timestamp;
424 OutputFrameInfo get_one_frame_from_each_card(unsigned master_card_index, bool master_card_is_output, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS]);
426 InputState input_state;
428 // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
429 // Protected by its own mutex.
430 std::mutex hotplug_mutex;
431 std::vector<libusb_device *> hotplugged_cards;
433 class OutputChannel {
436 void output_frame(DisplayFrame frame);
437 bool get_display_frame(DisplayFrame *frame);
438 void set_frame_ready_callback(new_frame_ready_callback_t callback);
439 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
440 void set_name_updated_callback(name_updated_callback_t callback);
441 void set_color_updated_callback(color_updated_callback_t callback);
447 Mixer *parent = nullptr; // Not owned.
448 std::mutex frame_mutex;
449 DisplayFrame current_frame, ready_frame; // protected by <frame_mutex>
450 bool has_current_frame = false, has_ready_frame = false; // protected by <frame_mutex>
451 new_frame_ready_callback_t new_frame_ready_callback;
452 transition_names_updated_callback_t transition_names_updated_callback;
453 name_updated_callback_t name_updated_callback;
454 color_updated_callback_t color_updated_callback;
456 std::vector<std::string> last_transition_names;
457 std::string last_name, last_color;
459 OutputChannel output_channel[NUM_OUTPUTS];
461 std::thread mixer_thread;
462 std::thread audio_thread;
463 std::atomic<bool> should_quit{false};
464 std::atomic<bool> should_cut{false};
466 std::unique_ptr<ALSAOutput> alsa;
472 std::chrono::steady_clock::time_point frame_timestamp;
474 std::mutex audio_mutex;
475 std::condition_variable audio_task_queue_changed;
476 std::queue<AudioTask> audio_task_queue; // Under audio_mutex.
478 // For mode scanning.
479 bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
480 std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
481 unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
482 std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
485 extern Mixer *global_mixer;
486 extern bool uses_mlock;
488 #endif // !defined(_MIXER_H)