4 // The actual video mixer, running in its own separate background thread.
15 #include <condition_variable>
28 #include <movit/effect.h>
30 #include "audio_mixer.h"
31 #include "card_type.h"
32 #include "bmusb/bmusb.h"
33 #include "ffmpeg_capture.h"
34 #include "shared/httpd.h"
35 #include "input_state.h"
37 #include "pbo_frame_allocator.h"
38 #include "queue_length_policy.h"
39 #include "ref_counted_frame.h"
40 #include "shared/ref_counted_gl_sync.h"
41 #include "srt_metrics.h"
43 #include "shared/shared_defs.h"
44 #include "shared/timebase.h"
45 #include "video_encoder.h"
46 #include "ycbcr_interpretation.h"
49 class ChromaSubsampler;
54 class TimecodeRenderer;
66 // The surface format is used for offscreen destinations for OpenGL contexts we need.
67 Mixer(const QSurfaceFormat &format);
72 void transition_clicked(int transition_num);
73 void channel_clicked(int preview_num);
78 OUTPUT_INPUT0, // 1, 2, 3, up to 15 follow numerically.
83 // The chain for rendering this frame. To render a display frame,
84 // first wait for <ready_fence>, then call <setup_chain>
85 // to wire up all the inputs, and then finally call
86 // chain->render_to_screen() or similar.
87 movit::EffectChain *chain;
88 std::function<void()> setup_chain;
90 // Asserted when all the inputs are ready; you cannot render the chain
92 RefCountedGLsync ready_fence;
94 // Holds on to all the input frames needed for this display frame,
95 // so they are not released while still rendering.
96 std::vector<RefCountedFrame> input_frames;
98 // Textures that should be released back to the resource pool
99 // when this frame disappears, if any.
100 // TODO: Refcount these as well?
101 std::vector<GLuint> temp_textures;
103 // Implicitly frees the previous one if there's a new frame available.
104 bool get_display_frame(Output output, DisplayFrame *frame) {
105 return output_channel[output].get_display_frame(frame);
108 // NOTE: Callbacks will be called with a mutex held, so you should probably
109 // not do real work in them.
110 typedef std::function<void()> new_frame_ready_callback_t;
111 void add_frame_ready_callback(Output output, void *key, new_frame_ready_callback_t callback)
113 output_channel[output].add_frame_ready_callback(key, callback);
116 void remove_frame_ready_callback(Output output, void *key)
118 output_channel[output].remove_frame_ready_callback(key);
121 // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
122 typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
123 void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
125 output_channel[output].set_transition_names_updated_callback(callback);
128 typedef std::function<void(const std::string &)> name_updated_callback_t;
129 void set_name_updated_callback(Output output, name_updated_callback_t callback)
131 output_channel[output].set_name_updated_callback(callback);
134 typedef std::function<void(const std::string &)> color_updated_callback_t;
135 void set_color_updated_callback(Output output, color_updated_callback_t callback)
137 output_channel[output].set_color_updated_callback(callback);
140 std::vector<std::string> get_transition_names()
142 return theme->get_transition_names(pts());
145 unsigned get_num_channels() const
147 return theme->get_num_channels();
150 std::string get_channel_name(unsigned channel) const
152 return theme->get_channel_name(channel);
155 std::string get_channel_color(unsigned channel) const
157 return theme->get_channel_color(channel);
160 int map_channel_to_signal(unsigned channel) const
162 return theme->map_channel_to_signal(channel);
165 int map_signal_to_card(int signal)
167 return theme->map_signal_to_card(signal);
170 unsigned get_master_clock() const
172 return master_clock_channel;
175 void set_master_clock(unsigned channel)
177 master_clock_channel = channel;
180 void set_signal_mapping(int signal, int card)
182 return theme->set_signal_mapping(signal, card);
185 YCbCrInterpretation get_input_ycbcr_interpretation(unsigned card_index) const;
186 void set_input_ycbcr_interpretation(unsigned card_index, const YCbCrInterpretation &interpretation);
188 bool get_supports_set_wb(unsigned channel) const
190 return theme->get_supports_set_wb(channel);
193 void set_wb(unsigned channel, double r, double g, double b) const
195 theme->set_wb(channel, r, g, b);
198 std::string format_status_line(const std::string &disk_space_left_text, double file_length_seconds)
200 return theme->format_status_line(disk_space_left_text, file_length_seconds);
203 // Note: You can also get this through the global variable global_audio_mixer.
204 AudioMixer *get_audio_mixer() { return audio_mixer.get(); }
205 const AudioMixer *get_audio_mixer() const { return audio_mixer.get(); }
212 std::string get_card_description(unsigned card_index) const {
213 assert(card_index < MAX_VIDEO_CARDS);
214 return cards[card_index].capture->get_description();
217 // The difference between this and the previous function is that if a card
218 // is used as the current output, get_card_description() will return the
219 // fake card that's replacing it for input, whereas this function will return
220 // the card's actual name.
221 std::string get_output_card_description(unsigned card_index) const {
222 assert(card_can_be_used_as_output(card_index));
223 assert(card_index < MAX_VIDEO_CARDS);
224 if (cards[card_index].parked_capture) {
225 return cards[card_index].parked_capture->get_description();
227 return cards[card_index].capture->get_description();
231 bool card_can_be_used_as_output(unsigned card_index) const {
232 assert(card_index < MAX_VIDEO_CARDS);
233 return cards[card_index].output != nullptr && cards[card_index].capture != nullptr;
236 bool card_is_cef(unsigned card_index) const {
237 assert(card_index < MAX_VIDEO_CARDS);
238 return cards[card_index].type == CardType::CEF_INPUT;
241 bool card_is_ffmpeg(unsigned card_index) const {
242 assert(card_index < MAX_VIDEO_CARDS);
243 if (cards[card_index].type != CardType::FFMPEG_INPUT) {
247 // SRT inputs are more like regular inputs than FFmpeg inputs,
248 // so show them as such. (This allows the user to right-click
249 // to select a different input.)
250 return static_cast<FFmpegCapture *>(cards[card_index].capture.get())->get_srt_sock() == -1;
256 bool card_is_active(unsigned card_index) const {
257 assert(card_index < MAX_VIDEO_CARDS);
258 std::lock_guard<std::mutex> lock(card_mutex);
259 return cards[card_index].capture != nullptr;
262 void force_card_active(unsigned card_index)
264 // handle_hotplugged_cards() will pick this up.
265 std::lock_guard<std::mutex> lock(card_mutex);
266 cards[card_index].force_active = true;
269 std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
270 assert(card_index < MAX_VIDEO_CARDS);
271 return cards[card_index].capture->get_available_video_modes();
274 uint32_t get_current_video_mode(unsigned card_index) const {
275 assert(card_index < MAX_VIDEO_CARDS);
276 return cards[card_index].capture->get_current_video_mode();
279 void set_video_mode(unsigned card_index, uint32_t mode) {
280 assert(card_index < MAX_VIDEO_CARDS);
281 cards[card_index].capture->set_video_mode(mode);
284 void start_mode_scanning(unsigned card_index);
286 std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
287 assert(card_index < MAX_VIDEO_CARDS);
288 return cards[card_index].capture->get_available_video_inputs();
291 uint32_t get_current_video_input(unsigned card_index) const {
292 assert(card_index < MAX_VIDEO_CARDS);
293 return cards[card_index].capture->get_current_video_input();
296 void set_video_input(unsigned card_index, uint32_t input) {
297 assert(card_index < MAX_VIDEO_CARDS);
298 cards[card_index].capture->set_video_input(input);
301 std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
302 assert(card_index < MAX_VIDEO_CARDS);
303 return cards[card_index].capture->get_available_audio_inputs();
306 uint32_t get_current_audio_input(unsigned card_index) const {
307 assert(card_index < MAX_VIDEO_CARDS);
308 return cards[card_index].capture->get_current_audio_input();
311 void set_audio_input(unsigned card_index, uint32_t input) {
312 assert(card_index < MAX_VIDEO_CARDS);
313 cards[card_index].capture->set_audio_input(input);
316 std::string get_ffmpeg_filename(unsigned card_index) const;
318 void set_ffmpeg_filename(unsigned card_index, const std::string &filename);
320 void change_x264_bitrate(unsigned rate_kbit) {
321 video_encoder->change_x264_bitrate(rate_kbit);
324 int get_output_card_index() const { // -1 = no output, just stream.
325 return desired_output_card_index;
328 void set_output_card(int card_index) { // -1 = no output, just stream.
329 desired_output_card_index = card_index;
332 bool get_output_card_is_master() const {
333 return output_card_is_master;
336 std::map<uint32_t, bmusb::VideoMode> get_available_output_video_modes() const;
338 uint32_t get_output_video_mode() const {
339 return desired_output_video_mode;
342 void set_output_video_mode(uint32_t mode) {
343 desired_output_video_mode = mode;
346 void set_display_timecode_in_stream(bool enable) {
347 display_timecode_in_stream = enable;
350 void set_display_timecode_on_stdout(bool enable) {
351 display_timecode_on_stdout = enable;
354 int64_t get_num_connected_clients() const {
355 return httpd.get_num_connected_clients();
358 Theme::MenuEntry *get_theme_menu() { return theme->get_theme_menu(); }
360 void theme_menu_entry_clicked(int lua_ref) { return theme->theme_menu_entry_clicked(lua_ref); }
362 void set_theme_menu_callback(std::function<void()> callback)
364 theme->set_theme_menu_callback(callback);
367 void wait_for_next_frame();
372 void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, CardType card_type, DeckLinkOutput *output, bool is_srt_card);
373 void set_output_card_internal(int card_index); // Should only be called from the mixer thread.
374 void bm_frame(unsigned card_index, uint16_t timecode,
375 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
376 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
377 void upload_texture_for_frame(
378 int field, bmusb::VideoFormat video_format,
379 size_t y_offset, size_t cbcr_offset, size_t video_offset,
380 PBOFrameAllocator::Userdata *userdata);
381 void bm_hotplug_add(libusb_device *dev);
382 void bm_hotplug_remove(unsigned card_index);
383 void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
385 void handle_hotplugged_cards();
386 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);
387 std::string get_timecode_text() const;
388 void render_one_frame(int64_t duration);
389 void audio_thread_func();
390 void release_display_frame(DisplayFrame *frame);
394 double pts() { return double(pts_int) / TIMEBASE; }
395 void trim_queue(CaptureCard *card, size_t safe_queue_length);
396 std::pair<std::string, std::string> get_channels_json();
397 std::pair<std::string, std::string> get_channel_color_http(unsigned channel_idx);
400 unsigned num_video_inputs, num_html_inputs = 0;
402 QSurface *mixer_surface, *h264_encoder_surface, *decklink_output_surface, *image_update_surface;
403 std::unique_ptr<movit::ResourcePool> resource_pool;
404 std::unique_ptr<Theme> theme;
405 std::atomic<unsigned> audio_source_channel{0};
406 std::atomic<int> master_clock_channel{0}; // Gets overridden by <output_card_index> if output_card_is_master == true.
407 int output_card_index = -1; // -1 for none.
408 uint32_t output_video_mode = -1;
409 bool output_card_is_master = false; // Only relevant if output_card_index != -1.
411 // The mechanics of changing the output card and modes are so intricately connected
412 // with the work the mixer thread is doing. Thus, we don't change it directly,
413 // we just set this variable instead, which signals to the mixer thread that
414 // it should do the change before the next frame. This simplifies locking
415 // considerations immensely.
416 std::atomic<int> desired_output_card_index{-1};
417 std::atomic<uint32_t> desired_output_video_mode{0};
419 std::unique_ptr<movit::EffectChain> display_chain;
420 std::unique_ptr<ChromaSubsampler> chroma_subsampler;
421 std::unique_ptr<v210Converter> v210_converter;
422 std::unique_ptr<VideoEncoder> video_encoder;
423 std::unique_ptr<MJPEGEncoder> mjpeg_encoder;
425 std::unique_ptr<TimecodeRenderer> timecode_renderer;
426 std::atomic<bool> display_timecode_in_stream{false};
427 std::atomic<bool> display_timecode_on_stdout{false};
429 // Effects part of <display_chain>. Owned by <display_chain>.
430 movit::YCbCrInput *display_input;
432 int64_t pts_int = 0; // In TIMEBASE units.
434 mutable std::mutex frame_num_mutex;
435 std::condition_variable frame_num_updated;
436 unsigned frame_num = 0; // Under <frame_num_mutex>.
438 // Accumulated errors in number of 1/TIMEBASE audio samples. If OUTPUT_FREQUENCY divided by
439 // frame rate is integer, will always stay zero.
440 unsigned fractional_samples = 0;
442 // Monotonic counter that lets us know which slot was last turned into
443 // a fake capture. Used for SRT re-plugging.
444 unsigned fake_capture_counter = 0;
446 mutable std::mutex card_mutex;
447 bool has_bmusb_thread = false;
449 // If nullptr, the card is inactive, and will be hidden in the UI.
450 // Only fake capture cards can be inactive.
451 std::unique_ptr<bmusb::CaptureInterface> capture;
452 // If true, card must always be active (typically because it's one of the
453 // first cards, or because the theme has explicitly asked for it).
454 bool force_active = false;
455 bool is_fake_capture;
456 // If is_fake_capture is true, contains a monotonic timer value for when
457 // it was last changed. Otherwise undefined. Used for SRT re-plugging.
458 int fake_capture_counter;
459 std::string last_srt_stream_id = "<default, matches nothing>"; // Used for SRT re-plugging.
461 std::unique_ptr<DeckLinkOutput> output;
463 // CEF only delivers frames when it actually has a change.
464 // If we trim the queue for latency reasons, we could thus
465 // end up in a situation trimming a frame that was meant to
466 // be displayed for a long time, which is really suboptimal.
467 // Thus, if we drop the last frame we have, may_have_dropped_last_frame
468 // is set to true, and the next starvation event will trigger
469 // us requestin a CEF repaint.
470 bool is_cef_capture, may_have_dropped_last_frame = false;
472 // If this card is used for output (ie., output_card_index points to it),
473 // it cannot simultaneously be uesd for capture, so <capture> gets replaced
474 // by a FakeCapture. However, since reconstructing the real capture object
475 // with all its state can be annoying, it is not being deleted, just stopped
477 std::unique_ptr<bmusb::CaptureInterface> parked_capture;
479 std::unique_ptr<PBOFrameAllocator> frame_allocator;
481 // Stuff for the OpenGL context (for texture uploading).
482 QSurface *surface = nullptr;
485 RefCountedFrame frame;
486 int64_t length; // In TIMEBASE units.
488 unsigned field; // Which field (0 or 1) of the frame to use. Always 0 for progressive.
489 bool texture_uploaded = false;
490 unsigned dropped_frames = 0; // Number of dropped frames before this one.
491 std::chrono::steady_clock::time_point received_timestamp = std::chrono::steady_clock::time_point::min();
492 movit::RGBTriplet neutral_color{1.0f, 1.0f, 1.0f};
494 // Used for MJPEG encoding, and texture upload.
495 // width=0 or height=0 means a broken frame, ie., do not upload.
496 bmusb::VideoFormat video_format;
497 size_t video_offset, y_offset, cbcr_offset;
499 std::deque<NewFrame> new_frames;
500 std::condition_variable new_frames_changed; // Set whenever new_frames is changed.
501 QueueLengthPolicy queue_length_policy; // Refers to the "new_frames" queue.
503 std::vector<int32_t> new_raw_audio;
505 int last_timecode = -1; // Unwrapped.
507 JitterHistory jitter_history;
510 std::vector<std::pair<std::string, std::string>> labels;
511 std::atomic<int64_t> metric_input_received_frames{0};
512 std::atomic<int64_t> metric_input_duped_frames{0};
513 std::atomic<int64_t> metric_input_dropped_frames_jitter{0};
514 std::atomic<int64_t> metric_input_dropped_frames_error{0};
515 std::atomic<int64_t> metric_input_resets{0};
516 std::atomic<int64_t> metric_input_queue_length_frames{0};
518 std::atomic<int64_t> metric_input_has_signal_bool{-1};
519 std::atomic<int64_t> metric_input_is_connected_bool{-1};
520 std::atomic<int64_t> metric_input_interlaced_bool{-1};
521 std::atomic<int64_t> metric_input_width_pixels{-1};
522 std::atomic<int64_t> metric_input_height_pixels{-1};
523 std::atomic<int64_t> metric_input_frame_rate_nom{-1};
524 std::atomic<int64_t> metric_input_frame_rate_den{-1};
525 std::atomic<int64_t> metric_input_sample_rate_hz{-1};
528 SRTMetrics srt_metrics;
531 JitterHistory output_jitter_history;
532 CaptureCard cards[MAX_VIDEO_CARDS]; // Protected by <card_mutex>.
533 YCbCrInterpretation ycbcr_interpretation[MAX_VIDEO_CARDS]; // Protected by <card_mutex>.
534 movit::RGBTriplet last_received_neutral_color[MAX_VIDEO_CARDS]; // Used by the mixer thread only. Constructor-initialiezd.
535 std::unique_ptr<AudioMixer> audio_mixer; // Same as global_audio_mixer (see audio_mixer.h).
536 bool input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const;
537 struct OutputFrameInfo {
538 int dropped_frames; // Since last frame.
539 int num_samples; // Audio samples needed for this output frame.
540 int64_t frame_duration; // In TIMEBASE units.
542 std::chrono::steady_clock::time_point frame_timestamp;
544 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], std::vector<int32_t> raw_audio[MAX_VIDEO_CARDS]);
546 std::string description_for_card(unsigned card_index);
547 static bool is_srt_card(const CaptureCard *card);
549 InputState input_state;
551 // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
552 // Protected by its own mutex.
553 std::mutex hotplug_mutex;
554 std::vector<libusb_device *> hotplugged_cards;
556 std::vector<int> hotplugged_srt_cards;
559 class OutputChannel {
562 void output_frame(DisplayFrame &&frame);
563 bool get_display_frame(DisplayFrame *frame);
564 void add_frame_ready_callback(void *key, new_frame_ready_callback_t callback);
565 void remove_frame_ready_callback(void *key);
566 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
567 void set_name_updated_callback(name_updated_callback_t callback);
568 void set_color_updated_callback(color_updated_callback_t callback);
574 Mixer *parent = nullptr; // Not owned.
575 std::mutex frame_mutex;
576 DisplayFrame current_frame, ready_frame; // protected by <frame_mutex>
577 bool has_current_frame = false, has_ready_frame = false; // protected by <frame_mutex>
578 std::map<void *, new_frame_ready_callback_t> new_frame_ready_callbacks; // protected by <frame_mutex>
579 transition_names_updated_callback_t transition_names_updated_callback;
580 name_updated_callback_t name_updated_callback;
581 color_updated_callback_t color_updated_callback;
583 std::vector<std::string> last_transition_names;
584 std::string last_name, last_color;
586 OutputChannel output_channel[NUM_OUTPUTS];
588 std::thread mixer_thread;
589 std::thread audio_thread;
591 std::thread srt_thread;
593 std::atomic<bool> should_quit{false};
594 std::atomic<bool> should_cut{false};
596 std::unique_ptr<ALSAOutput> alsa;
602 std::chrono::steady_clock::time_point frame_timestamp;
604 std::mutex audio_mutex;
605 std::condition_variable audio_task_queue_changed;
606 std::queue<AudioTask> audio_task_queue; // Under audio_mutex.
608 // For mode scanning.
609 bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
610 std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
611 unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
612 std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
615 extern Mixer *global_mixer;
617 #endif // !defined(_MIXER_H)