4 // The actual video mixer, running in its own separate background thread.
15 #include <condition_variable>
26 #include <movit/image_format.h>
28 #include "audio_mixer.h"
29 #include "bmusb/bmusb.h"
32 #include "input_state.h"
34 #include "pbo_frame_allocator.h"
35 #include "ref_counted_frame.h"
36 #include "ref_counted_gl_sync.h"
39 #include "video_encoder.h"
42 class ChromaSubsampler;
46 class TimecodeRenderer;
56 // For any card that's not the master (where we pick out the frames as they
57 // come, as fast as we can process), there's going to be a queue. The question
58 // is when we should drop frames from that queue (apart from the obvious
59 // dropping if the 16-frame queue should become full), especially given that
60 // the frame rate could be lower or higher than the master (either subtly or
61 // dramatically). We have two (conflicting) demands:
63 // 1. We want to avoid starving the queue.
64 // 2. We don't want to add more delay than is needed.
66 // Our general strategy is to drop as many frames as we can (helping for #2)
67 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
68 // where we assume that if we have N frames in the queue, we're always safe from
69 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
70 // more than N frames in the queue after reading out the one we need, we head-drop
71 // them to reduce the queue.
73 // N is reduced as follows: If the queue has had at least one spare frame for
74 // at least 50 (master) frames (ie., it's been too conservative for a second),
75 // we reduce N by 1 and reset the timers.
77 // Whenever the queue is starved (we needed a frame but there was none),
78 // and we've been at N since the last starvation, N was obviously too low,
79 // so we increment it. We will never set N above 5, though.
80 class QueueLengthPolicy {
82 QueueLengthPolicy() {}
83 void reset(unsigned card_index) {
84 this->card_index = card_index;
85 safe_queue_length = 1;
86 frames_with_at_least_one = 0;
87 been_at_safe_point_since_last_starvation = false;
90 void update_policy(unsigned queue_length); // Call before picking out a frame, so 0 means starvation.
91 unsigned get_safe_queue_length() const { return safe_queue_length; }
94 unsigned card_index; // For debugging only.
95 unsigned safe_queue_length = 1; // Called N in the comments. Can never go below 1.
96 unsigned frames_with_at_least_one = 0;
97 bool been_at_safe_point_since_last_starvation = false;
102 // The surface format is used for offscreen destinations for OpenGL contexts we need.
103 Mixer(const QSurfaceFormat &format, unsigned num_cards);
108 void transition_clicked(int transition_num);
109 void channel_clicked(int preview_num);
114 OUTPUT_INPUT0, // 1, 2, 3, up to 15 follow numerically.
118 struct DisplayFrame {
119 // The chain for rendering this frame. To render a display frame,
120 // first wait for <ready_fence>, then call <setup_chain>
121 // to wire up all the inputs, and then finally call
122 // chain->render_to_screen() or similar.
123 movit::EffectChain *chain;
124 std::function<void()> setup_chain;
126 // Asserted when all the inputs are ready; you cannot render the chain
128 RefCountedGLsync ready_fence;
130 // Holds on to all the input frames needed for this display frame,
131 // so they are not released while still rendering.
132 std::vector<RefCountedFrame> input_frames;
134 // Textures that should be released back to the resource pool
135 // when this frame disappears, if any.
136 // TODO: Refcount these as well?
137 std::vector<GLuint> temp_textures;
139 // Implicitly frees the previous one if there's a new frame available.
140 bool get_display_frame(Output output, DisplayFrame *frame) {
141 return output_channel[output].get_display_frame(frame);
144 // NOTE: Callbacks will be called with a mutex held, so you should probably
145 // not do real work in them.
146 typedef std::function<void()> new_frame_ready_callback_t;
147 void add_frame_ready_callback(Output output, void *key, new_frame_ready_callback_t callback)
149 output_channel[output].add_frame_ready_callback(key, callback);
152 void remove_frame_ready_callback(Output output, void *key)
154 output_channel[output].remove_frame_ready_callback(key);
157 // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
158 typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
159 void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
161 output_channel[output].set_transition_names_updated_callback(callback);
164 typedef std::function<void(const std::string &)> name_updated_callback_t;
165 void set_name_updated_callback(Output output, name_updated_callback_t callback)
167 output_channel[output].set_name_updated_callback(callback);
170 typedef std::function<void(const std::string &)> color_updated_callback_t;
171 void set_color_updated_callback(Output output, color_updated_callback_t callback)
173 output_channel[output].set_color_updated_callback(callback);
176 std::vector<std::string> get_transition_names()
178 return theme->get_transition_names(pts());
181 unsigned get_num_channels() const
183 return theme->get_num_channels();
186 std::string get_channel_name(unsigned channel) const
188 return theme->get_channel_name(channel);
191 std::string get_channel_color(unsigned channel) const
193 return theme->get_channel_color(channel);
196 int get_channel_signal(unsigned channel) const
198 return theme->get_channel_signal(channel);
201 int map_signal(unsigned channel)
203 return theme->map_signal(channel);
206 unsigned get_master_clock() const
208 return master_clock_channel;
211 void set_master_clock(unsigned channel)
213 master_clock_channel = channel;
216 void set_signal_mapping(int signal, int card)
218 return theme->set_signal_mapping(signal, card);
221 void get_input_ycbcr_interpretation(unsigned card_index, bool *ycbcr_coefficients_auto,
222 movit::YCbCrLumaCoefficients *ycbcr_coefficients, bool *full_range);
223 void set_input_ycbcr_interpretation(unsigned card_index, bool ycbcr_coefficients_auto,
224 movit::YCbCrLumaCoefficients ycbcr_coefficients, bool full_range);
226 bool get_supports_set_wb(unsigned channel) const
228 return theme->get_supports_set_wb(channel);
231 void set_wb(unsigned channel, double r, double g, double b) const
233 theme->set_wb(channel, r, g, b);
236 // Note: You can also get this through the global variable global_audio_mixer.
237 AudioMixer *get_audio_mixer() { return &audio_mixer; }
238 const AudioMixer *get_audio_mixer() const { return &audio_mixer; }
245 unsigned get_num_cards() const { return num_cards; }
247 std::string get_card_description(unsigned card_index) const {
248 assert(card_index < num_cards);
249 return cards[card_index].capture->get_description();
252 // The difference between this and the previous function is that if a card
253 // is used as the current output, get_card_description() will return the
254 // fake card that's replacing it for input, whereas this function will return
255 // the card's actual name.
256 std::string get_output_card_description(unsigned card_index) const {
257 assert(card_can_be_used_as_output(card_index));
258 assert(card_index < num_cards);
259 if (cards[card_index].parked_capture) {
260 return cards[card_index].parked_capture->get_description();
262 return cards[card_index].capture->get_description();
266 bool card_can_be_used_as_output(unsigned card_index) const {
267 assert(card_index < num_cards);
268 return cards[card_index].output != nullptr;
271 std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
272 assert(card_index < num_cards);
273 return cards[card_index].capture->get_available_video_modes();
276 uint32_t get_current_video_mode(unsigned card_index) const {
277 assert(card_index < num_cards);
278 return cards[card_index].capture->get_current_video_mode();
281 void set_video_mode(unsigned card_index, uint32_t mode) {
282 assert(card_index < num_cards);
283 cards[card_index].capture->set_video_mode(mode);
286 void start_mode_scanning(unsigned card_index);
288 std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
289 assert(card_index < num_cards);
290 return cards[card_index].capture->get_available_video_inputs();
293 uint32_t get_current_video_input(unsigned card_index) const {
294 assert(card_index < num_cards);
295 return cards[card_index].capture->get_current_video_input();
298 void set_video_input(unsigned card_index, uint32_t input) {
299 assert(card_index < num_cards);
300 cards[card_index].capture->set_video_input(input);
303 std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
304 assert(card_index < num_cards);
305 return cards[card_index].capture->get_available_audio_inputs();
308 uint32_t get_current_audio_input(unsigned card_index) const {
309 assert(card_index < num_cards);
310 return cards[card_index].capture->get_current_audio_input();
313 void set_audio_input(unsigned card_index, uint32_t input) {
314 assert(card_index < num_cards);
315 cards[card_index].capture->set_audio_input(input);
318 void change_x264_bitrate(unsigned rate_kbit) {
319 video_encoder->change_x264_bitrate(rate_kbit);
322 int get_output_card_index() const { // -1 = no output, just stream.
323 return desired_output_card_index;
326 void set_output_card(int card_index) { // -1 = no output, just stream.
327 desired_output_card_index = card_index;
330 std::map<uint32_t, bmusb::VideoMode> get_available_output_video_modes() const;
332 uint32_t get_output_video_mode() const {
333 return desired_output_video_mode;
336 void set_output_video_mode(uint32_t mode) {
337 desired_output_video_mode = mode;
340 void set_display_timecode_in_stream(bool enable) {
341 display_timecode_in_stream = enable;
344 void set_display_timecode_on_stdout(bool enable) {
345 display_timecode_on_stdout = enable;
351 enum class CardType {
356 void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, CardType card_type, DeckLinkOutput *output);
357 void set_output_card_internal(int card_index); // Should only be called from the mixer thread.
358 void bm_frame(unsigned card_index, uint16_t timecode,
359 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
360 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
361 void bm_hotplug_add(libusb_device *dev);
362 void bm_hotplug_remove(unsigned card_index);
363 void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
365 void handle_hotplugged_cards();
366 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);
367 std::string get_timecode_text() const;
368 void render_one_frame(int64_t duration);
369 void audio_thread_func();
370 void release_display_frame(DisplayFrame *frame);
371 double pts() { return double(pts_int) / TIMEBASE; }
372 // Call this _before_ trying to pull out a frame from a capture card;
373 // it will update the policy and drop the right amount of frames for you.
374 void trim_queue(CaptureCard *card, unsigned card_index);
377 unsigned num_cards, num_video_inputs;
379 QSurface *mixer_surface, *h264_encoder_surface, *decklink_output_surface;
380 std::unique_ptr<movit::ResourcePool> resource_pool;
381 std::unique_ptr<Theme> theme;
382 std::atomic<unsigned> audio_source_channel{0};
383 std::atomic<int> master_clock_channel{0}; // Gets overridden by <output_card_index> if set.
384 int output_card_index = -1; // -1 for none.
385 uint32_t output_video_mode = -1;
387 // The mechanics of changing the output card and modes are so intricately connected
388 // with the work the mixer thread is doing. Thus, we don't change it directly,
389 // we just set this variable instead, which signals to the mixer thread that
390 // it should do the change before the next frame. This simplifies locking
391 // considerations immensely.
392 std::atomic<int> desired_output_card_index{-1};
393 std::atomic<uint32_t> desired_output_video_mode{0};
395 std::unique_ptr<movit::EffectChain> display_chain;
396 std::unique_ptr<ChromaSubsampler> chroma_subsampler;
397 std::unique_ptr<v210Converter> v210_converter;
398 std::unique_ptr<VideoEncoder> video_encoder;
400 std::unique_ptr<TimecodeRenderer> timecode_renderer;
401 std::atomic<bool> display_timecode_in_stream{false};
402 std::atomic<bool> display_timecode_on_stdout{false};
404 // Effects part of <display_chain>. Owned by <display_chain>.
405 movit::YCbCrInput *display_input;
407 int64_t pts_int = 0; // In TIMEBASE units.
408 unsigned frame_num = 0;
410 // Accumulated errors in number of 1/TIMEBASE audio samples. If OUTPUT_FREQUENCY divided by
411 // frame rate is integer, will always stay zero.
412 unsigned fractional_samples = 0;
414 mutable std::mutex card_mutex;
415 bool has_bmusb_thread = false;
417 std::unique_ptr<bmusb::CaptureInterface> capture;
418 bool is_fake_capture;
419 std::unique_ptr<DeckLinkOutput> output;
421 // If this card is used for output (ie., output_card_index points to it),
422 // it cannot simultaneously be uesd for capture, so <capture> gets replaced
423 // by a FakeCapture. However, since reconstructing the real capture object
424 // with all its state can be annoying, it is not being deleted, just stopped
426 std::unique_ptr<bmusb::CaptureInterface> parked_capture;
428 std::unique_ptr<PBOFrameAllocator> frame_allocator;
430 // Stuff for the OpenGL context (for texture uploading).
431 QSurface *surface = nullptr;
434 RefCountedFrame frame;
435 int64_t length; // In TIMEBASE units.
437 unsigned field; // Which field (0 or 1) of the frame to use. Always 0 for progressive.
438 std::function<void()> upload_func; // Needs to be called to actually upload the texture to OpenGL.
439 unsigned dropped_frames = 0; // Number of dropped frames before this one.
440 std::chrono::steady_clock::time_point received_timestamp = std::chrono::steady_clock::time_point::min();
442 std::deque<NewFrame> new_frames;
443 bool should_quit = false;
444 std::condition_variable new_frames_changed; // Set whenever new_frames (or should_quit) is changed.
446 QueueLengthPolicy queue_length_policy; // Refers to the "new_frames" queue.
448 int last_timecode = -1; // Unwrapped.
450 bool ycbcr_coefficients_auto = true;
451 movit::YCbCrLumaCoefficients ycbcr_coefficients = movit::YCBCR_REC_709;
452 bool full_range = false;
454 CaptureCard cards[MAX_VIDEO_CARDS]; // Protected by <card_mutex>.
455 AudioMixer audio_mixer; // Same as global_audio_mixer (see audio_mixer.h).
456 bool input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const;
457 struct OutputFrameInfo {
458 int dropped_frames; // Since last frame.
459 int num_samples; // Audio samples needed for this output frame.
460 int64_t frame_duration; // In TIMEBASE units.
462 std::chrono::steady_clock::time_point frame_timestamp;
464 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]);
466 InputState input_state;
468 // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
469 // Protected by its own mutex.
470 std::mutex hotplug_mutex;
471 std::vector<libusb_device *> hotplugged_cards;
473 class OutputChannel {
476 void output_frame(DisplayFrame frame);
477 bool get_display_frame(DisplayFrame *frame);
478 void add_frame_ready_callback(void *key, new_frame_ready_callback_t callback);
479 void remove_frame_ready_callback(void *key);
480 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
481 void set_name_updated_callback(name_updated_callback_t callback);
482 void set_color_updated_callback(color_updated_callback_t callback);
488 Mixer *parent = nullptr; // Not owned.
489 std::mutex frame_mutex;
490 DisplayFrame current_frame, ready_frame; // protected by <frame_mutex>
491 bool has_current_frame = false, has_ready_frame = false; // protected by <frame_mutex>
492 std::map<void *, new_frame_ready_callback_t> new_frame_ready_callbacks; // protected by <frame_mutex>
493 transition_names_updated_callback_t transition_names_updated_callback;
494 name_updated_callback_t name_updated_callback;
495 color_updated_callback_t color_updated_callback;
497 std::vector<std::string> last_transition_names;
498 std::string last_name, last_color;
500 OutputChannel output_channel[NUM_OUTPUTS];
502 std::thread mixer_thread;
503 std::thread audio_thread;
504 std::atomic<bool> should_quit{false};
505 std::atomic<bool> should_cut{false};
507 std::unique_ptr<ALSAOutput> alsa;
513 std::chrono::steady_clock::time_point frame_timestamp;
515 std::mutex audio_mutex;
516 std::condition_variable audio_task_queue_changed;
517 std::queue<AudioTask> audio_task_queue; // Under audio_mutex.
519 // For mode scanning.
520 bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
521 std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
522 unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
523 std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
526 extern Mixer *global_mixer;
527 extern bool uses_mlock;
529 #endif // !defined(_MIXER_H)