]> git.sesse.net Git - nageru/blob - mixer.h
Add a printout of mlockall() memory used, from bitter experience :-)
[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 <epoxy/gl.h>
7 #undef Success
8 #include <stdbool.h>
9 #include <stdint.h>
10
11 #include <movit/effect_chain.h>
12 #include <movit/flat_input.h>
13 #include <zita-resampler/resampler.h>
14 #include <atomic>
15 #include <condition_variable>
16 #include <cstddef>
17 #include <functional>
18 #include <memory>
19 #include <mutex>
20 #include <string>
21 #include <thread>
22 #include <vector>
23
24 #include "bmusb/bmusb.h"
25 #include "alsa_output.h"
26 #include "ebu_r128_proc.h"
27 #include "video_encoder.h"
28 #include "httpd.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"
33 #include "theme.h"
34 #include "timebase.h"
35 #include "stereocompressor.h"
36 #include "filter.h"
37 #include "input_state.h"
38 #include "correlation_measurer.h"
39
40 class QuickSyncEncoder;
41 class QSurface;
42 namespace movit {
43 class Effect;
44 class EffectChain;
45 class FlatInput;
46 class ResourcePool;
47 }  // namespace movit
48
49 namespace movit {
50 class YCbCrInput;
51 }
52 class QOpenGLContext;
53 class QSurfaceFormat;
54
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:
61 //
62 //   1. We want to avoid starving the queue.
63 //   2. We don't want to add more delay than is needed.
64 //
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.
71 //
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
75 // touched the limit.
76 //
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 {
81 public:
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;
88         }
89
90         void update_policy(int queue_length);  // Give in -1 for starvation.
91         unsigned get_safe_queue_length() const { return safe_queue_length; }
92
93 private:
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;
98 };
99
100 class Mixer {
101 public:
102         // The surface format is used for offscreen destinations for OpenGL contexts we need.
103         Mixer(const QSurfaceFormat &format, unsigned num_cards);
104         ~Mixer();
105         void start();
106         void quit();
107
108         void transition_clicked(int transition_num);
109         void channel_clicked(int preview_num);
110
111         enum Output {
112                 OUTPUT_LIVE = 0,
113                 OUTPUT_PREVIEW,
114                 OUTPUT_INPUT0,  // 1, 2, 3, up to 15 follow numerically.
115                 NUM_OUTPUTS = 18
116         };
117
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;
125
126                 // Asserted when all the inputs are ready; you cannot render the chain
127                 // before this.
128                 RefCountedGLsync ready_fence;
129
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;
133
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;
138         };
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);
142         }
143
144         typedef std::function<void()> new_frame_ready_callback_t;
145         void set_frame_ready_callback(Output output, new_frame_ready_callback_t callback)
146         {
147                 output_channel[output].set_frame_ready_callback(callback);
148         }
149
150         // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
151         typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
152         void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
153         {
154                 output_channel[output].set_transition_names_updated_callback(callback);
155         }
156
157         typedef std::function<void(const std::string &)> name_updated_callback_t;
158         void set_name_updated_callback(Output output, name_updated_callback_t callback)
159         {
160                 output_channel[output].set_name_updated_callback(callback);
161         }
162
163         typedef std::function<void(const std::string &)> color_updated_callback_t;
164         void set_color_updated_callback(Output output, color_updated_callback_t callback)
165         {
166                 output_channel[output].set_color_updated_callback(callback);
167         }
168
169         typedef std::function<void(float level_lufs, float peak_db,
170                                    float global_level_lufs, float range_low_lufs, float range_high_lufs,
171                                    float gain_staging_db, float final_makeup_gain_db,
172                                    float correlation)> audio_level_callback_t;
173         void set_audio_level_callback(audio_level_callback_t callback)
174         {
175                 audio_level_callback = callback;
176         }
177
178         std::vector<std::string> get_transition_names()
179         {
180                 return theme->get_transition_names(pts());
181         }
182
183         unsigned get_num_channels() const
184         {
185                 return theme->get_num_channels();
186         }
187
188         std::string get_channel_name(unsigned channel) const
189         {
190                 return theme->get_channel_name(channel);
191         }
192
193         std::string get_channel_color(unsigned channel) const
194         {
195                 return theme->get_channel_color(channel);
196         }
197
198         int get_channel_signal(unsigned channel) const
199         {
200                 return theme->get_channel_signal(channel);
201         }
202
203         int map_signal(unsigned channel)
204         {
205                 return theme->map_signal(channel);
206         }
207
208         unsigned get_audio_source() const
209         {
210                 return audio_source_channel;
211         }
212
213         void set_audio_source(unsigned channel)
214         {
215                 audio_source_channel = channel;
216         }
217
218         unsigned get_master_clock() const
219         {
220                 return master_clock_channel;
221         }
222
223         void set_master_clock(unsigned channel)
224         {
225                 master_clock_channel = channel;
226         }
227
228         void set_signal_mapping(int signal, int card)
229         {
230                 return theme->set_signal_mapping(signal, card);
231         }
232
233         bool get_supports_set_wb(unsigned channel) const
234         {
235                 return theme->get_supports_set_wb(channel);
236         }
237
238         void set_wb(unsigned channel, double r, double g, double b) const
239         {
240                 theme->set_wb(channel, r, g, b);
241         }
242
243         void set_locut_cutoff(float cutoff_hz)
244         {
245                 locut_cutoff_hz = cutoff_hz;
246         }
247
248         void set_locut_enabled(bool enabled)
249         {
250                 locut_enabled = enabled;
251         }
252
253         bool get_locut_enabled() const
254         {
255                 return locut_enabled;
256         }
257
258         float get_limiter_threshold_dbfs()
259         {
260                 return limiter_threshold_dbfs;
261         }
262
263         float get_compressor_threshold_dbfs()
264         {
265                 return compressor_threshold_dbfs;
266         }
267
268         void set_limiter_threshold_dbfs(float threshold_dbfs)
269         {
270                 limiter_threshold_dbfs = threshold_dbfs;
271         }
272
273         void set_compressor_threshold_dbfs(float threshold_dbfs)
274         {
275                 compressor_threshold_dbfs = threshold_dbfs;
276         }
277
278         void set_limiter_enabled(bool enabled)
279         {
280                 limiter_enabled = enabled;
281         }
282
283         bool get_limiter_enabled() const
284         {
285                 return limiter_enabled;
286         }
287
288         void set_compressor_enabled(bool enabled)
289         {
290                 compressor_enabled = enabled;
291         }
292
293         bool get_compressor_enabled() const
294         {
295                 return compressor_enabled;
296         }
297
298         void set_gain_staging_db(float gain_db)
299         {
300                 std::unique_lock<std::mutex> lock(compressor_mutex);
301                 level_compressor_enabled = false;
302                 gain_staging_db = gain_db;
303         }
304
305         void set_gain_staging_auto(bool enabled)
306         {
307                 std::unique_lock<std::mutex> lock(compressor_mutex);
308                 level_compressor_enabled = enabled;
309         }
310
311         bool get_gain_staging_auto() const
312         {
313                 std::unique_lock<std::mutex> lock(compressor_mutex);
314                 return level_compressor_enabled;
315         }
316
317         void set_final_makeup_gain_db(float gain_db)
318         {
319                 std::unique_lock<std::mutex> lock(compressor_mutex);
320                 final_makeup_gain_auto = false;
321                 final_makeup_gain = pow(10.0f, gain_db / 20.0f);
322         }
323
324         void set_final_makeup_gain_auto(bool enabled)
325         {
326                 std::unique_lock<std::mutex> lock(compressor_mutex);
327                 final_makeup_gain_auto = enabled;
328         }
329
330         void schedule_cut()
331         {
332                 should_cut = true;
333         }
334
335         void reset_meters();
336
337         unsigned get_num_cards() const { return num_cards; }
338
339         std::string get_card_description(unsigned card_index) const {
340                 assert(card_index < num_cards);
341                 return cards[card_index].capture->get_description();
342         }
343
344         std::map<uint32_t, VideoMode> get_available_video_modes(unsigned card_index) const {
345                 assert(card_index < num_cards);
346                 return cards[card_index].capture->get_available_video_modes();
347         }
348
349         uint32_t get_current_video_mode(unsigned card_index) const {
350                 assert(card_index < num_cards);
351                 return cards[card_index].capture->get_current_video_mode();
352         }
353
354         void set_video_mode(unsigned card_index, uint32_t mode) {
355                 assert(card_index < num_cards);
356                 cards[card_index].capture->set_video_mode(mode);
357         }
358
359         void start_mode_scanning(unsigned card_index);
360
361         std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
362                 assert(card_index < num_cards);
363                 return cards[card_index].capture->get_available_video_inputs();
364         }
365
366         uint32_t get_current_video_input(unsigned card_index) const {
367                 assert(card_index < num_cards);
368                 return cards[card_index].capture->get_current_video_input();
369         }
370
371         void set_video_input(unsigned card_index, uint32_t input) {
372                 assert(card_index < num_cards);
373                 cards[card_index].capture->set_video_input(input);
374         }
375
376         std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
377                 assert(card_index < num_cards);
378                 return cards[card_index].capture->get_available_audio_inputs();
379         }
380
381         uint32_t get_current_audio_input(unsigned card_index) const {
382                 assert(card_index < num_cards);
383                 return cards[card_index].capture->get_current_audio_input();
384         }
385
386         void set_audio_input(unsigned card_index, uint32_t input) {
387                 assert(card_index < num_cards);
388                 cards[card_index].capture->set_audio_input(input);
389         }
390
391 private:
392         void configure_card(unsigned card_index, const QSurfaceFormat &format, CaptureInterface *capture);
393         void bm_frame(unsigned card_index, uint16_t timecode,
394                 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
395                 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format);
396         void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
397         void thread_func();
398         void schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame);
399         void render_one_frame(int64_t duration);
400         void send_audio_level_callback();
401         void audio_thread_func();
402         void process_audio_one_frame(int64_t frame_pts_int, int num_samples);
403         void subsample_chroma(GLuint src_tex, GLuint dst_dst);
404         void release_display_frame(DisplayFrame *frame);
405         double pts() { return double(pts_int) / TIMEBASE; }
406
407         HTTPD httpd;
408         unsigned num_cards;
409
410         QSurface *mixer_surface, *h264_encoder_surface;
411         std::unique_ptr<movit::ResourcePool> resource_pool;
412         std::unique_ptr<Theme> theme;
413         std::atomic<unsigned> audio_source_channel{0};
414         std::atomic<unsigned> master_clock_channel{0};
415         std::unique_ptr<movit::EffectChain> display_chain;
416         GLuint cbcr_program_num;  // Owned by <resource_pool>.
417         GLuint cbcr_vbo;  // Holds position and texcoord data.
418         GLuint cbcr_position_attribute_index, cbcr_texcoord_attribute_index;
419         std::unique_ptr<VideoEncoder> video_encoder;
420
421         // Effects part of <display_chain>. Owned by <display_chain>.
422         movit::FlatInput *display_input;
423
424         int64_t pts_int = 0;  // In TIMEBASE units.
425
426         std::mutex bmusb_mutex;
427         bool has_bmusb_thread = false;
428         struct CaptureCard {
429                 CaptureInterface *capture;
430                 std::unique_ptr<PBOFrameAllocator> frame_allocator;
431
432                 // Stuff for the OpenGL context (for texture uploading).
433                 QSurface *surface;
434                 QOpenGLContext *context;
435
436                 struct NewFrame {
437                         RefCountedFrame frame;
438                         int64_t length;  // In TIMEBASE units.
439                         bool interlaced;
440                         unsigned field;  // Which field (0 or 1) of the frame to use. Always 0 for progressive.
441                         std::function<void()> upload_func;  // Needs to be called to actually upload the texture to OpenGL.
442                         unsigned dropped_frames = 0;  // Number of dropped frames before this one.
443                 };
444                 std::queue<NewFrame> new_frames;
445                 bool should_quit = false;
446                 std::condition_variable new_frames_changed;  // Set whenever new_frames (or should_quit) is changed.
447
448                 QueueLengthPolicy queue_length_policy;  // Refers to the "new_frames" queue.
449
450                 // Accumulated errors in number of 1/TIMEBASE samples. If OUTPUT_FREQUENCY divided by
451                 // frame rate is integer, will always stay zero.
452                 unsigned fractional_samples = 0;
453
454                 std::mutex audio_mutex;
455                 std::unique_ptr<ResamplingQueue> resampling_queue;  // Under audio_mutex.
456                 int last_timecode = -1;  // Unwrapped.
457                 int64_t next_local_pts = 0;  // Beginning of next frame, in TIMEBASE units.
458         };
459         CaptureCard cards[MAX_CARDS];  // protected by <bmusb_mutex>
460         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]);
461
462         InputState input_state;
463
464         class OutputChannel {
465         public:
466                 ~OutputChannel();
467                 void output_frame(DisplayFrame frame);
468                 bool get_display_frame(DisplayFrame *frame);
469                 void set_frame_ready_callback(new_frame_ready_callback_t callback);
470                 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
471                 void set_name_updated_callback(name_updated_callback_t callback);
472                 void set_color_updated_callback(color_updated_callback_t callback);
473
474         private:
475                 friend class Mixer;
476
477                 unsigned channel;
478                 Mixer *parent = nullptr;  // Not owned.
479                 std::mutex frame_mutex;
480                 DisplayFrame current_frame, ready_frame;  // protected by <frame_mutex>
481                 bool has_current_frame = false, has_ready_frame = false;  // protected by <frame_mutex>
482                 new_frame_ready_callback_t new_frame_ready_callback;
483                 transition_names_updated_callback_t transition_names_updated_callback;
484                 name_updated_callback_t name_updated_callback;
485                 color_updated_callback_t color_updated_callback;
486
487                 std::vector<std::string> last_transition_names;
488                 std::string last_name, last_color;
489         };
490         OutputChannel output_channel[NUM_OUTPUTS];
491
492         std::thread mixer_thread;
493         std::thread audio_thread;
494         std::atomic<bool> should_quit{false};
495         std::atomic<bool> should_cut{false};
496
497         audio_level_callback_t audio_level_callback = nullptr;
498         mutable std::mutex compressor_mutex;
499         Ebu_r128_proc r128;  // Under compressor_mutex.
500         CorrelationMeasurer correlation;  // Under compressor_mutex.
501
502         Resampler peak_resampler;
503         std::atomic<float> peak{0.0f};
504
505         StereoFilter locut;  // Default cutoff 120 Hz, 24 dB/oct.
506         std::atomic<float> locut_cutoff_hz;
507         std::atomic<bool> locut_enabled{true};
508
509         // First compressor; takes us up to about -12 dBFS.
510         StereoCompressor level_compressor;  // Under compressor_mutex. Used to set/override gain_staging_db if <level_compressor_enabled>.
511         float gain_staging_db = 0.0f;  // Under compressor_mutex.
512         bool level_compressor_enabled = true;  // Under compressor_mutex.
513
514         static constexpr float ref_level_dbfs = -14.0f;  // Chosen so that we end up around 0 LU in practice.
515         static constexpr float ref_level_lufs = -23.0f;  // 0 LU, more or less by definition.
516
517         StereoCompressor limiter;
518         std::atomic<float> limiter_threshold_dbfs{ref_level_dbfs + 4.0f};   // 4 dB.
519         std::atomic<bool> limiter_enabled{true};
520         StereoCompressor compressor;
521         std::atomic<float> compressor_threshold_dbfs{ref_level_dbfs - 12.0f};  // -12 dB.
522         std::atomic<bool> compressor_enabled{true};
523
524         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.
525         bool final_makeup_gain_auto = true;  // Under compressor_mutex.
526
527         std::unique_ptr<ALSAOutput> alsa;
528
529         struct AudioTask {
530                 int64_t pts_int;
531                 int num_samples;
532         };
533         std::mutex audio_mutex;
534         std::condition_variable audio_task_queue_changed;
535         std::queue<AudioTask> audio_task_queue;  // Under audio_mutex.
536
537         // For mode scanning.
538         bool is_mode_scanning[MAX_CARDS]{ false };
539         std::vector<uint32_t> mode_scanlist[MAX_CARDS];
540         unsigned mode_scanlist_index[MAX_CARDS]{ 0 };
541         timespec last_mode_scan_change[MAX_CARDS];
542 };
543
544 extern Mixer *global_mixer;
545 extern bool uses_mlock;
546
547 #endif  // !defined(_MIXER_H)