4 // The actual video mixer, running in its own separate background thread.
11 #include <movit/effect_chain.h>
12 #include <movit/flat_input.h>
13 #include <zita-resampler/resampler.h>
15 #include <condition_variable>
24 #include "bmusb/bmusb.h"
25 #include "alsa_output.h"
26 #include "ebu_r128_proc.h"
27 #include "h264encode.h"
29 #include "pbo_frame_allocator.h"
30 #include "ref_counted_frame.h"
31 #include "ref_counted_gl_sync.h"
32 #include "resampling_queue.h"
35 #include "stereocompressor.h"
37 #include "input_state.h"
38 #include "correlation_measurer.h"
55 // For any card that's not the master (where we pick out the frames as they
56 // come, as fast as we can process), there's going to be a queue. The question
57 // is when we should drop frames from that queue (apart from the obvious
58 // dropping if the 16-frame queue should become full), especially given that
59 // the frame rate could be lower or higher than the master (either subtly or
60 // dramatically). We have two (conflicting) demands:
62 // 1. We want to avoid starving the queue.
63 // 2. We don't want to add more delay than is needed.
65 // Our general strategy is to drop as many frames as we can (helping for #2)
66 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
67 // where we assume that if we have N frames in the queue, we're always safe from
68 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
69 // more than N frames in the queue after reading out the one we need, we head-drop
70 // them to reduce the queue.
72 // N is reduced as follows: If the queue has had at least one spare frame for
73 // at least 50 (master) frames (ie., it's been too conservative for a second),
74 // we reduce N by 1 and reset the timers. TODO: Only do this if N ever actually
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 = 0;
86 frames_with_at_least_one = 0;
87 been_at_safe_point_since_last_starvation = false;
90 void update_policy(int queue_length); // Give in -1 for starvation.
91 unsigned get_safe_queue_length() const { return safe_queue_length; }
94 unsigned card_index; // For debugging only.
95 unsigned safe_queue_length = 0; // Called N in the comments.
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 typedef std::function<void()> new_frame_ready_callback_t;
145 void set_frame_ready_callback(Output output, new_frame_ready_callback_t callback)
147 output_channel[output].set_frame_ready_callback(callback);
150 typedef std::function<void(float level_lufs, float peak_db,
151 float global_level_lufs, float range_low_lufs, float range_high_lufs,
152 float gain_staging_db, float final_makeup_gain_db,
153 float correlation)> audio_level_callback_t;
154 void set_audio_level_callback(audio_level_callback_t callback)
156 audio_level_callback = callback;
159 std::vector<std::string> get_transition_names()
161 return theme->get_transition_names(pts());
164 unsigned get_num_channels() const
166 return theme->get_num_channels();
169 std::string get_channel_name(unsigned channel) const
171 return theme->get_channel_name(channel);
174 std::string get_channel_color(unsigned channel) const
176 return theme->get_channel_color(channel);
179 int get_channel_signal(unsigned channel) const
181 return theme->get_channel_signal(channel);
184 int map_signal(unsigned channel)
186 return theme->map_signal(channel);
189 unsigned get_audio_source() const
191 return audio_source_channel;
194 void set_audio_source(unsigned channel)
196 audio_source_channel = channel;
199 unsigned get_master_clock() const
201 return master_clock_channel;
204 void set_master_clock(unsigned channel)
206 master_clock_channel = channel;
209 void set_signal_mapping(int signal, int card)
211 return theme->set_signal_mapping(signal, card);
214 bool get_supports_set_wb(unsigned channel) const
216 return theme->get_supports_set_wb(channel);
219 void set_wb(unsigned channel, double r, double g, double b) const
221 theme->set_wb(channel, r, g, b);
224 void set_locut_cutoff(float cutoff_hz)
226 locut_cutoff_hz = cutoff_hz;
229 void set_locut_enabled(bool enabled)
231 locut_enabled = enabled;
234 float get_limiter_threshold_dbfs()
236 return limiter_threshold_dbfs;
239 float get_compressor_threshold_dbfs()
241 return compressor_threshold_dbfs;
244 void set_limiter_threshold_dbfs(float threshold_dbfs)
246 limiter_threshold_dbfs = threshold_dbfs;
249 void set_compressor_threshold_dbfs(float threshold_dbfs)
251 compressor_threshold_dbfs = threshold_dbfs;
254 void set_limiter_enabled(bool enabled)
256 limiter_enabled = enabled;
259 void set_compressor_enabled(bool enabled)
261 compressor_enabled = enabled;
264 void set_gain_staging_db(float gain_db)
266 std::unique_lock<std::mutex> lock(compressor_mutex);
267 level_compressor_enabled = false;
268 gain_staging_db = gain_db;
271 void set_gain_staging_auto(bool enabled)
273 std::unique_lock<std::mutex> lock(compressor_mutex);
274 level_compressor_enabled = enabled;
277 void set_final_makeup_gain_db(float gain_db)
279 std::unique_lock<std::mutex> lock(compressor_mutex);
280 final_makeup_gain_auto = false;
281 final_makeup_gain = pow(10.0f, gain_db / 20.0f);
284 void set_final_makeup_gain_auto(bool enabled)
286 std::unique_lock<std::mutex> lock(compressor_mutex);
287 final_makeup_gain_auto = enabled;
297 unsigned get_num_cards() const { return num_cards; }
299 std::string get_card_description(unsigned card_index) const {
300 assert(card_index < num_cards);
301 return cards[card_index].capture->get_description();
304 std::map<uint32_t, VideoMode> get_available_video_modes(unsigned card_index) const {
305 assert(card_index < num_cards);
306 return cards[card_index].capture->get_available_video_modes();
309 uint32_t get_current_video_mode(unsigned card_index) const {
310 assert(card_index < num_cards);
311 return cards[card_index].capture->get_current_video_mode();
314 void set_video_mode(unsigned card_index, uint32_t mode) {
315 assert(card_index < num_cards);
316 cards[card_index].capture->set_video_mode(mode);
319 void start_mode_scanning(unsigned card_index);
321 std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
322 assert(card_index < num_cards);
323 return cards[card_index].capture->get_available_video_inputs();
326 uint32_t get_current_video_input(unsigned card_index) const {
327 assert(card_index < num_cards);
328 return cards[card_index].capture->get_current_video_input();
331 void set_video_input(unsigned card_index, uint32_t input) {
332 assert(card_index < num_cards);
333 cards[card_index].capture->set_video_input(input);
336 std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
337 assert(card_index < num_cards);
338 return cards[card_index].capture->get_available_audio_inputs();
341 uint32_t get_current_audio_input(unsigned card_index) const {
342 assert(card_index < num_cards);
343 return cards[card_index].capture->get_current_audio_input();
346 void set_audio_input(unsigned card_index, uint32_t input) {
347 assert(card_index < num_cards);
348 cards[card_index].capture->set_audio_input(input);
352 void configure_card(unsigned card_index, const QSurfaceFormat &format, CaptureInterface *capture);
353 void bm_frame(unsigned card_index, uint16_t timecode,
354 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
355 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format);
356 void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
358 void schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame);
359 void render_one_frame();
360 void send_audio_level_callback();
361 void audio_thread_func();
362 void process_audio_one_frame(int64_t frame_pts_int, int num_samples);
363 void subsample_chroma(GLuint src_tex, GLuint dst_dst);
364 void release_display_frame(DisplayFrame *frame);
365 double pts() { return double(pts_int) / TIMEBASE; }
370 QSurface *mixer_surface, *h264_encoder_surface;
371 std::unique_ptr<movit::ResourcePool> resource_pool;
372 std::unique_ptr<Theme> theme;
373 std::atomic<unsigned> audio_source_channel{0};
374 std::atomic<unsigned> master_clock_channel{0};
375 std::unique_ptr<movit::EffectChain> display_chain;
376 GLuint cbcr_program_num; // Owned by <resource_pool>.
377 GLuint cbcr_vbo; // Holds position and texcoord data.
378 GLuint cbcr_position_attribute_index, cbcr_texcoord_attribute_index;
379 std::unique_ptr<H264Encoder> h264_encoder;
381 // Effects part of <display_chain>. Owned by <display_chain>.
382 movit::FlatInput *display_input;
384 int64_t pts_int = 0; // In TIMEBASE units.
386 std::mutex bmusb_mutex;
388 CaptureInterface *capture;
389 std::unique_ptr<PBOFrameAllocator> frame_allocator;
391 // Stuff for the OpenGL context (for texture uploading).
393 QOpenGLContext *context;
396 RefCountedFrame frame;
397 int64_t length; // In TIMEBASE units.
399 unsigned field; // Which field (0 or 1) of the frame to use. Always 0 for progressive.
400 RefCountedGLsync ready_fence; // Whether frame is ready for rendering.
401 unsigned dropped_frames = 0; // Number of dropped frames before this one.
403 std::queue<NewFrame> new_frames;
404 bool should_quit = false;
405 std::condition_variable new_frames_changed; // Set whenever new_frames (or should_quit) is changed.
407 QueueLengthPolicy queue_length_policy; // Refers to the "new_frames" queue.
409 // Accumulated errors in number of 1/TIMEBASE samples. If OUTPUT_FREQUENCY divided by
410 // frame rate is integer, will always stay zero.
411 unsigned fractional_samples = 0;
413 std::mutex audio_mutex;
414 std::unique_ptr<ResamplingQueue> resampling_queue; // Under audio_mutex.
415 int last_timecode = -1; // Unwrapped.
416 int64_t next_local_pts = 0; // Beginning of next frame, in TIMEBASE units.
418 CaptureCard cards[MAX_CARDS]; // protected by <bmusb_mutex>
419 void get_one_frame_from_each_card(unsigned master_card_index, CaptureCard::NewFrame new_frames[MAX_CARDS], bool has_new_frame[MAX_CARDS], int num_samples[MAX_CARDS]);
421 InputState input_state;
423 class OutputChannel {
426 void output_frame(DisplayFrame frame);
427 bool get_display_frame(DisplayFrame *frame);
428 void set_frame_ready_callback(new_frame_ready_callback_t callback);
433 Mixer *parent = nullptr; // Not owned.
434 std::mutex frame_mutex;
435 DisplayFrame current_frame, ready_frame; // protected by <frame_mutex>
436 bool has_current_frame = false, has_ready_frame = false; // protected by <frame_mutex>
437 new_frame_ready_callback_t new_frame_ready_callback;
438 bool has_new_frame_ready_callback = false;
440 OutputChannel output_channel[NUM_OUTPUTS];
442 std::thread mixer_thread;
443 std::thread audio_thread;
444 std::atomic<bool> should_quit{false};
445 std::atomic<bool> should_cut{false};
447 audio_level_callback_t audio_level_callback = nullptr;
448 std::mutex compressor_mutex;
449 Ebu_r128_proc r128; // Under compressor_mutex.
450 CorrelationMeasurer correlation; // Under compressor_mutex.
452 Resampler peak_resampler;
453 std::atomic<float> peak{0.0f};
455 StereoFilter locut; // Default cutoff 120 Hz, 24 dB/oct.
456 std::atomic<float> locut_cutoff_hz;
457 std::atomic<bool> locut_enabled{true};
459 // First compressor; takes us up to about -12 dBFS.
460 StereoCompressor level_compressor; // Under compressor_mutex. Used to set/override gain_staging_db if <level_compressor_enabled>.
461 float gain_staging_db = 0.0f; // Under compressor_mutex.
462 bool level_compressor_enabled = true; // Under compressor_mutex.
464 static constexpr float ref_level_dbfs = -14.0f; // Chosen so that we end up around 0 LU in practice.
465 static constexpr float ref_level_lufs = -23.0f; // 0 LU, more or less by definition.
467 StereoCompressor limiter;
468 std::atomic<float> limiter_threshold_dbfs{ref_level_dbfs + 4.0f}; // 4 dB.
469 std::atomic<bool> limiter_enabled{true};
470 StereoCompressor compressor;
471 std::atomic<float> compressor_threshold_dbfs{ref_level_dbfs - 12.0f}; // -12 dB.
472 std::atomic<bool> compressor_enabled{true};
474 double final_makeup_gain = 1.0; // Under compressor_mutex. Read/write by the user. Note: Not in dB, we want the numeric precision so that we can change it slowly.
475 bool final_makeup_gain_auto = true; // Under compressor_mutex.
477 std::unique_ptr<ALSAOutput> alsa;
483 std::mutex audio_mutex;
484 std::condition_variable audio_task_queue_changed;
485 std::queue<AudioTask> audio_task_queue; // Under audio_mutex.
487 // For mode scanning.
488 bool is_mode_scanning[MAX_CARDS]{ false };
489 std::vector<uint32_t> mode_scanlist[MAX_CARDS];
490 unsigned mode_scanlist_index[MAX_CARDS]{ 0 };
491 timespec last_mode_scan_change[MAX_CARDS];
494 extern Mixer *global_mixer;
496 #endif // !defined(_MIXER_H)