]> git.sesse.net Git - nageru/blob - mixer.h
Add a final makeup gain, trying to set the level straight at +0 LU (more or less...
[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 "h264encode.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
39 class H264Encoder;
40 class QSurface;
41 namespace movit {
42 class Effect;
43 class EffectChain;
44 class FlatInput;
45 class ResourcePool;
46 }  // namespace movit
47
48 namespace movit {
49 class YCbCrInput;
50 }
51 class QOpenGLContext;
52 class QSurfaceFormat;
53
54 class Mixer {
55 public:
56         // The surface format is used for offscreen destinations for OpenGL contexts we need.
57         Mixer(const QSurfaceFormat &format, unsigned num_cards);
58         ~Mixer();
59         void start();
60         void quit();
61
62         void transition_clicked(int transition_num);
63         void channel_clicked(int preview_num);
64
65         enum Output {
66                 OUTPUT_LIVE = 0,
67                 OUTPUT_PREVIEW,
68                 OUTPUT_INPUT0,  // 1, 2, 3, up to 15 follow numerically.
69                 NUM_OUTPUTS = 18
70         };
71
72         struct DisplayFrame {
73                 // The chain for rendering this frame. To render a display frame,
74                 // first wait for <ready_fence>, then call <setup_chain>
75                 // to wire up all the inputs, and then finally call
76                 // chain->render_to_screen() or similar.
77                 movit::EffectChain *chain;
78                 std::function<void()> setup_chain;
79
80                 // Asserted when all the inputs are ready; you cannot render the chain
81                 // before this.
82                 RefCountedGLsync ready_fence;
83
84                 // Holds on to all the input frames needed for this display frame,
85                 // so they are not released while still rendering.
86                 std::vector<RefCountedFrame> input_frames;
87
88                 // Textures that should be released back to the resource pool
89                 // when this frame disappears, if any.
90                 // TODO: Refcount these as well?
91                 std::vector<GLuint> temp_textures;
92         };
93         // Implicitly frees the previous one if there's a new frame available.
94         bool get_display_frame(Output output, DisplayFrame *frame) {
95                 return output_channel[output].get_display_frame(frame);
96         }
97
98         typedef std::function<void()> new_frame_ready_callback_t;
99         void set_frame_ready_callback(Output output, new_frame_ready_callback_t callback)
100         {
101                 output_channel[output].set_frame_ready_callback(callback);
102         }
103
104         typedef std::function<void(float level_lufs, float peak_db,
105                                    float global_level_lufs, float range_low_lufs, float range_high_lufs,
106                                    float gain_staging_db, float final_makeup_gain_db)> audio_level_callback_t;
107         void set_audio_level_callback(audio_level_callback_t callback)
108         {
109                 audio_level_callback = callback;
110         }
111
112         std::vector<std::string> get_transition_names()
113         {
114                 return theme->get_transition_names(pts());
115         }
116
117         unsigned get_num_channels() const
118         {
119                 return theme->get_num_channels();
120         }
121
122         std::string get_channel_name(unsigned channel) const
123         {
124                 return theme->get_channel_name(channel);
125         }
126
127         bool get_supports_set_wb(unsigned channel) const
128         {
129                 return theme->get_supports_set_wb(channel);
130         }
131
132         void set_wb(unsigned channel, double r, double g, double b) const
133         {
134                 theme->set_wb(channel, r, g, b);
135         }
136
137         void set_locut_cutoff(float cutoff_hz)
138         {
139                 locut_cutoff_hz = cutoff_hz;
140         }
141
142         float get_limiter_threshold_dbfs()
143         {
144                 return limiter_threshold_dbfs;
145         }
146
147         float get_compressor_threshold_dbfs()
148         {
149                 return compressor_threshold_dbfs;
150         }
151
152         void set_limiter_threshold_dbfs(float threshold_dbfs)
153         {
154                 limiter_threshold_dbfs = threshold_dbfs;
155         }
156
157         void set_compressor_threshold_dbfs(float threshold_dbfs)
158         {
159                 compressor_threshold_dbfs = threshold_dbfs;
160         }
161
162         void set_limiter_enabled(bool enabled)
163         {
164                 limiter_enabled = enabled;
165         }
166
167         void set_compressor_enabled(bool enabled)
168         {
169                 compressor_enabled = enabled;
170         }
171
172         void set_gain_staging_db(float gain_db)
173         {
174                 std::unique_lock<std::mutex> lock(compressor_mutex);
175                 level_compressor_enabled = false;
176                 gain_staging_db = gain_db;
177         }
178
179         void set_gain_staging_auto(bool enabled)
180         {
181                 std::unique_lock<std::mutex> lock(compressor_mutex);
182                 level_compressor_enabled = enabled;
183         }
184
185         void set_final_makeup_gain_db(float gain_db)
186         {
187                 std::unique_lock<std::mutex> lock(compressor_mutex);
188                 final_makeup_gain_auto = false;
189                 final_makeup_gain = pow(10.0f, gain_db / 20.0f);
190         }
191
192         void set_final_makeup_gain_auto(bool enabled)
193         {
194                 std::unique_lock<std::mutex> lock(compressor_mutex);
195                 final_makeup_gain_auto = enabled;
196         }
197
198         void schedule_cut()
199         {
200                 should_cut = true;
201         }
202
203         void reset_meters();
204
205 private:
206         void bm_frame(unsigned card_index, uint16_t timecode,
207                 FrameAllocator::Frame video_frame, size_t video_offset, uint16_t video_format,
208                 FrameAllocator::Frame audio_frame, size_t audio_offset, uint16_t audio_format);
209         void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
210         void thread_func();
211         void audio_thread_func();
212         void process_audio_one_frame(int64_t frame_pts_int, int num_samples);
213         void subsample_chroma(GLuint src_tex, GLuint dst_dst);
214         void release_display_frame(DisplayFrame *frame);
215         double pts() { return double(pts_int) / TIMEBASE; }
216
217         HTTPD httpd;
218         unsigned num_cards;
219
220         QSurface *mixer_surface, *h264_encoder_surface;
221         std::unique_ptr<movit::ResourcePool> resource_pool;
222         std::unique_ptr<Theme> theme;
223         std::unique_ptr<movit::EffectChain> display_chain;
224         GLuint cbcr_program_num;  // Owned by <resource_pool>.
225         std::unique_ptr<H264Encoder> h264_encoder;
226
227         // Effects part of <display_chain>. Owned by <display_chain>.
228         movit::FlatInput *display_input;
229
230         int64_t pts_int = 0;  // In TIMEBASE units.
231
232         std::mutex bmusb_mutex;
233         struct CaptureCard {
234                 BMUSBCapture *usb;
235                 std::unique_ptr<PBOFrameAllocator> frame_allocator;
236
237                 // Stuff for the OpenGL context (for texture uploading).
238                 QSurface *surface;
239                 QOpenGLContext *context;
240
241                 bool new_data_ready = false;  // Whether new_frame contains anything.
242                 bool should_quit = false;
243                 RefCountedFrame new_frame;
244                 int64_t new_frame_length;  // In TIMEBASE units.
245                 bool new_frame_interlaced;
246                 unsigned new_frame_field;  // Which field (0 or 1) of the frame to use. Always 0 for progressive.
247                 GLsync new_data_ready_fence;  // Whether new_frame is ready for rendering.
248                 std::condition_variable new_data_ready_changed;  // Set whenever new_data_ready is changed.
249                 unsigned dropped_frames = 0;  // Before new_frame.
250
251                 // Accumulated errors in number of 1/TIMEBASE samples. If OUTPUT_FREQUENCY divided by
252                 // frame rate is integer, will always stay zero.
253                 unsigned fractional_samples = 0;
254
255                 std::mutex audio_mutex;
256                 std::unique_ptr<ResamplingQueue> resampling_queue;  // Under audio_mutex.
257                 int last_timecode = -1;  // Unwrapped.
258                 int64_t next_local_pts = 0;  // Beginning of next frame, in TIMEBASE units.
259         };
260         CaptureCard cards[MAX_CARDS];  // protected by <bmusb_mutex>
261
262         InputState input_state;
263
264         class OutputChannel {
265         public:
266                 ~OutputChannel();
267                 void output_frame(DisplayFrame frame);
268                 bool get_display_frame(DisplayFrame *frame);
269                 void set_frame_ready_callback(new_frame_ready_callback_t callback);
270
271         private:
272                 friend class Mixer;
273
274                 Mixer *parent = nullptr;  // Not owned.
275                 std::mutex frame_mutex;
276                 DisplayFrame current_frame, ready_frame;  // protected by <frame_mutex>
277                 bool has_current_frame = false, has_ready_frame = false;  // protected by <frame_mutex>
278                 new_frame_ready_callback_t new_frame_ready_callback;
279                 bool has_new_frame_ready_callback = false;
280         };
281         OutputChannel output_channel[NUM_OUTPUTS];
282
283         std::thread mixer_thread;
284         std::thread audio_thread;
285         std::atomic<bool> should_quit{false};
286         std::atomic<bool> should_cut{false};
287
288         audio_level_callback_t audio_level_callback = nullptr;
289         std::mutex compressor_mutex;
290         Ebu_r128_proc r128;  // Under compressor_mutex.
291
292         Resampler peak_resampler;
293         std::atomic<float> peak{0.0f};
294
295         StereoFilter locut;  // Default cutoff 150 Hz, 24 dB/oct.
296         std::atomic<float> locut_cutoff_hz;
297
298         // First compressor; takes us up to about -12 dBFS.
299         StereoCompressor level_compressor;  // Under compressor_mutex. Used to set/override gain_staging_db if <level_compressor_enabled>.
300         float gain_staging_db = 0.0f;  // Under compressor_mutex.
301         bool level_compressor_enabled = true;  // Under compressor_mutex.
302
303         static constexpr float ref_level_dbfs = -14.0f;  // Chosen so that we end up around 0 LU in practice.
304         static constexpr float ref_level_lufs = -23.0f;  // 0 LU, more or less by definition.
305
306         StereoCompressor limiter;
307         std::atomic<float> limiter_threshold_dbfs{ref_level_dbfs + 4.0f};   // 4 dB.
308         std::atomic<bool> limiter_enabled{true};
309         StereoCompressor compressor;
310         std::atomic<float> compressor_threshold_dbfs{ref_level_dbfs - 12.0f};  // -12 dB.
311         std::atomic<bool> compressor_enabled{true};
312
313         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.
314         bool final_makeup_gain_auto = true;  // Under compressor_mutex.
315
316         std::unique_ptr<ALSAOutput> alsa;
317
318         struct AudioTask {
319                 int64_t pts_int;
320                 int num_samples;
321         };
322         std::mutex audio_mutex;
323         std::condition_variable audio_task_queue_changed;
324         std::queue<AudioTask> audio_task_queue;  // Under audio_mutex.
325 };
326
327 extern Mixer *global_mixer;
328
329 #endif  // !defined(_MIXER_H)