]> git.sesse.net Git - nageru/blob - mixer.h
Add the first beginnings of Prometheus metrics.
[nageru] / mixer.h
1 #ifndef _MIXER_H
2 #define _MIXER_H 1
3
4 // The actual video mixer, running in its own separate background thread.
5
6 #include <assert.h>
7 #include <epoxy/gl.h>
8
9 #undef Success
10
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include <atomic>
14 #include <chrono>
15 #include <condition_variable>
16 #include <cstddef>
17 #include <functional>
18 #include <map>
19 #include <memory>
20 #include <mutex>
21 #include <queue>
22 #include <string>
23 #include <thread>
24 #include <vector>
25
26 #include <movit/image_format.h>
27
28 #include "audio_mixer.h"
29 #include "bmusb/bmusb.h"
30 #include "defs.h"
31 #include "httpd.h"
32 #include "input_state.h"
33 #include "libusb.h"
34 #include "pbo_frame_allocator.h"
35 #include "ref_counted_frame.h"
36 #include "ref_counted_gl_sync.h"
37 #include "theme.h"
38 #include "timebase.h"
39 #include "video_encoder.h"
40 #include "ycbcr_interpretation.h"
41
42 class ALSAOutput;
43 class ChromaSubsampler;
44 class DeckLinkOutput;
45 class QSurface;
46 class QSurfaceFormat;
47 class TimecodeRenderer;
48 class v210Converter;
49
50 namespace movit {
51 class Effect;
52 class EffectChain;
53 class ResourcePool;
54 class YCbCrInput;
55 }  // namespace movit
56
57 // For any card that's not the master (where we pick out the frames as they
58 // come, as fast as we can process), there's going to be a queue. The question
59 // is when we should drop frames from that queue (apart from the obvious
60 // dropping if the 16-frame queue should become full), especially given that
61 // the frame rate could be lower or higher than the master (either subtly or
62 // dramatically). We have two (conflicting) demands:
63 //
64 //   1. We want to avoid starving the queue.
65 //   2. We don't want to add more delay than is needed.
66 //
67 // Our general strategy is to drop as many frames as we can (helping for #2)
68 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
69 // where we assume that if we have N frames in the queue, we're always safe from
70 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
71 // more than N frames in the queue after reading out the one we need, we head-drop
72 // them to reduce the queue.
73 //
74 // N is reduced as follows: If the queue has had at least one spare frame for
75 // at least 50 (master) frames (ie., it's been too conservative for a second),
76 // we reduce N by 1 and reset the timers.
77 //
78 // Whenever the queue is starved (we needed a frame but there was none),
79 // and we've been at N since the last starvation, N was obviously too low,
80 // so we increment it. We will never set N above 5, though.
81 class QueueLengthPolicy {
82 public:
83         QueueLengthPolicy() {}
84         void reset(unsigned card_index) {
85                 this->card_index = card_index;
86                 safe_queue_length = 1;
87                 frames_with_at_least_one = 0;
88                 been_at_safe_point_since_last_starvation = false;
89         }
90
91         void update_policy(unsigned queue_length);  // Call before picking out a frame, so 0 means starvation.
92         unsigned get_safe_queue_length() const { return safe_queue_length; }
93
94 private:
95         unsigned card_index;  // For debugging only.
96         unsigned safe_queue_length = 1;  // Called N in the comments. Can never go below 1.
97         unsigned frames_with_at_least_one = 0;
98         bool been_at_safe_point_since_last_starvation = false;
99 };
100
101 class Mixer {
102 public:
103         // The surface format is used for offscreen destinations for OpenGL contexts we need.
104         Mixer(const QSurfaceFormat &format, unsigned num_cards);
105         ~Mixer();
106         void start();
107         void quit();
108
109         void transition_clicked(int transition_num);
110         void channel_clicked(int preview_num);
111
112         enum Output {
113                 OUTPUT_LIVE = 0,
114                 OUTPUT_PREVIEW,
115                 OUTPUT_INPUT0,  // 1, 2, 3, up to 15 follow numerically.
116                 NUM_OUTPUTS = 18
117         };
118
119         struct DisplayFrame {
120                 // The chain for rendering this frame. To render a display frame,
121                 // first wait for <ready_fence>, then call <setup_chain>
122                 // to wire up all the inputs, and then finally call
123                 // chain->render_to_screen() or similar.
124                 movit::EffectChain *chain;
125                 std::function<void()> setup_chain;
126
127                 // Asserted when all the inputs are ready; you cannot render the chain
128                 // before this.
129                 RefCountedGLsync ready_fence;
130
131                 // Holds on to all the input frames needed for this display frame,
132                 // so they are not released while still rendering.
133                 std::vector<RefCountedFrame> input_frames;
134
135                 // Textures that should be released back to the resource pool
136                 // when this frame disappears, if any.
137                 // TODO: Refcount these as well?
138                 std::vector<GLuint> temp_textures;
139         };
140         // Implicitly frees the previous one if there's a new frame available.
141         bool get_display_frame(Output output, DisplayFrame *frame) {
142                 return output_channel[output].get_display_frame(frame);
143         }
144
145         // NOTE: Callbacks will be called with a mutex held, so you should probably
146         // not do real work in them.
147         typedef std::function<void()> new_frame_ready_callback_t;
148         void add_frame_ready_callback(Output output, void *key, new_frame_ready_callback_t callback)
149         {
150                 output_channel[output].add_frame_ready_callback(key, callback);
151         }
152
153         void remove_frame_ready_callback(Output output, void *key)
154         {
155                 output_channel[output].remove_frame_ready_callback(key);
156         }
157
158         // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
159         typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
160         void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
161         {
162                 output_channel[output].set_transition_names_updated_callback(callback);
163         }
164
165         typedef std::function<void(const std::string &)> name_updated_callback_t;
166         void set_name_updated_callback(Output output, name_updated_callback_t callback)
167         {
168                 output_channel[output].set_name_updated_callback(callback);
169         }
170
171         typedef std::function<void(const std::string &)> color_updated_callback_t;
172         void set_color_updated_callback(Output output, color_updated_callback_t callback)
173         {
174                 output_channel[output].set_color_updated_callback(callback);
175         }
176
177         std::vector<std::string> get_transition_names()
178         {
179                 return theme->get_transition_names(pts());
180         }
181
182         unsigned get_num_channels() const
183         {
184                 return theme->get_num_channels();
185         }
186
187         std::string get_channel_name(unsigned channel) const
188         {
189                 return theme->get_channel_name(channel);
190         }
191
192         std::string get_channel_color(unsigned channel) const
193         {
194                 return theme->get_channel_color(channel);
195         }
196
197         int get_channel_signal(unsigned channel) const
198         {
199                 return theme->get_channel_signal(channel);
200         }
201
202         int map_signal(unsigned channel)
203         {
204                 return theme->map_signal(channel);
205         }
206
207         unsigned get_master_clock() const
208         {
209                 return master_clock_channel;
210         }
211
212         void set_master_clock(unsigned channel)
213         {
214                 master_clock_channel = channel;
215         }
216
217         void set_signal_mapping(int signal, int card)
218         {
219                 return theme->set_signal_mapping(signal, card);
220         }
221
222         YCbCrInterpretation get_input_ycbcr_interpretation(unsigned card_index) const;
223         void set_input_ycbcr_interpretation(unsigned card_index, const YCbCrInterpretation &interpretation);
224
225         bool get_supports_set_wb(unsigned channel) const
226         {
227                 return theme->get_supports_set_wb(channel);
228         }
229
230         void set_wb(unsigned channel, double r, double g, double b) const
231         {
232                 theme->set_wb(channel, r, g, b);
233         }
234
235         // Note: You can also get this through the global variable global_audio_mixer.
236         AudioMixer *get_audio_mixer() { return &audio_mixer; }
237         const AudioMixer *get_audio_mixer() const { return &audio_mixer; }
238
239         void schedule_cut()
240         {
241                 should_cut = true;
242         }
243
244         unsigned get_num_cards() const { return num_cards; }
245
246         std::string get_card_description(unsigned card_index) const {
247                 assert(card_index < num_cards);
248                 return cards[card_index].capture->get_description();
249         }
250
251         // The difference between this and the previous function is that if a card
252         // is used as the current output, get_card_description() will return the
253         // fake card that's replacing it for input, whereas this function will return
254         // the card's actual name.
255         std::string get_output_card_description(unsigned card_index) const {
256                 assert(card_can_be_used_as_output(card_index));
257                 assert(card_index < num_cards);
258                 if (cards[card_index].parked_capture) {
259                         return cards[card_index].parked_capture->get_description();
260                 } else {
261                         return cards[card_index].capture->get_description();
262                 }
263         }
264
265         bool card_can_be_used_as_output(unsigned card_index) const {
266                 assert(card_index < num_cards);
267                 return cards[card_index].output != nullptr;
268         }
269
270         std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
271                 assert(card_index < num_cards);
272                 return cards[card_index].capture->get_available_video_modes();
273         }
274
275         uint32_t get_current_video_mode(unsigned card_index) const {
276                 assert(card_index < num_cards);
277                 return cards[card_index].capture->get_current_video_mode();
278         }
279
280         void set_video_mode(unsigned card_index, uint32_t mode) {
281                 assert(card_index < num_cards);
282                 cards[card_index].capture->set_video_mode(mode);
283         }
284
285         void start_mode_scanning(unsigned card_index);
286
287         std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
288                 assert(card_index < num_cards);
289                 return cards[card_index].capture->get_available_video_inputs();
290         }
291
292         uint32_t get_current_video_input(unsigned card_index) const {
293                 assert(card_index < num_cards);
294                 return cards[card_index].capture->get_current_video_input();
295         }
296
297         void set_video_input(unsigned card_index, uint32_t input) {
298                 assert(card_index < num_cards);
299                 cards[card_index].capture->set_video_input(input);
300         }
301
302         std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
303                 assert(card_index < num_cards);
304                 return cards[card_index].capture->get_available_audio_inputs();
305         }
306
307         uint32_t get_current_audio_input(unsigned card_index) const {
308                 assert(card_index < num_cards);
309                 return cards[card_index].capture->get_current_audio_input();
310         }
311
312         void set_audio_input(unsigned card_index, uint32_t input) {
313                 assert(card_index < num_cards);
314                 cards[card_index].capture->set_audio_input(input);
315         }
316
317         void change_x264_bitrate(unsigned rate_kbit) {
318                 video_encoder->change_x264_bitrate(rate_kbit);
319         }
320
321         int get_output_card_index() const {  // -1 = no output, just stream.
322                 return desired_output_card_index;
323         }
324
325         void set_output_card(int card_index) { // -1 = no output, just stream.
326                 desired_output_card_index = card_index;
327         }
328
329         std::map<uint32_t, bmusb::VideoMode> get_available_output_video_modes() const;
330
331         uint32_t get_output_video_mode() const {
332                 return desired_output_video_mode;
333         }
334
335         void set_output_video_mode(uint32_t mode) {
336                 desired_output_video_mode = mode;
337         }
338
339         void set_display_timecode_in_stream(bool enable) {
340                 display_timecode_in_stream = enable;
341         }
342
343         void set_display_timecode_on_stdout(bool enable) {
344                 display_timecode_on_stdout = enable;
345         }
346
347 private:
348         struct CaptureCard;
349
350         enum class CardType {
351                 LIVE_CARD,
352                 FAKE_CAPTURE,
353                 FFMPEG_INPUT
354         };
355         void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, CardType card_type, DeckLinkOutput *output);
356         void set_output_card_internal(int card_index);  // Should only be called from the mixer thread.
357         void bm_frame(unsigned card_index, uint16_t timecode,
358                 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
359                 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
360         void bm_hotplug_add(libusb_device *dev);
361         void bm_hotplug_remove(unsigned card_index);
362         void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
363         void thread_func();
364         void handle_hotplugged_cards();
365         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);
366         std::string get_timecode_text() const;
367         void render_one_frame(int64_t duration);
368         void audio_thread_func();
369         void release_display_frame(DisplayFrame *frame);
370         double pts() { return double(pts_int) / TIMEBASE; }
371         // Call this _before_ trying to pull out a frame from a capture card;
372         // it will update the policy and drop the right amount of frames for you.
373         void trim_queue(CaptureCard *card, unsigned card_index);
374
375         HTTPD httpd;
376         unsigned num_cards, num_video_inputs;
377
378         QSurface *mixer_surface, *h264_encoder_surface, *decklink_output_surface;
379         std::unique_ptr<movit::ResourcePool> resource_pool;
380         std::unique_ptr<Theme> theme;
381         std::atomic<unsigned> audio_source_channel{0};
382         std::atomic<int> master_clock_channel{0};  // Gets overridden by <output_card_index> if set.
383         int output_card_index = -1;  // -1 for none.
384         uint32_t output_video_mode = -1;
385
386         // The mechanics of changing the output card and modes are so intricately connected
387         // with the work the mixer thread is doing. Thus, we don't change it directly,
388         // we just set this variable instead, which signals to the mixer thread that
389         // it should do the change before the next frame. This simplifies locking
390         // considerations immensely.
391         std::atomic<int> desired_output_card_index{-1};
392         std::atomic<uint32_t> desired_output_video_mode{0};
393
394         std::unique_ptr<movit::EffectChain> display_chain;
395         std::unique_ptr<ChromaSubsampler> chroma_subsampler;
396         std::unique_ptr<v210Converter> v210_converter;
397         std::unique_ptr<VideoEncoder> video_encoder;
398
399         std::unique_ptr<TimecodeRenderer> timecode_renderer;
400         std::atomic<bool> display_timecode_in_stream{false};
401         std::atomic<bool> display_timecode_on_stdout{false};
402
403         // Effects part of <display_chain>. Owned by <display_chain>.
404         movit::YCbCrInput *display_input;
405
406         int64_t pts_int = 0;  // In TIMEBASE units.
407         unsigned frame_num = 0;
408
409         // Accumulated errors in number of 1/TIMEBASE audio samples. If OUTPUT_FREQUENCY divided by
410         // frame rate is integer, will always stay zero.
411         unsigned fractional_samples = 0;
412
413         mutable std::mutex card_mutex;
414         bool has_bmusb_thread = false;
415         struct CaptureCard {
416                 std::unique_ptr<bmusb::CaptureInterface> capture;
417                 bool is_fake_capture;
418                 CardType type;
419                 std::unique_ptr<DeckLinkOutput> output;
420
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
425                 // and moved here.
426                 std::unique_ptr<bmusb::CaptureInterface> parked_capture;
427
428                 std::unique_ptr<PBOFrameAllocator> frame_allocator;
429
430                 // Stuff for the OpenGL context (for texture uploading).
431                 QSurface *surface = nullptr;
432
433                 struct NewFrame {
434                         RefCountedFrame frame;
435                         int64_t length;  // In TIMEBASE units.
436                         bool interlaced;
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();
441                 };
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.
445
446                 QueueLengthPolicy queue_length_policy;  // Refers to the "new_frames" queue.
447
448                 int last_timecode = -1;  // Unwrapped.
449         };
450         CaptureCard cards[MAX_VIDEO_CARDS];  // Protected by <card_mutex>.
451         YCbCrInterpretation ycbcr_interpretation[MAX_VIDEO_CARDS];  // Protected by <card_mutex>.
452         AudioMixer audio_mixer;  // Same as global_audio_mixer (see audio_mixer.h).
453         bool input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const;
454         struct OutputFrameInfo {
455                 int dropped_frames;  // Since last frame.
456                 int num_samples;  // Audio samples needed for this output frame.
457                 int64_t frame_duration;  // In TIMEBASE units.
458                 bool is_preroll;
459                 std::chrono::steady_clock::time_point frame_timestamp;
460         };
461         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]);
462
463         InputState input_state;
464
465         // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
466         // Protected by its own mutex.
467         std::mutex hotplug_mutex;
468         std::vector<libusb_device *> hotplugged_cards;
469
470         class OutputChannel {
471         public:
472                 ~OutputChannel();
473                 void output_frame(DisplayFrame frame);
474                 bool get_display_frame(DisplayFrame *frame);
475                 void add_frame_ready_callback(void *key, new_frame_ready_callback_t callback);
476                 void remove_frame_ready_callback(void *key);
477                 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
478                 void set_name_updated_callback(name_updated_callback_t callback);
479                 void set_color_updated_callback(color_updated_callback_t callback);
480
481         private:
482                 friend class Mixer;
483
484                 unsigned channel;
485                 Mixer *parent = nullptr;  // Not owned.
486                 std::mutex frame_mutex;
487                 DisplayFrame current_frame, ready_frame;  // protected by <frame_mutex>
488                 bool has_current_frame = false, has_ready_frame = false;  // protected by <frame_mutex>
489                 std::map<void *, new_frame_ready_callback_t> new_frame_ready_callbacks;  // protected by <frame_mutex>
490                 transition_names_updated_callback_t transition_names_updated_callback;
491                 name_updated_callback_t name_updated_callback;
492                 color_updated_callback_t color_updated_callback;
493
494                 std::vector<std::string> last_transition_names;
495                 std::string last_name, last_color;
496         };
497         OutputChannel output_channel[NUM_OUTPUTS];
498
499         std::thread mixer_thread;
500         std::thread audio_thread;
501         std::atomic<bool> should_quit{false};
502         std::atomic<bool> should_cut{false};
503
504         std::unique_ptr<ALSAOutput> alsa;
505
506         struct AudioTask {
507                 int64_t pts_int;
508                 int num_samples;
509                 bool adjust_rate;
510                 std::chrono::steady_clock::time_point frame_timestamp;
511         };
512         std::mutex audio_mutex;
513         std::condition_variable audio_task_queue_changed;
514         std::queue<AudioTask> audio_task_queue;  // Under audio_mutex.
515
516         // For mode scanning.
517         bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
518         std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
519         unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
520         std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
521
522         // Metrics.
523         std::atomic<int64_t> metrics_num_frames;
524         std::atomic<int64_t> metrics_dropped_frames;
525         std::atomic<double> metrics_uptime;
526 };
527
528 extern Mixer *global_mixer;
529 extern bool uses_mlock;
530
531 #endif  // !defined(_MIXER_H)