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;
42 class TimecodeRenderer;
53 // For any card that's not the master (where we pick out the frames as they
54 // come, as fast as we can process), there's going to be a queue. The question
55 // is when we should drop frames from that queue (apart from the obvious
56 // dropping if the 16-frame queue should become full), especially given that
57 // the frame rate could be lower or higher than the master (either subtly or
58 // dramatically). We have two (conflicting) demands:
60 // 1. We want to avoid starving the queue.
61 // 2. We don't want to add more delay than is needed.
63 // Our general strategy is to drop as many frames as we can (helping for #2)
64 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
65 // where we assume that if we have N frames in the queue, we're always safe from
66 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
67 // more than N frames in the queue after reading out the one we need, we head-drop
68 // them to reduce the queue.
70 // N is reduced as follows: If the queue has had at least one spare frame for
71 // at least 50 (master) frames (ie., it's been too conservative for a second),
72 // we reduce N by 1 and reset the timers.
74 // Whenever the queue is starved (we needed a frame but there was none),
75 // and we've been at N since the last starvation, N was obviously too low,
76 // so we increment it. We will never set N above 5, though.
77 class QueueLengthPolicy {
79 QueueLengthPolicy() {}
80 void reset(unsigned card_index) {
81 this->card_index = card_index;
82 safe_queue_length = 1;
83 frames_with_at_least_one = 0;
84 been_at_safe_point_since_last_starvation = false;
87 void update_policy(unsigned queue_length); // Call before picking out a frame, so 0 means starvation.
88 unsigned get_safe_queue_length() const { return safe_queue_length; }
91 unsigned card_index; // For debugging only.
92 unsigned safe_queue_length = 1; // Called N in the comments. Can never go below 1.
93 unsigned frames_with_at_least_one = 0;
94 bool been_at_safe_point_since_last_starvation = false;
99 // The surface format is used for offscreen destinations for OpenGL contexts we need.
100 Mixer(const QSurfaceFormat &format, unsigned num_cards);
105 void transition_clicked(int transition_num);
106 void channel_clicked(int preview_num);
111 OUTPUT_INPUT0, // 1, 2, 3, up to 15 follow numerically.
115 struct DisplayFrame {
116 // The chain for rendering this frame. To render a display frame,
117 // first wait for <ready_fence>, then call <setup_chain>
118 // to wire up all the inputs, and then finally call
119 // chain->render_to_screen() or similar.
120 movit::EffectChain *chain;
121 std::function<void()> setup_chain;
123 // Asserted when all the inputs are ready; you cannot render the chain
125 RefCountedGLsync ready_fence;
127 // Holds on to all the input frames needed for this display frame,
128 // so they are not released while still rendering.
129 std::vector<RefCountedFrame> input_frames;
131 // Textures that should be released back to the resource pool
132 // when this frame disappears, if any.
133 // TODO: Refcount these as well?
134 std::vector<GLuint> temp_textures;
136 // Implicitly frees the previous one if there's a new frame available.
137 bool get_display_frame(Output output, DisplayFrame *frame) {
138 return output_channel[output].get_display_frame(frame);
141 typedef std::function<void()> new_frame_ready_callback_t;
142 void set_frame_ready_callback(Output output, new_frame_ready_callback_t callback)
144 output_channel[output].set_frame_ready_callback(callback);
147 // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
148 typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
149 void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
151 output_channel[output].set_transition_names_updated_callback(callback);
154 typedef std::function<void(const std::string &)> name_updated_callback_t;
155 void set_name_updated_callback(Output output, name_updated_callback_t callback)
157 output_channel[output].set_name_updated_callback(callback);
160 typedef std::function<void(const std::string &)> color_updated_callback_t;
161 void set_color_updated_callback(Output output, color_updated_callback_t callback)
163 output_channel[output].set_color_updated_callback(callback);
166 std::vector<std::string> get_transition_names()
168 return theme->get_transition_names(pts());
171 unsigned get_num_channels() const
173 return theme->get_num_channels();
176 std::string get_channel_name(unsigned channel) const
178 return theme->get_channel_name(channel);
181 std::string get_channel_color(unsigned channel) const
183 return theme->get_channel_color(channel);
186 int get_channel_signal(unsigned channel) const
188 return theme->get_channel_signal(channel);
191 int map_signal(unsigned channel)
193 return theme->map_signal(channel);
196 unsigned get_master_clock() const
198 return master_clock_channel;
201 void set_master_clock(unsigned channel)
203 master_clock_channel = channel;
206 void set_signal_mapping(int signal, int card)
208 return theme->set_signal_mapping(signal, card);
211 bool get_supports_set_wb(unsigned channel) const
213 return theme->get_supports_set_wb(channel);
216 void set_wb(unsigned channel, double r, double g, double b) const
218 theme->set_wb(channel, r, g, b);
221 // Note: You can also get this through the global variable global_audio_mixer.
222 AudioMixer *get_audio_mixer() { return &audio_mixer; }
223 const AudioMixer *get_audio_mixer() const { return &audio_mixer; }
230 unsigned get_num_cards() const { return num_cards; }
232 std::string get_card_description(unsigned card_index) const {
233 assert(card_index < num_cards);
234 return cards[card_index].capture->get_description();
237 // The difference between this and the previous function is that if a card
238 // is used as the current output, get_card_description() will return the
239 // fake card that's replacing it for input, whereas this function will return
240 // the card's actual name.
241 std::string get_output_card_description(unsigned card_index) const {
242 assert(card_can_be_used_as_output(card_index));
243 assert(card_index < num_cards);
244 if (cards[card_index].parked_capture) {
245 return cards[card_index].parked_capture->get_description();
247 return cards[card_index].capture->get_description();
251 bool card_can_be_used_as_output(unsigned card_index) const {
252 assert(card_index < num_cards);
253 return cards[card_index].output != nullptr;
256 std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
257 assert(card_index < num_cards);
258 return cards[card_index].capture->get_available_video_modes();
261 uint32_t get_current_video_mode(unsigned card_index) const {
262 assert(card_index < num_cards);
263 return cards[card_index].capture->get_current_video_mode();
266 void set_video_mode(unsigned card_index, uint32_t mode) {
267 assert(card_index < num_cards);
268 cards[card_index].capture->set_video_mode(mode);
271 void start_mode_scanning(unsigned card_index);
273 std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
274 assert(card_index < num_cards);
275 return cards[card_index].capture->get_available_video_inputs();
278 uint32_t get_current_video_input(unsigned card_index) const {
279 assert(card_index < num_cards);
280 return cards[card_index].capture->get_current_video_input();
283 void set_video_input(unsigned card_index, uint32_t input) {
284 assert(card_index < num_cards);
285 cards[card_index].capture->set_video_input(input);
288 std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
289 assert(card_index < num_cards);
290 return cards[card_index].capture->get_available_audio_inputs();
293 uint32_t get_current_audio_input(unsigned card_index) const {
294 assert(card_index < num_cards);
295 return cards[card_index].capture->get_current_audio_input();
298 void set_audio_input(unsigned card_index, uint32_t input) {
299 assert(card_index < num_cards);
300 cards[card_index].capture->set_audio_input(input);
303 void change_x264_bitrate(unsigned rate_kbit) {
304 video_encoder->change_x264_bitrate(rate_kbit);
307 int get_output_card_index() const { // -1 = no output, just stream.
308 return desired_output_card_index;
311 void set_output_card(int card_index) { // -1 = no output, just stream.
312 desired_output_card_index = card_index;
315 std::map<uint32_t, bmusb::VideoMode> get_available_output_video_modes() const;
317 uint32_t get_output_video_mode() const {
318 return desired_output_video_mode;
321 void set_output_video_mode(uint32_t mode) {
322 desired_output_video_mode = mode;
325 void set_display_timecode_in_stream(bool enable) {
326 display_timecode_in_stream = enable;
329 void set_display_timecode_on_stdout(bool enable) {
330 display_timecode_on_stdout = enable;
336 void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, bool is_fake_capture, DeckLinkOutput *output);
337 void set_output_card_internal(int card_index); // Should only be called from the mixer thread.
338 void bm_frame(unsigned card_index, uint16_t timecode,
339 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
340 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
341 void bm_hotplug_add(libusb_device *dev);
342 void bm_hotplug_remove(unsigned card_index);
343 void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
345 void handle_hotplugged_cards();
346 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);
347 std::string get_timecode_text() const;
348 void render_one_frame(int64_t duration);
349 void audio_thread_func();
350 void release_display_frame(DisplayFrame *frame);
351 double pts() { return double(pts_int) / TIMEBASE; }
352 // Call this _before_ trying to pull out a frame from a capture card;
353 // it will update the policy and drop the right amount of frames for you.
354 void trim_queue(CaptureCard *card, unsigned card_index);
359 QSurface *mixer_surface, *h264_encoder_surface, *decklink_output_surface;
360 std::unique_ptr<movit::ResourcePool> resource_pool;
361 std::unique_ptr<Theme> theme;
362 std::atomic<unsigned> audio_source_channel{0};
363 std::atomic<int> master_clock_channel{0}; // Gets overridden by <output_card_index> if set.
364 int output_card_index = -1; // -1 for none.
365 uint32_t output_video_mode = -1;
367 // The mechanics of changing the output card and modes are so intricately connected
368 // with the work the mixer thread is doing. Thus, we don't change it directly,
369 // we just set this variable instead, which signals to the mixer thread that
370 // it should do the change before the next frame. This simplifies locking
371 // considerations immensely.
372 std::atomic<int> desired_output_card_index{-1};
373 std::atomic<uint32_t> desired_output_video_mode{0};
375 std::unique_ptr<movit::EffectChain> display_chain;
376 std::unique_ptr<ChromaSubsampler> chroma_subsampler;
377 std::unique_ptr<VideoEncoder> video_encoder;
379 std::unique_ptr<TimecodeRenderer> timecode_renderer;
380 std::atomic<bool> display_timecode_in_stream{false};
381 std::atomic<bool> display_timecode_on_stdout{false};
383 // Effects part of <display_chain>. Owned by <display_chain>.
384 movit::FlatInput *display_input;
386 int64_t pts_int = 0; // In TIMEBASE units.
387 unsigned frame_num = 0;
389 // Accumulated errors in number of 1/TIMEBASE audio samples. If OUTPUT_FREQUENCY divided by
390 // frame rate is integer, will always stay zero.
391 unsigned fractional_samples = 0;
393 mutable std::mutex card_mutex;
394 bool has_bmusb_thread = false;
396 std::unique_ptr<bmusb::CaptureInterface> capture;
397 bool is_fake_capture;
398 std::unique_ptr<DeckLinkOutput> output;
400 // If this card is used for output (ie., output_card_index points to it),
401 // it cannot simultaneously be uesd for capture, so <capture> gets replaced
402 // by a FakeCapture. However, since reconstructing the real capture object
403 // with all its state can be annoying, it is not being deleted, just stopped
405 std::unique_ptr<bmusb::CaptureInterface> parked_capture;
407 std::unique_ptr<PBOFrameAllocator> frame_allocator;
409 // Stuff for the OpenGL context (for texture uploading).
410 QSurface *surface = nullptr;
413 RefCountedFrame frame;
414 int64_t length; // In TIMEBASE units.
416 unsigned field; // Which field (0 or 1) of the frame to use. Always 0 for progressive.
417 std::function<void()> upload_func; // Needs to be called to actually upload the texture to OpenGL.
418 unsigned dropped_frames = 0; // Number of dropped frames before this one.
419 std::chrono::steady_clock::time_point received_timestamp = std::chrono::steady_clock::time_point::min();
421 std::deque<NewFrame> new_frames;
422 bool should_quit = false;
423 std::condition_variable new_frames_changed; // Set whenever new_frames (or should_quit) is changed.
425 QueueLengthPolicy queue_length_policy; // Refers to the "new_frames" queue.
427 int last_timecode = -1; // Unwrapped.
429 CaptureCard cards[MAX_VIDEO_CARDS]; // Protected by <card_mutex>.
430 AudioMixer audio_mixer; // Same as global_audio_mixer (see audio_mixer.h).
431 bool input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const;
432 struct OutputFrameInfo {
433 int dropped_frames; // Since last frame.
434 int num_samples; // Audio samples needed for this output frame.
435 int64_t frame_duration; // In TIMEBASE units.
437 std::chrono::steady_clock::time_point frame_timestamp;
439 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]);
441 InputState input_state;
443 // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
444 // Protected by its own mutex.
445 std::mutex hotplug_mutex;
446 std::vector<libusb_device *> hotplugged_cards;
448 class OutputChannel {
451 void output_frame(DisplayFrame frame);
452 bool get_display_frame(DisplayFrame *frame);
453 void set_frame_ready_callback(new_frame_ready_callback_t callback);
454 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
455 void set_name_updated_callback(name_updated_callback_t callback);
456 void set_color_updated_callback(color_updated_callback_t callback);
462 Mixer *parent = nullptr; // Not owned.
463 std::mutex frame_mutex;
464 DisplayFrame current_frame, ready_frame; // protected by <frame_mutex>
465 bool has_current_frame = false, has_ready_frame = false; // protected by <frame_mutex>
466 new_frame_ready_callback_t new_frame_ready_callback;
467 transition_names_updated_callback_t transition_names_updated_callback;
468 name_updated_callback_t name_updated_callback;
469 color_updated_callback_t color_updated_callback;
471 std::vector<std::string> last_transition_names;
472 std::string last_name, last_color;
474 OutputChannel output_channel[NUM_OUTPUTS];
476 std::thread mixer_thread;
477 std::thread audio_thread;
478 std::atomic<bool> should_quit{false};
479 std::atomic<bool> should_cut{false};
481 std::unique_ptr<ALSAOutput> alsa;
487 std::chrono::steady_clock::time_point frame_timestamp;
489 std::mutex audio_mutex;
490 std::condition_variable audio_task_queue_changed;
491 std::queue<AudioTask> audio_task_queue; // Under audio_mutex.
493 // For mode scanning.
494 bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
495 std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
496 unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
497 std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
500 extern Mixer *global_mixer;
501 extern bool uses_mlock;
503 #endif // !defined(_MIXER_H)