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;
44 class TimecodeRenderer;
54 // For any card that's not the master (where we pick out the frames as they
55 // come, as fast as we can process), there's going to be a queue. The question
56 // is when we should drop frames from that queue (apart from the obvious
57 // dropping if the 16-frame queue should become full), especially given that
58 // the frame rate could be lower or higher than the master (either subtly or
59 // dramatically). We have two (conflicting) demands:
61 // 1. We want to avoid starving the queue.
62 // 2. We don't want to add more delay than is needed.
64 // Our general strategy is to drop as many frames as we can (helping for #2)
65 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
66 // where we assume that if we have N frames in the queue, we're always safe from
67 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
68 // more than N frames in the queue after reading out the one we need, we head-drop
69 // them to reduce the queue.
71 // N is reduced as follows: If the queue has had at least one spare frame for
72 // at least 50 (master) frames (ie., it's been too conservative for a second),
73 // we reduce N by 1 and reset the timers.
75 // Whenever the queue is starved (we needed a frame but there was none),
76 // and we've been at N since the last starvation, N was obviously too low,
77 // so we increment it. We will never set N above 5, though.
78 class QueueLengthPolicy {
80 QueueLengthPolicy() {}
81 void reset(unsigned card_index) {
82 this->card_index = card_index;
83 safe_queue_length = 1;
84 frames_with_at_least_one = 0;
85 been_at_safe_point_since_last_starvation = false;
88 void update_policy(unsigned queue_length); // Call before picking out a frame, so 0 means starvation.
89 unsigned get_safe_queue_length() const { return safe_queue_length; }
92 unsigned card_index; // For debugging only.
93 unsigned safe_queue_length = 1; // Called N in the comments. Can never go below 1.
94 unsigned frames_with_at_least_one = 0;
95 bool been_at_safe_point_since_last_starvation = false;
100 // The surface format is used for offscreen destinations for OpenGL contexts we need.
101 Mixer(const QSurfaceFormat &format, unsigned num_cards);
106 void transition_clicked(int transition_num);
107 void channel_clicked(int preview_num);
112 OUTPUT_INPUT0, // 1, 2, 3, up to 15 follow numerically.
116 struct DisplayFrame {
117 // The chain for rendering this frame. To render a display frame,
118 // first wait for <ready_fence>, then call <setup_chain>
119 // to wire up all the inputs, and then finally call
120 // chain->render_to_screen() or similar.
121 movit::EffectChain *chain;
122 std::function<void()> setup_chain;
124 // Asserted when all the inputs are ready; you cannot render the chain
126 RefCountedGLsync ready_fence;
128 // Holds on to all the input frames needed for this display frame,
129 // so they are not released while still rendering.
130 std::vector<RefCountedFrame> input_frames;
132 // Textures that should be released back to the resource pool
133 // when this frame disappears, if any.
134 // TODO: Refcount these as well?
135 std::vector<GLuint> temp_textures;
137 // Implicitly frees the previous one if there's a new frame available.
138 bool get_display_frame(Output output, DisplayFrame *frame) {
139 return output_channel[output].get_display_frame(frame);
142 typedef std::function<void()> new_frame_ready_callback_t;
143 void set_frame_ready_callback(Output output, new_frame_ready_callback_t callback)
145 output_channel[output].set_frame_ready_callback(callback);
148 // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
149 typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
150 void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
152 output_channel[output].set_transition_names_updated_callback(callback);
155 typedef std::function<void(const std::string &)> name_updated_callback_t;
156 void set_name_updated_callback(Output output, name_updated_callback_t callback)
158 output_channel[output].set_name_updated_callback(callback);
161 typedef std::function<void(const std::string &)> color_updated_callback_t;
162 void set_color_updated_callback(Output output, color_updated_callback_t callback)
164 output_channel[output].set_color_updated_callback(callback);
167 std::vector<std::string> get_transition_names()
169 return theme->get_transition_names(pts());
172 unsigned get_num_channels() const
174 return theme->get_num_channels();
177 std::string get_channel_name(unsigned channel) const
179 return theme->get_channel_name(channel);
182 std::string get_channel_color(unsigned channel) const
184 return theme->get_channel_color(channel);
187 int get_channel_signal(unsigned channel) const
189 return theme->get_channel_signal(channel);
192 int map_signal(unsigned channel)
194 return theme->map_signal(channel);
197 unsigned get_master_clock() const
199 return master_clock_channel;
202 void set_master_clock(unsigned channel)
204 master_clock_channel = channel;
207 void set_signal_mapping(int signal, int card)
209 return theme->set_signal_mapping(signal, card);
212 bool get_supports_set_wb(unsigned channel) const
214 return theme->get_supports_set_wb(channel);
217 void set_wb(unsigned channel, double r, double g, double b) const
219 theme->set_wb(channel, r, g, b);
222 // Note: You can also get this through the global variable global_audio_mixer.
223 AudioMixer *get_audio_mixer() { return &audio_mixer; }
224 const AudioMixer *get_audio_mixer() const { return &audio_mixer; }
231 unsigned get_num_cards() const { return num_cards; }
233 std::string get_card_description(unsigned card_index) const {
234 assert(card_index < num_cards);
235 return cards[card_index].capture->get_description();
238 // The difference between this and the previous function is that if a card
239 // is used as the current output, get_card_description() will return the
240 // fake card that's replacing it for input, whereas this function will return
241 // the card's actual name.
242 std::string get_output_card_description(unsigned card_index) const {
243 assert(card_can_be_used_as_output(card_index));
244 assert(card_index < num_cards);
245 if (cards[card_index].parked_capture) {
246 return cards[card_index].parked_capture->get_description();
248 return cards[card_index].capture->get_description();
252 bool card_can_be_used_as_output(unsigned card_index) const {
253 assert(card_index < num_cards);
254 return cards[card_index].output != nullptr;
257 std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
258 assert(card_index < num_cards);
259 return cards[card_index].capture->get_available_video_modes();
262 uint32_t get_current_video_mode(unsigned card_index) const {
263 assert(card_index < num_cards);
264 return cards[card_index].capture->get_current_video_mode();
267 void set_video_mode(unsigned card_index, uint32_t mode) {
268 assert(card_index < num_cards);
269 cards[card_index].capture->set_video_mode(mode);
272 void start_mode_scanning(unsigned card_index);
274 std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
275 assert(card_index < num_cards);
276 return cards[card_index].capture->get_available_video_inputs();
279 uint32_t get_current_video_input(unsigned card_index) const {
280 assert(card_index < num_cards);
281 return cards[card_index].capture->get_current_video_input();
284 void set_video_input(unsigned card_index, uint32_t input) {
285 assert(card_index < num_cards);
286 cards[card_index].capture->set_video_input(input);
289 std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
290 assert(card_index < num_cards);
291 return cards[card_index].capture->get_available_audio_inputs();
294 uint32_t get_current_audio_input(unsigned card_index) const {
295 assert(card_index < num_cards);
296 return cards[card_index].capture->get_current_audio_input();
299 void set_audio_input(unsigned card_index, uint32_t input) {
300 assert(card_index < num_cards);
301 cards[card_index].capture->set_audio_input(input);
304 void change_x264_bitrate(unsigned rate_kbit) {
305 video_encoder->change_x264_bitrate(rate_kbit);
308 int get_output_card_index() const { // -1 = no output, just stream.
309 return desired_output_card_index;
312 void set_output_card(int card_index) { // -1 = no output, just stream.
313 desired_output_card_index = card_index;
316 std::map<uint32_t, bmusb::VideoMode> get_available_output_video_modes() const;
318 uint32_t get_output_video_mode() const {
319 return desired_output_video_mode;
322 void set_output_video_mode(uint32_t mode) {
323 desired_output_video_mode = mode;
326 void set_display_timecode_in_stream(bool enable) {
327 display_timecode_in_stream = enable;
330 void set_display_timecode_on_stdout(bool enable) {
331 display_timecode_on_stdout = enable;
337 enum class CardType {
342 void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, CardType card_type, DeckLinkOutput *output);
343 void set_output_card_internal(int card_index); // Should only be called from the mixer thread.
344 void bm_frame(unsigned card_index, uint16_t timecode,
345 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
346 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
347 void bm_hotplug_add(libusb_device *dev);
348 void bm_hotplug_remove(unsigned card_index);
349 void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
351 void handle_hotplugged_cards();
352 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);
353 std::string get_timecode_text() const;
354 void render_one_frame(int64_t duration);
355 void audio_thread_func();
356 void release_display_frame(DisplayFrame *frame);
357 double pts() { return double(pts_int) / TIMEBASE; }
358 // Call this _before_ trying to pull out a frame from a capture card;
359 // it will update the policy and drop the right amount of frames for you.
360 void trim_queue(CaptureCard *card, unsigned card_index);
363 unsigned num_cards, num_video_inputs;
365 QSurface *mixer_surface, *h264_encoder_surface, *decklink_output_surface;
366 std::unique_ptr<movit::ResourcePool> resource_pool;
367 std::unique_ptr<Theme> theme;
368 std::atomic<unsigned> audio_source_channel{0};
369 std::atomic<int> master_clock_channel{0}; // Gets overridden by <output_card_index> if set.
370 int output_card_index = -1; // -1 for none.
371 uint32_t output_video_mode = -1;
373 // The mechanics of changing the output card and modes are so intricately connected
374 // with the work the mixer thread is doing. Thus, we don't change it directly,
375 // we just set this variable instead, which signals to the mixer thread that
376 // it should do the change before the next frame. This simplifies locking
377 // considerations immensely.
378 std::atomic<int> desired_output_card_index{-1};
379 std::atomic<uint32_t> desired_output_video_mode{0};
381 std::unique_ptr<movit::EffectChain> display_chain;
382 std::unique_ptr<ChromaSubsampler> chroma_subsampler;
383 std::unique_ptr<v210Converter> v210_converter;
384 std::unique_ptr<VideoEncoder> video_encoder;
386 std::unique_ptr<TimecodeRenderer> timecode_renderer;
387 std::atomic<bool> display_timecode_in_stream{false};
388 std::atomic<bool> display_timecode_on_stdout{false};
390 // Effects part of <display_chain>. Owned by <display_chain>.
391 movit::YCbCrInput *display_input;
393 int64_t pts_int = 0; // In TIMEBASE units.
394 unsigned frame_num = 0;
396 // Accumulated errors in number of 1/TIMEBASE audio samples. If OUTPUT_FREQUENCY divided by
397 // frame rate is integer, will always stay zero.
398 unsigned fractional_samples = 0;
400 mutable std::mutex card_mutex;
401 bool has_bmusb_thread = false;
403 std::unique_ptr<bmusb::CaptureInterface> capture;
404 bool is_fake_capture;
405 std::unique_ptr<DeckLinkOutput> output;
407 // If this card is used for output (ie., output_card_index points to it),
408 // it cannot simultaneously be uesd for capture, so <capture> gets replaced
409 // by a FakeCapture. However, since reconstructing the real capture object
410 // with all its state can be annoying, it is not being deleted, just stopped
412 std::unique_ptr<bmusb::CaptureInterface> parked_capture;
414 std::unique_ptr<PBOFrameAllocator> frame_allocator;
416 // Stuff for the OpenGL context (for texture uploading).
417 QSurface *surface = nullptr;
420 RefCountedFrame frame;
421 int64_t length; // In TIMEBASE units.
423 unsigned field; // Which field (0 or 1) of the frame to use. Always 0 for progressive.
424 std::function<void()> upload_func; // Needs to be called to actually upload the texture to OpenGL.
425 unsigned dropped_frames = 0; // Number of dropped frames before this one.
426 std::chrono::steady_clock::time_point received_timestamp = std::chrono::steady_clock::time_point::min();
428 std::deque<NewFrame> new_frames;
429 bool should_quit = false;
430 std::condition_variable new_frames_changed; // Set whenever new_frames (or should_quit) is changed.
432 QueueLengthPolicy queue_length_policy; // Refers to the "new_frames" queue.
434 int last_timecode = -1; // Unwrapped.
436 CaptureCard cards[MAX_VIDEO_CARDS]; // Protected by <card_mutex>.
437 AudioMixer audio_mixer; // Same as global_audio_mixer (see audio_mixer.h).
438 bool input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const;
439 struct OutputFrameInfo {
440 int dropped_frames; // Since last frame.
441 int num_samples; // Audio samples needed for this output frame.
442 int64_t frame_duration; // In TIMEBASE units.
444 std::chrono::steady_clock::time_point frame_timestamp;
446 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]);
448 InputState input_state;
450 // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
451 // Protected by its own mutex.
452 std::mutex hotplug_mutex;
453 std::vector<libusb_device *> hotplugged_cards;
455 class OutputChannel {
458 void output_frame(DisplayFrame frame);
459 bool get_display_frame(DisplayFrame *frame);
460 void set_frame_ready_callback(new_frame_ready_callback_t callback);
461 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
462 void set_name_updated_callback(name_updated_callback_t callback);
463 void set_color_updated_callback(color_updated_callback_t callback);
469 Mixer *parent = nullptr; // Not owned.
470 std::mutex frame_mutex;
471 DisplayFrame current_frame, ready_frame; // protected by <frame_mutex>
472 bool has_current_frame = false, has_ready_frame = false; // protected by <frame_mutex>
473 new_frame_ready_callback_t new_frame_ready_callback;
474 transition_names_updated_callback_t transition_names_updated_callback;
475 name_updated_callback_t name_updated_callback;
476 color_updated_callback_t color_updated_callback;
478 std::vector<std::string> last_transition_names;
479 std::string last_name, last_color;
481 OutputChannel output_channel[NUM_OUTPUTS];
483 std::thread mixer_thread;
484 std::thread audio_thread;
485 std::atomic<bool> should_quit{false};
486 std::atomic<bool> should_cut{false};
488 std::unique_ptr<ALSAOutput> alsa;
494 std::chrono::steady_clock::time_point frame_timestamp;
496 std::mutex audio_mutex;
497 std::condition_variable audio_task_queue_changed;
498 std::queue<AudioTask> audio_task_queue; // Under audio_mutex.
500 // For mode scanning.
501 bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
502 std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
503 unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
504 std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
507 extern Mixer *global_mixer;
508 extern bool uses_mlock;
510 #endif // !defined(_MIXER_H)