]> git.sesse.net Git - nageru/blob - mixer.cpp
Do not use the timing of dropped frames as part of the video master clock.
[nageru] / mixer.cpp
1 #undef Success
2
3 #include "mixer.h"
4
5 #include <assert.h>
6 #include <endian.h>
7 #include <epoxy/egl.h>
8 #include <movit/effect_chain.h>
9 #include <movit/effect_util.h>
10 #include <movit/flat_input.h>
11 #include <movit/image_format.h>
12 #include <movit/init.h>
13 #include <movit/resource_pool.h>
14 #include <movit/util.h>
15 #include <stdint.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <sys/time.h>
19 #include <time.h>
20 #include <algorithm>
21 #include <chrono>
22 #include <cmath>
23 #include <condition_variable>
24 #include <cstddef>
25 #include <memory>
26 #include <mutex>
27 #include <string>
28 #include <thread>
29 #include <utility>
30 #include <vector>
31 #include <arpa/inet.h>
32 #include <sys/time.h>
33 #include <sys/resource.h>
34
35 #include "bmusb/bmusb.h"
36 #include "bmusb/fake_capture.h"
37 #include "context.h"
38 #include "decklink_capture.h"
39 #include "defs.h"
40 #include "flags.h"
41 #include "video_encoder.h"
42 #include "pbo_frame_allocator.h"
43 #include "ref_counted_gl_sync.h"
44 #include "timebase.h"
45
46 class QOpenGLContext;
47
48 using namespace movit;
49 using namespace std;
50 using namespace std::chrono;
51 using namespace std::placeholders;
52 using namespace bmusb;
53
54 Mixer *global_mixer = nullptr;
55 bool uses_mlock = false;
56
57 namespace {
58
59 void convert_fixed24_to_fp32(float *dst, size_t out_channels, const uint8_t *src, size_t in_channels, size_t num_samples)
60 {
61         assert(in_channels >= out_channels);
62         for (size_t i = 0; i < num_samples; ++i) {
63                 for (size_t j = 0; j < out_channels; ++j) {
64                         uint32_t s1 = *src++;
65                         uint32_t s2 = *src++;
66                         uint32_t s3 = *src++;
67                         uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
68                         dst[i * out_channels + j] = int(s) * (1.0f / 2147483648.0f);
69                 }
70                 src += 3 * (in_channels - out_channels);
71         }
72 }
73
74 void convert_fixed32_to_fp32(float *dst, size_t out_channels, const uint8_t *src, size_t in_channels, size_t num_samples)
75 {
76         assert(in_channels >= out_channels);
77         for (size_t i = 0; i < num_samples; ++i) {
78                 for (size_t j = 0; j < out_channels; ++j) {
79                         int32_t s = le32toh(*(int32_t *)src);
80                         dst[i * out_channels + j] = s * (1.0f / 2147483648.0f);
81                         src += 4;
82                 }
83                 src += 4 * (in_channels - out_channels);
84         }
85 }
86
87 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
88 {
89         if (interlaced) {
90                 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) {  // :-)
91                         input_state->buffered_frames[card_index][frame_num] =
92                                 input_state->buffered_frames[card_index][frame_num - 1];
93                 }
94                 input_state->buffered_frames[card_index][0] = { frame, field_num };
95         } else {
96                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
97                         input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
98                 }
99         }
100 }
101
102 }  // namespace
103
104 void QueueLengthPolicy::update_policy(int queue_length)
105 {
106         if (queue_length < 0) {  // Starvation.
107                 if (been_at_safe_point_since_last_starvation && safe_queue_length < 5) {
108                         ++safe_queue_length;
109                         fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frames\n",
110                                 card_index, safe_queue_length);
111                 }
112                 frames_with_at_least_one = 0;
113                 been_at_safe_point_since_last_starvation = false;
114                 return;
115         }
116         if (queue_length > 0) {
117                 if (queue_length >= int(safe_queue_length)) {
118                         been_at_safe_point_since_last_starvation = true;
119                 }
120                 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 0) {
121                         --safe_queue_length;
122                         fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frames\n",
123                                 card_index, safe_queue_length);
124                         frames_with_at_least_one = 0;
125                 }
126         } else {
127                 frames_with_at_least_one = 0;
128         }
129 }
130
131 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
132         : httpd(),
133           num_cards(num_cards),
134           mixer_surface(create_surface(format)),
135           h264_encoder_surface(create_surface(format)),
136           correlation(OUTPUT_FREQUENCY),
137           level_compressor(OUTPUT_FREQUENCY),
138           limiter(OUTPUT_FREQUENCY),
139           compressor(OUTPUT_FREQUENCY)
140 {
141         CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
142         check_error();
143
144         // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
145         // will be halved when sampling them, and we need to compensate here.
146         movit_texel_subpixel_precision /= 2.0;
147
148         resource_pool.reset(new ResourcePool);
149         theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get(), num_cards));
150         for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
151                 output_channel[i].parent = this;
152                 output_channel[i].channel = i;
153         }
154
155         ImageFormat inout_format;
156         inout_format.color_space = COLORSPACE_sRGB;
157         inout_format.gamma_curve = GAMMA_sRGB;
158
159         // Display chain; shows the live output produced by the main chain (its RGBA version).
160         display_chain.reset(new EffectChain(WIDTH, HEIGHT, resource_pool.get()));
161         check_error();
162         display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, WIDTH, HEIGHT);  // FIXME: GL_UNSIGNED_BYTE is really wrong.
163         display_chain->add_input(display_input);
164         display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
165         display_chain->set_dither_bits(0);  // Don't bother.
166         display_chain->finalize();
167
168         video_encoder.reset(new VideoEncoder(resource_pool.get(), h264_encoder_surface, global_flags.va_display, WIDTH, HEIGHT, &httpd));
169
170         // Start listening for clients only once VideoEncoder has written its header, if any.
171         httpd.start(9095);
172
173         // First try initializing the then PCI devices, then USB, then
174         // fill up with fake cards until we have the desired number of cards.
175         unsigned num_pci_devices = 0;
176         unsigned card_index = 0;
177
178         {
179                 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
180                 if (decklink_iterator != nullptr) {
181                         for ( ; card_index < num_cards; ++card_index) {
182                                 IDeckLink *decklink;
183                                 if (decklink_iterator->Next(&decklink) != S_OK) {
184                                         break;
185                                 }
186
187                                 configure_card(card_index, new DeckLinkCapture(decklink, card_index), /*is_fake_capture=*/false);
188                                 ++num_pci_devices;
189                         }
190                         decklink_iterator->Release();
191                         fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
192                 } else {
193                         fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
194                 }
195         }
196         unsigned num_usb_devices = BMUSBCapture::num_cards();
197         for (unsigned usb_card_index = 0; usb_card_index < num_usb_devices && card_index < num_cards; ++usb_card_index, ++card_index) {
198                 BMUSBCapture *capture = new BMUSBCapture(usb_card_index);
199                 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, card_index));
200                 configure_card(card_index, capture, /*is_fake_capture=*/false);
201         }
202         fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
203
204         unsigned num_fake_cards = 0;
205         for ( ; card_index < num_cards; ++card_index, ++num_fake_cards) {
206                 FakeCapture *capture = new FakeCapture(WIDTH, HEIGHT, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
207                 configure_card(card_index, capture, /*is_fake_capture=*/true);
208         }
209
210         if (num_fake_cards > 0) {
211                 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
212         }
213
214         BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
215         BMUSBCapture::start_bm_thread();
216
217         for (card_index = 0; card_index < num_cards; ++card_index) {
218                 cards[card_index].queue_length_policy.reset(card_index);
219                 cards[card_index].capture->start_bm_capture();
220         }
221
222         // Set up stuff for NV12 conversion.
223
224         // Cb/Cr shader.
225         string cbcr_vert_shader =
226                 "#version 130 \n"
227                 " \n"
228                 "in vec2 position; \n"
229                 "in vec2 texcoord; \n"
230                 "out vec2 tc0; \n"
231                 "uniform vec2 foo_chroma_offset_0; \n"
232                 " \n"
233                 "void main() \n"
234                 "{ \n"
235                 "    // The result of glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0) is: \n"
236                 "    // \n"
237                 "    //   2.000  0.000  0.000 -1.000 \n"
238                 "    //   0.000  2.000  0.000 -1.000 \n"
239                 "    //   0.000  0.000 -2.000 -1.000 \n"
240                 "    //   0.000  0.000  0.000  1.000 \n"
241                 "    gl_Position = vec4(2.0 * position.x - 1.0, 2.0 * position.y - 1.0, -1.0, 1.0); \n"
242                 "    vec2 flipped_tc = texcoord; \n"
243                 "    tc0 = flipped_tc + foo_chroma_offset_0; \n"
244                 "} \n";
245         string cbcr_frag_shader =
246                 "#version 130 \n"
247                 "in vec2 tc0; \n"
248                 "uniform sampler2D cbcr_tex; \n"
249                 "out vec4 FragColor; \n"
250                 "void main() { \n"
251                 "    FragColor = texture(cbcr_tex, tc0); \n"
252                 "} \n";
253         vector<string> frag_shader_outputs;
254         cbcr_program_num = resource_pool->compile_glsl_program(cbcr_vert_shader, cbcr_frag_shader, frag_shader_outputs);
255
256         float vertices[] = {
257                 0.0f, 2.0f,
258                 0.0f, 0.0f,
259                 2.0f, 0.0f
260         };
261         cbcr_vbo = generate_vbo(2, GL_FLOAT, sizeof(vertices), vertices);
262         cbcr_position_attribute_index = glGetAttribLocation(cbcr_program_num, "position");
263         cbcr_texcoord_attribute_index = glGetAttribLocation(cbcr_program_num, "texcoord");
264
265         r128.init(2, OUTPUT_FREQUENCY);
266         r128.integr_start();
267
268         locut.init(FILTER_HPF, 2);
269
270         set_locut_enabled(global_flags.locut_enabled);
271         set_gain_staging_db(global_flags.initial_gain_staging_db);
272         set_gain_staging_auto(global_flags.gain_staging_auto);
273         set_compressor_enabled(global_flags.compressor_enabled);
274         set_limiter_enabled(global_flags.limiter_enabled);
275         set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
276
277         // hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise,
278         // and there's a limit to how important the peak meter is.
279         peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0);
280
281         if (global_flags.enable_alsa_output) {
282                 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
283         }
284 }
285
286 Mixer::~Mixer()
287 {
288         resource_pool->release_glsl_program(cbcr_program_num);
289         glDeleteBuffers(1, &cbcr_vbo);
290         BMUSBCapture::stop_bm_thread();
291
292         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
293                 {
294                         unique_lock<mutex> lock(bmusb_mutex);
295                         cards[card_index].should_quit = true;  // Unblock thread.
296                         cards[card_index].new_frames_changed.notify_all();
297                 }
298                 cards[card_index].capture->stop_dequeue_thread();
299         }
300
301         video_encoder.reset(nullptr);
302 }
303
304 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture)
305 {
306         printf("Configuring card %d...\n", card_index);
307
308         CaptureCard *card = &cards[card_index];
309         if (card->capture != nullptr) {
310                 card->capture->stop_dequeue_thread();
311                 delete card->capture;
312         }
313         card->capture = capture;
314         card->is_fake_capture = is_fake_capture;
315         card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
316         if (card->frame_allocator == nullptr) {
317                 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, WIDTH, HEIGHT));  // 8 MB.
318         }
319         card->capture->set_video_frame_allocator(card->frame_allocator.get());
320         if (card->surface == nullptr) {
321                 card->surface = create_surface_with_same_format(mixer_surface);
322         }
323         {
324                 unique_lock<mutex> lock(cards[card_index].audio_mutex);
325                 card->resampling_queue.reset(new ResamplingQueue(card_index, OUTPUT_FREQUENCY, OUTPUT_FREQUENCY, 2));
326         }
327         while (!card->new_frames.empty()) card->new_frames.pop();
328         card->fractional_samples = 0;
329         card->last_timecode = -1;
330         card->next_local_pts = 0;
331         card->capture->configure_card();
332 }
333
334
335 namespace {
336
337 int unwrap_timecode(uint16_t current_wrapped, int last)
338 {
339         uint16_t last_wrapped = last & 0xffff;
340         if (current_wrapped > last_wrapped) {
341                 return (last & ~0xffff) | current_wrapped;
342         } else {
343                 return 0x10000 + ((last & ~0xffff) | current_wrapped);
344         }
345 }
346
347 float find_peak(const float *samples, size_t num_samples)
348 {
349         float m = fabs(samples[0]);
350         for (size_t i = 1; i < num_samples; ++i) {
351                 m = max(m, fabs(samples[i]));
352         }
353         return m;
354 }
355
356 void deinterleave_samples(const vector<float> &in, vector<float> *out_l, vector<float> *out_r)
357 {
358         size_t num_samples = in.size() / 2;
359         out_l->resize(num_samples);
360         out_r->resize(num_samples);
361
362         const float *inptr = in.data();
363         float *lptr = &(*out_l)[0];
364         float *rptr = &(*out_r)[0];
365         for (size_t i = 0; i < num_samples; ++i) {
366                 *lptr++ = *inptr++;
367                 *rptr++ = *inptr++;
368         }
369 }
370
371 }  // namespace
372
373 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
374                      FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
375                      FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
376 {
377         CaptureCard *card = &cards[card_index];
378
379         if (is_mode_scanning[card_index]) {
380                 if (video_format.has_signal) {
381                         // Found a stable signal, so stop scanning.
382                         is_mode_scanning[card_index] = false;
383                 } else {
384                         static constexpr double switch_time_s = 0.5;  // Should be enough time for the signal to stabilize.
385                         steady_clock::time_point now = steady_clock::now();
386                         double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
387                         if (sec_since_last_switch > switch_time_s) {
388                                 // It isn't this mode; try the next one.
389                                 mode_scanlist_index[card_index]++;
390                                 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
391                                 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
392                                 last_mode_scan_change[card_index] = now;
393                         }
394                 }
395         }
396
397         int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
398         assert(frame_length > 0);
399
400         size_t num_samples = (audio_frame.len > audio_offset) ? (audio_frame.len - audio_offset) / audio_format.num_channels / (audio_format.bits_per_sample / 8) : 0;
401         if (num_samples > OUTPUT_FREQUENCY / 10) {
402                 printf("Card %d: Dropping frame with implausible audio length (len=%d, offset=%d) [timecode=0x%04x video_len=%d video_offset=%d video_format=%x)\n",
403                         card_index, int(audio_frame.len), int(audio_offset),
404                         timecode, int(video_frame.len), int(video_offset), video_format.id);
405                 if (video_frame.owner) {
406                         video_frame.owner->release_frame(video_frame);
407                 }
408                 if (audio_frame.owner) {
409                         audio_frame.owner->release_frame(audio_frame);
410                 }
411                 return;
412         }
413
414         int64_t local_pts = card->next_local_pts;
415         int dropped_frames = 0;
416         if (card->last_timecode != -1) {
417                 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
418         }
419
420         // Convert the audio to stereo fp32 and add it.
421         vector<float> audio;
422         audio.resize(num_samples * 2);
423         switch (audio_format.bits_per_sample) {
424         case 0:
425                 assert(num_samples == 0);
426                 break;
427         case 24:
428                 convert_fixed24_to_fp32(&audio[0], 2, audio_frame.data + audio_offset, audio_format.num_channels, num_samples);
429                 break;
430         case 32:
431                 convert_fixed32_to_fp32(&audio[0], 2, audio_frame.data + audio_offset, audio_format.num_channels, num_samples);
432                 break;
433         default:
434                 fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
435                 assert(false);
436         }
437
438         // Add the audio.
439         {
440                 unique_lock<mutex> lock(card->audio_mutex);
441
442                 // Number of samples per frame if we need to insert silence.
443                 // (Could be nonintegral, but resampling will save us then.)
444                 int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
445
446                 if (dropped_frames > MAX_FPS * 2) {
447                         fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
448                                 card_index, card->last_timecode, timecode);
449                         card->resampling_queue.reset(new ResamplingQueue(card_index, OUTPUT_FREQUENCY, OUTPUT_FREQUENCY, 2));
450                         dropped_frames = 0;
451                 } else if (dropped_frames > 0) {
452                         // Insert silence as needed.
453                         fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
454                                 card_index, dropped_frames, timecode);
455                         vector<float> silence(silence_samples * 2, 0.0f);
456                         for (int i = 0; i < dropped_frames; ++i) {
457                                 card->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), silence.data(), silence_samples);
458                                 // Note that if the format changed in the meantime, we have
459                                 // no way of detecting that; we just have to assume the frame length
460                                 // is always the same.
461                                 local_pts += frame_length;
462                         }
463                 }
464                 if (num_samples == 0) {
465                         audio.resize(silence_samples * 2);
466                         num_samples = silence_samples;
467                 }
468                 card->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.data(), num_samples);
469                 card->next_local_pts = local_pts + frame_length;
470         }
471
472         card->last_timecode = timecode;
473
474         // Done with the audio, so release it.
475         if (audio_frame.owner) {
476                 audio_frame.owner->release_frame(audio_frame);
477         }
478
479         size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
480         if (video_frame.len - video_offset == 0 ||
481             video_frame.len - video_offset != expected_length) {
482                 if (video_frame.len != 0) {
483                         printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
484                                 card_index, video_frame.len - video_offset, expected_length);
485                 }
486                 if (video_frame.owner) {
487                         video_frame.owner->release_frame(video_frame);
488                 }
489
490                 // Still send on the information that we _had_ a frame, even though it's corrupted,
491                 // so that pts can go up accordingly.
492                 {
493                         unique_lock<mutex> lock(bmusb_mutex);
494                         CaptureCard::NewFrame new_frame;
495                         new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
496                         new_frame.length = frame_length;
497                         new_frame.interlaced = false;
498                         new_frame.dropped_frames = dropped_frames;
499                         card->new_frames.push(move(new_frame));
500                         card->new_frames_changed.notify_all();
501                 }
502                 return;
503         }
504
505         PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
506
507         unsigned num_fields = video_format.interlaced ? 2 : 1;
508         steady_clock::time_point frame_upload_start;
509         if (video_format.interlaced) {
510                 // Send the two fields along as separate frames; the other side will need to add
511                 // a deinterlacer to actually get this right.
512                 assert(video_format.height % 2 == 0);
513                 video_format.height /= 2;
514                 assert(frame_length % 2 == 0);
515                 frame_length /= 2;
516                 num_fields = 2;
517                 frame_upload_start = steady_clock::now();
518         }
519         userdata->last_interlaced = video_format.interlaced;
520         userdata->last_has_signal = video_format.has_signal;
521         userdata->last_is_connected = video_format.is_connected;
522         userdata->last_frame_rate_nom = video_format.frame_rate_nom;
523         userdata->last_frame_rate_den = video_format.frame_rate_den;
524         RefCountedFrame frame(video_frame);
525
526         // Upload the textures.
527         size_t cbcr_width = video_format.width / 2;
528         size_t cbcr_offset = video_offset / 2;
529         size_t y_offset = video_frame.size / 2 + video_offset / 2;
530
531         for (unsigned field = 0; field < num_fields; ++field) {
532                 // Put the actual texture upload in a lambda that is executed in the main thread.
533                 // It is entirely possible to do this in the same thread (and it might even be
534                 // faster, depending on the GPU and driver), but it appears to be trickling
535                 // driver bugs very easily.
536                 //
537                 // Note that this means we must hold on to the actual frame data in <userdata>
538                 // until the upload command is run, but we hold on to <frame> much longer than that
539                 // (in fact, all the way until we no longer use the texture in rendering).
540                 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, userdata]() {
541                         unsigned field_start_line = (field == 1) ? video_format.second_field_start : video_format.extra_lines_top + field * (video_format.height + 22);
542
543                         if (userdata->tex_y[field] == 0 ||
544                             userdata->tex_cbcr[field] == 0 ||
545                             video_format.width != userdata->last_width[field] ||
546                             video_format.height != userdata->last_height[field]) {
547                                 // We changed resolution since last use of this texture, so we need to create
548                                 // a new object. Note that this each card has its own PBOFrameAllocator,
549                                 // we don't need to worry about these flip-flopping between resolutions.
550                                 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
551                                 check_error();
552                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
553                                 check_error();
554                                 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
555                                 check_error();
556                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
557                                 check_error();
558                                 userdata->last_width[field] = video_format.width;
559                                 userdata->last_height[field] = video_format.height;
560                         }
561
562                         GLuint pbo = userdata->pbo;
563                         check_error();
564                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
565                         check_error();
566
567                         size_t field_y_start = y_offset + video_format.width * field_start_line;
568                         size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
569
570                         if (global_flags.flush_pbos) {
571                                 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
572                                 check_error();
573                                 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
574                                 check_error();
575                         }
576
577                         glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
578                         check_error();
579                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
580                         check_error();
581                         glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
582                         check_error();
583                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
584                         check_error();
585                         glBindTexture(GL_TEXTURE_2D, 0);
586                         check_error();
587                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
588                         check_error();
589                 };
590
591                 if (field == 1) {
592                         // Don't upload the second field as fast as we can; wait until
593                         // the field time has approximately passed. (Otherwise, we could
594                         // get timing jitter against the other sources, and possibly also
595                         // against the video display, although the latter is not as critical.)
596                         // This requires our system clock to be reasonably close to the
597                         // video clock, but that's not an unreasonable assumption.
598                         steady_clock::time_point second_field_start = frame_upload_start +
599                                 nanoseconds(frame_length * 1000000000 / TIMEBASE);
600                         this_thread::sleep_until(second_field_start);
601                 }
602
603                 {
604                         unique_lock<mutex> lock(bmusb_mutex);
605                         CaptureCard::NewFrame new_frame;
606                         new_frame.frame = frame;
607                         new_frame.length = frame_length;
608                         new_frame.field = field;
609                         new_frame.interlaced = video_format.interlaced;
610                         new_frame.upload_func = upload_func;
611                         new_frame.dropped_frames = dropped_frames;
612                         card->new_frames.push(move(new_frame));
613                         card->new_frames_changed.notify_all();
614                 }
615         }
616 }
617
618 void Mixer::bm_hotplug_add(libusb_device *dev)
619 {
620         lock_guard<mutex> lock(hotplug_mutex);
621         hotplugged_cards.push_back(dev);
622 }
623
624 void Mixer::bm_hotplug_remove(unsigned card_index)
625 {
626         cards[card_index].new_frames_changed.notify_all();
627 }
628
629 void Mixer::thread_func()
630 {
631         eglBindAPI(EGL_OPENGL_API);
632         QOpenGLContext *context = create_context(mixer_surface);
633         if (!make_current(context, mixer_surface)) {
634                 printf("oops\n");
635                 exit(1);
636         }
637
638         steady_clock::time_point start, now;
639         start = steady_clock::now();
640
641         int frame = 0;
642         int stats_dropped_frames = 0;
643
644         while (!should_quit) {
645                 CaptureCard::NewFrame new_frames[MAX_CARDS];
646                 bool has_new_frame[MAX_CARDS] = { false };
647                 int num_samples[MAX_CARDS] = { 0 };
648
649                 unsigned master_card_index = theme->map_signal(master_clock_channel);
650                 assert(master_card_index < num_cards);
651
652                 get_one_frame_from_each_card(master_card_index, new_frames, has_new_frame, num_samples);
653                 schedule_audio_resampling_tasks(new_frames[master_card_index].dropped_frames, num_samples[master_card_index], new_frames[master_card_index].length);
654                 stats_dropped_frames += new_frames[master_card_index].dropped_frames;
655                 send_audio_level_callback();
656
657                 handle_hotplugged_cards();
658
659                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
660                         if (card_index == master_card_index || !has_new_frame[card_index]) {
661                                 continue;
662                         }
663                         if (new_frames[card_index].frame->len == 0) {
664                                 ++new_frames[card_index].dropped_frames;
665                         }
666                         if (new_frames[card_index].dropped_frames > 0) {
667                                 printf("Card %u dropped %d frames before this\n",
668                                         card_index, int(new_frames[card_index].dropped_frames));
669                         }
670                 }
671
672                 // If the first card is reporting a corrupted or otherwise dropped frame,
673                 // just increase the pts (skipping over this frame) and don't try to compute anything new.
674                 if (new_frames[master_card_index].frame->len == 0) {
675                         ++stats_dropped_frames;
676                         pts_int += new_frames[master_card_index].length;
677                         continue;
678                 }
679
680                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
681                         if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
682                                 continue;
683
684                         CaptureCard::NewFrame *new_frame = &new_frames[card_index];
685                         assert(new_frame->frame != nullptr);
686                         insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
687                         check_error();
688
689                         // The new texture might need uploading before use.
690                         if (new_frame->upload_func) {
691                                 new_frame->upload_func();
692                                 new_frame->upload_func = nullptr;
693                         }
694                 }
695
696                 int64_t frame_duration = new_frames[master_card_index].length;
697                 render_one_frame(frame_duration);
698                 ++frame;
699                 pts_int += frame_duration;
700
701                 now = steady_clock::now();
702                 double elapsed = duration<double>(now - start).count();
703                 if (frame % 100 == 0) {
704                         printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
705                                 frame, stats_dropped_frames, elapsed, frame / elapsed,
706                                 1e3 * elapsed / frame);
707                 //      chain->print_phase_timing();
708
709                         // Check our memory usage, to see if we are close to our mlockall()
710                         // limit (if at all set).
711                         rusage used;
712                         if (getrusage(RUSAGE_SELF, &used) == -1) {
713                                 perror("getrusage(RUSAGE_SELF)");
714                                 assert(false);
715                         }
716
717                         if (uses_mlock) {
718                                 rlimit limit;
719                                 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
720                                         perror("getrlimit(RLIMIT_MEMLOCK)");
721                                         assert(false);
722                                 }
723
724                                 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
725                                         long(used.ru_maxrss / 1024),
726                                         long(limit.rlim_cur / 1048576),
727                                         float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
728                         } else {
729                                 printf(", using %ld MB memory (not locked)",
730                                         long(used.ru_maxrss / 1024));
731                         }
732
733                         printf("\n");
734                 }
735
736
737                 if (should_cut.exchange(false)) {  // Test and clear.
738                         video_encoder->do_cut(frame);
739                 }
740
741 #if 0
742                 // Reset every 100 frames, so that local variations in frame times
743                 // (especially for the first few frames, when the shaders are
744                 // compiled etc.) don't make it hard to measure for the entire
745                 // remaining duration of the program.
746                 if (frame == 10000) {
747                         frame = 0;
748                         start = now;
749                 }
750 #endif
751                 check_error();
752         }
753
754         resource_pool->clean_context();
755 }
756
757 void Mixer::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])
758 {
759 start:
760         // The first card is the master timer, so wait for it to have a new frame.
761         // TODO: Add a timeout.
762         unique_lock<mutex> lock(bmusb_mutex);
763         cards[master_card_index].new_frames_changed.wait(lock, [this, master_card_index]{ return !cards[master_card_index].new_frames.empty() || cards[master_card_index].capture->get_disconnected(); });
764
765         if (cards[master_card_index].new_frames.empty()) {
766                 // We were woken up, but not due to a new frame. Deal with it
767                 // and then restart.
768                 assert(cards[master_card_index].capture->get_disconnected());
769                 handle_hotplugged_cards();
770                 goto start;
771         }
772
773         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
774                 CaptureCard *card = &cards[card_index];
775                 if (card->new_frames.empty()) {
776                         assert(card_index != master_card_index);
777                         card->queue_length_policy.update_policy(-1);
778                         continue;
779                 }
780                 new_frames[card_index] = move(card->new_frames.front());
781                 has_new_frame[card_index] = true;
782                 card->new_frames.pop();
783                 card->new_frames_changed.notify_all();
784
785                 int num_samples_times_timebase = OUTPUT_FREQUENCY * new_frames[card_index].length + card->fractional_samples;
786                 num_samples[card_index] = num_samples_times_timebase / TIMEBASE;
787                 card->fractional_samples = num_samples_times_timebase % TIMEBASE;
788                 assert(num_samples[card_index] >= 0);
789
790                 if (card_index == master_card_index) {
791                         // We don't use the queue length policy for the master card,
792                         // but we will if it stops being the master. Thus, clear out
793                         // the policy in case we switch in the future.
794                         card->queue_length_policy.reset(card_index);
795                 } else {
796                         // If we have excess frames compared to the policy for this card,
797                         // drop frames from the head.
798                         card->queue_length_policy.update_policy(card->new_frames.size());
799                         while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
800                                 card->new_frames.pop();
801                         }
802                 }
803         }
804 }
805
806 void Mixer::handle_hotplugged_cards()
807 {
808         // Check for cards that have been disconnected since last frame.
809         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
810                 CaptureCard *card = &cards[card_index];
811                 if (card->capture->get_disconnected()) {
812                         fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
813                         FakeCapture *capture = new FakeCapture(WIDTH, HEIGHT, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
814                         configure_card(card_index, capture, /*is_fake_capture=*/true);
815                         card->queue_length_policy.reset(card_index);
816                         card->capture->start_bm_capture();
817                 }
818         }
819
820         // Check for cards that have been connected since last frame.
821         vector<libusb_device *> hotplugged_cards_copy;
822         {
823                 lock_guard<mutex> lock(hotplug_mutex);
824                 swap(hotplugged_cards, hotplugged_cards_copy);
825         }
826         for (libusb_device *new_dev : hotplugged_cards_copy) {
827                 // Look for a fake capture card where we can stick this in.
828                 int free_card_index = -1;
829                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
830                         if (cards[card_index].is_fake_capture) {
831                                 free_card_index = int(card_index);
832                                 break;
833                         }
834                 }
835
836                 if (free_card_index == -1) {
837                         fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
838                         libusb_unref_device(new_dev);
839                 } else {
840                         // BMUSBCapture takes ownership.
841                         fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
842                         CaptureCard *card = &cards[free_card_index];
843                         BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
844                         configure_card(free_card_index, capture, /*is_fake_capture=*/false);
845                         card->queue_length_policy.reset(free_card_index);
846                         capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
847                         capture->start_bm_capture();
848                 }
849         }
850 }
851
852
853 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame)
854 {
855         // Resample the audio as needed, including from previously dropped frames.
856         assert(num_cards > 0);
857         for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
858                 const bool dropped_frame = (frame_num != dropped_frames);
859                 {
860                         // Signal to the audio thread to process this frame.
861                         // Note that if the frame is a dropped frame, we signal that
862                         // we don't want to use this frame as base for adjusting
863                         // the resampler rate. The reason for this is that the timing
864                         // of these frames is often way too late; they typically don't
865                         // “arrive” before we synthesize them. Thus, we could end up
866                         // in a situation where we have inserted e.g. five audio frames
867                         // into the queue before we then start pulling five of them
868                         // back out. This makes ResamplingQueue overestimate the delay,
869                         // causing undue resampler changes. (We _do_ use the last,
870                         // non-dropped frame; perhaps we should just discard that as well,
871                         // since dropped frames are expected to be rare, and it might be
872                         // better to just wait until we have a slightly more normal situation).
873                         unique_lock<mutex> lock(audio_mutex);
874                         bool adjust_rate = !dropped_frame;
875                         audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate});
876                         audio_task_queue_changed.notify_one();
877                 }
878                 if (dropped_frame) {
879                         // For dropped frames, increase the pts. Note that if the format changed
880                         // in the meantime, we have no way of detecting that; we just have to
881                         // assume the frame length is always the same.
882                         pts_int += length_per_frame;
883                 }
884         }
885 }
886
887 void Mixer::render_one_frame(int64_t duration)
888 {
889         // Get the main chain from the theme, and set its state immediately.
890         Theme::Chain theme_main_chain = theme->get_chain(0, pts(), WIDTH, HEIGHT, input_state);
891         EffectChain *chain = theme_main_chain.chain;
892         theme_main_chain.setup_chain();
893         //theme_main_chain.chain->enable_phase_timing(true);
894
895         GLuint y_tex, cbcr_tex;
896         bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
897         assert(got_frame);
898
899         // Render main chain.
900         GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, WIDTH, HEIGHT);
901         GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, WIDTH, HEIGHT);  // Saves texture bandwidth, although dithering gets messed up.
902         GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
903         check_error();
904         chain->render_to_fbo(fbo, WIDTH, HEIGHT);
905         resource_pool->release_fbo(fbo);
906
907         subsample_chroma(cbcr_full_tex, cbcr_tex);
908         resource_pool->release_2d_texture(cbcr_full_tex);
909
910         // Set the right state for rgba_tex.
911         glBindFramebuffer(GL_FRAMEBUFFER, 0);
912         glBindTexture(GL_TEXTURE_2D, rgba_tex);
913         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
914         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
915         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
916
917         const int64_t av_delay = TIMEBASE / 10;  // Corresponds to the fixed delay in resampling_queue.h. TODO: Make less hard-coded.
918         RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
919
920         // The live frame just shows the RGBA texture we just rendered.
921         // It owns rgba_tex now.
922         DisplayFrame live_frame;
923         live_frame.chain = display_chain.get();
924         live_frame.setup_chain = [this, rgba_tex]{
925                 display_input->set_texture_num(rgba_tex);
926         };
927         live_frame.ready_fence = fence;
928         live_frame.input_frames = {};
929         live_frame.temp_textures = { rgba_tex };
930         output_channel[OUTPUT_LIVE].output_frame(live_frame);
931
932         // Set up preview and any additional channels.
933         for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
934                 DisplayFrame display_frame;
935                 Theme::Chain chain = theme->get_chain(i, pts(), WIDTH, HEIGHT, input_state);  // FIXME: dimensions
936                 display_frame.chain = chain.chain;
937                 display_frame.setup_chain = chain.setup_chain;
938                 display_frame.ready_fence = fence;
939                 display_frame.input_frames = chain.input_frames;
940                 display_frame.temp_textures = {};
941                 output_channel[i].output_frame(display_frame);
942         }
943 }
944
945 void Mixer::send_audio_level_callback()
946 {
947         if (audio_level_callback == nullptr) {
948                 return;
949         }
950
951         unique_lock<mutex> lock(compressor_mutex);
952         double loudness_s = r128.loudness_S();
953         double loudness_i = r128.integrated();
954         double loudness_range_low = r128.range_min();
955         double loudness_range_high = r128.range_max();
956
957         audio_level_callback(loudness_s, 20.0 * log10(peak),
958                 loudness_i, loudness_range_low, loudness_range_high,
959                 gain_staging_db, 20.0 * log10(final_makeup_gain),
960                 correlation.get_correlation());
961 }
962
963 void Mixer::audio_thread_func()
964 {
965         while (!should_quit) {
966                 AudioTask task;
967
968                 {
969                         unique_lock<mutex> lock(audio_mutex);
970                         audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
971                         if (should_quit) {
972                                 return;
973                         }
974                         task = audio_task_queue.front();
975                         audio_task_queue.pop();
976                 }
977
978                 process_audio_one_frame(task.pts_int, task.num_samples, task.adjust_rate);
979         }
980 }
981
982 void Mixer::process_audio_one_frame(int64_t frame_pts_int, int num_samples, bool adjust_rate)
983 {
984         vector<float> samples_card;
985         vector<float> samples_out;
986
987         // TODO: Allow mixing audio from several sources.
988         unsigned selected_audio_card = theme->map_signal(audio_source_channel);
989         assert(selected_audio_card < num_cards);
990
991         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
992                 samples_card.resize(num_samples * 2);
993                 {
994                         unique_lock<mutex> lock(cards[card_index].audio_mutex);
995                         ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
996                                 adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
997                         cards[card_index].resampling_queue->get_output_samples(
998                                 double(frame_pts_int) / TIMEBASE,
999                                 &samples_card[0],
1000                                 num_samples,
1001                                 rate_adjustment_policy);
1002                 }
1003                 if (card_index == selected_audio_card) {
1004                         samples_out = move(samples_card);
1005                 }
1006         }
1007
1008         // Cut away everything under 120 Hz (or whatever the cutoff is);
1009         // we don't need it for voice, and it will reduce headroom
1010         // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
1011         // should be dampened.)
1012         if (locut_enabled) {
1013                 locut.render(samples_out.data(), samples_out.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
1014         }
1015
1016         // Apply a level compressor to get the general level right.
1017         // Basically, if it's over about -40 dBFS, we squeeze it down to that level
1018         // (or more precisely, near it, since we don't use infinite ratio),
1019         // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
1020         // entirely arbitrary, but from practical tests with speech, it seems to
1021         // put ut around -23 LUFS, so it's a reasonable starting point for later use.
1022         {
1023                 unique_lock<mutex> lock(compressor_mutex);
1024                 if (level_compressor_enabled) {
1025                         float threshold = 0.01f;   // -40 dBFS.
1026                         float ratio = 20.0f;
1027                         float attack_time = 0.5f;
1028                         float release_time = 20.0f;
1029                         float makeup_gain = pow(10.0f, (ref_level_dbfs - (-40.0f)) / 20.0f);  // +26 dB.
1030                         level_compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
1031                         gain_staging_db = 20.0 * log10(level_compressor.get_attenuation() * makeup_gain);
1032                 } else {
1033                         // Just apply the gain we already had.
1034                         float g = pow(10.0f, gain_staging_db / 20.0f);
1035                         for (size_t i = 0; i < samples_out.size(); ++i) {
1036                                 samples_out[i] *= g;
1037                         }
1038                 }
1039         }
1040
1041 #if 0
1042         printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
1043                 level_compressor.get_level(), 20.0 * log10(level_compressor.get_level()),
1044                 level_compressor.get_attenuation(), 20.0 * log10(level_compressor.get_attenuation()),
1045                 20.0 * log10(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
1046 #endif
1047
1048 //      float limiter_att, compressor_att;
1049
1050         // The real compressor.
1051         if (compressor_enabled) {
1052                 float threshold = pow(10.0f, compressor_threshold_dbfs / 20.0f);
1053                 float ratio = 20.0f;
1054                 float attack_time = 0.005f;
1055                 float release_time = 0.040f;
1056                 float makeup_gain = 2.0f;  // +6 dB.
1057                 compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
1058 //              compressor_att = compressor.get_attenuation();
1059         }
1060
1061         // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
1062         // Note that since ratio is not infinite, we could go slightly higher than this.
1063         if (limiter_enabled) {
1064                 float threshold = pow(10.0f, limiter_threshold_dbfs / 20.0f);
1065                 float ratio = 30.0f;
1066                 float attack_time = 0.0f;  // Instant.
1067                 float release_time = 0.020f;
1068                 float makeup_gain = 1.0f;  // 0 dB.
1069                 limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
1070 //              limiter_att = limiter.get_attenuation();
1071         }
1072
1073 //      printf("limiter=%+5.1f  compressor=%+5.1f\n", 20.0*log10(limiter_att), 20.0*log10(compressor_att));
1074
1075         // At this point, we are most likely close to +0 LU, but all of our
1076         // measurements have been on raw sample values, not R128 values.
1077         // So we have a final makeup gain to get us to +0 LU; the gain
1078         // adjustments required should be relatively small, and also, the
1079         // offset shouldn't change much (only if the type of audio changes
1080         // significantly). Thus, we shoot for updating this value basically
1081         // “whenever we process buffers”, since the R128 calculation isn't exactly
1082         // something we get out per-sample.
1083         //
1084         // Note that there's a feedback loop here, so we choose a very slow filter
1085         // (half-time of 100 seconds).
1086         double target_loudness_factor, alpha;
1087         {
1088                 unique_lock<mutex> lock(compressor_mutex);
1089                 double loudness_lu = r128.loudness_M() - ref_level_lufs;
1090                 double current_makeup_lu = 20.0f * log10(final_makeup_gain);
1091                 target_loudness_factor = pow(10.0f, -loudness_lu / 20.0f);
1092
1093                 // If we're outside +/- 5 LU uncorrected, we don't count it as
1094                 // a normal signal (probably silence) and don't change the
1095                 // correction factor; just apply what we already have.
1096                 if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
1097                         alpha = 0.0;
1098                 } else {
1099                         // Formula adapted from
1100                         // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
1101                         const double half_time_s = 100.0;
1102                         const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
1103                         alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
1104                 }
1105
1106                 double m = final_makeup_gain;
1107                 for (size_t i = 0; i < samples_out.size(); i += 2) {
1108                         samples_out[i + 0] *= m;
1109                         samples_out[i + 1] *= m;
1110                         m += (target_loudness_factor - m) * alpha;
1111                 }
1112                 final_makeup_gain = m;
1113         }
1114
1115         // Upsample 4x to find interpolated peak.
1116         peak_resampler.inp_data = samples_out.data();
1117         peak_resampler.inp_count = samples_out.size() / 2;
1118
1119         vector<float> interpolated_samples_out;
1120         interpolated_samples_out.resize(samples_out.size());
1121         while (peak_resampler.inp_count > 0) {  // About four iterations.
1122                 peak_resampler.out_data = &interpolated_samples_out[0];
1123                 peak_resampler.out_count = interpolated_samples_out.size() / 2;
1124                 peak_resampler.process();
1125                 size_t out_stereo_samples = interpolated_samples_out.size() / 2 - peak_resampler.out_count;
1126                 peak = max<float>(peak, find_peak(interpolated_samples_out.data(), out_stereo_samples * 2));
1127                 peak_resampler.out_data = nullptr;
1128         }
1129
1130         // Find R128 levels and L/R correlation.
1131         vector<float> left, right;
1132         deinterleave_samples(samples_out, &left, &right);
1133         float *ptrs[] = { left.data(), right.data() };
1134         {
1135                 unique_lock<mutex> lock(compressor_mutex);
1136                 r128.process(left.size(), ptrs);
1137                 correlation.process_samples(samples_out);
1138         }
1139
1140         // Send the samples to the sound card.
1141         if (alsa) {
1142                 alsa->write(samples_out);
1143         }
1144
1145         // And finally add them to the output.
1146         video_encoder->add_audio(frame_pts_int, move(samples_out));
1147 }
1148
1149 void Mixer::subsample_chroma(GLuint src_tex, GLuint dst_tex)
1150 {
1151         GLuint vao;
1152         glGenVertexArrays(1, &vao);
1153         check_error();
1154
1155         glBindVertexArray(vao);
1156         check_error();
1157
1158         // Extract Cb/Cr.
1159         GLuint fbo = resource_pool->create_fbo(dst_tex);
1160         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1161         glViewport(0, 0, WIDTH/2, HEIGHT/2);
1162         check_error();
1163
1164         glUseProgram(cbcr_program_num);
1165         check_error();
1166
1167         glActiveTexture(GL_TEXTURE0);
1168         check_error();
1169         glBindTexture(GL_TEXTURE_2D, src_tex);
1170         check_error();
1171         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1172         check_error();
1173         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1174         check_error();
1175         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1176         check_error();
1177
1178         float chroma_offset_0[] = { -0.5f / WIDTH, 0.0f };
1179         set_uniform_vec2(cbcr_program_num, "foo", "chroma_offset_0", chroma_offset_0);
1180
1181         glBindBuffer(GL_ARRAY_BUFFER, cbcr_vbo);
1182         check_error();
1183
1184         for (GLint attr_index : { cbcr_position_attribute_index, cbcr_texcoord_attribute_index }) {
1185                 glEnableVertexAttribArray(attr_index);
1186                 check_error();
1187                 glVertexAttribPointer(attr_index, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1188                 check_error();
1189         }
1190
1191         glDrawArrays(GL_TRIANGLES, 0, 3);
1192         check_error();
1193
1194         for (GLint attr_index : { cbcr_position_attribute_index, cbcr_texcoord_attribute_index }) {
1195                 glDisableVertexAttribArray(attr_index);
1196                 check_error();
1197         }
1198
1199         glUseProgram(0);
1200         check_error();
1201         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1202         check_error();
1203
1204         resource_pool->release_fbo(fbo);
1205         glDeleteVertexArrays(1, &vao);
1206 }
1207
1208 void Mixer::release_display_frame(DisplayFrame *frame)
1209 {
1210         for (GLuint texnum : frame->temp_textures) {
1211                 resource_pool->release_2d_texture(texnum);
1212         }
1213         frame->temp_textures.clear();
1214         frame->ready_fence.reset();
1215         frame->input_frames.clear();
1216 }
1217
1218 void Mixer::start()
1219 {
1220         mixer_thread = thread(&Mixer::thread_func, this);
1221         audio_thread = thread(&Mixer::audio_thread_func, this);
1222 }
1223
1224 void Mixer::quit()
1225 {
1226         should_quit = true;
1227         audio_task_queue_changed.notify_one();
1228         mixer_thread.join();
1229         audio_thread.join();
1230 }
1231
1232 void Mixer::transition_clicked(int transition_num)
1233 {
1234         theme->transition_clicked(transition_num, pts());
1235 }
1236
1237 void Mixer::channel_clicked(int preview_num)
1238 {
1239         theme->channel_clicked(preview_num);
1240 }
1241
1242 void Mixer::reset_meters()
1243 {
1244         peak_resampler.reset();
1245         peak = 0.0f;
1246         r128.reset();
1247         r128.integr_start();
1248         correlation.reset();
1249 }
1250
1251 void Mixer::start_mode_scanning(unsigned card_index)
1252 {
1253         assert(card_index < num_cards);
1254         if (is_mode_scanning[card_index]) {
1255                 return;
1256         }
1257         is_mode_scanning[card_index] = true;
1258         mode_scanlist[card_index].clear();
1259         for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1260                 mode_scanlist[card_index].push_back(mode.first);
1261         }
1262         assert(!mode_scanlist[card_index].empty());
1263         mode_scanlist_index[card_index] = 0;
1264         cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1265         last_mode_scan_change[card_index] = steady_clock::now();
1266 }
1267
1268 Mixer::OutputChannel::~OutputChannel()
1269 {
1270         if (has_current_frame) {
1271                 parent->release_display_frame(&current_frame);
1272         }
1273         if (has_ready_frame) {
1274                 parent->release_display_frame(&ready_frame);
1275         }
1276 }
1277
1278 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1279 {
1280         // Store this frame for display. Remove the ready frame if any
1281         // (it was seemingly never used).
1282         {
1283                 unique_lock<mutex> lock(frame_mutex);
1284                 if (has_ready_frame) {
1285                         parent->release_display_frame(&ready_frame);
1286                 }
1287                 ready_frame = frame;
1288                 has_ready_frame = true;
1289         }
1290
1291         if (new_frame_ready_callback) {
1292                 new_frame_ready_callback();
1293         }
1294
1295         // Reduce the number of callbacks by filtering duplicates. The reason
1296         // why we bother doing this is that Qt seemingly can get into a state
1297         // where its builds up an essentially unbounded queue of signals,
1298         // consuming more and more memory, and there's no good way of collapsing
1299         // user-defined signals or limiting the length of the queue.
1300         if (transition_names_updated_callback) {
1301                 vector<string> transition_names = global_mixer->get_transition_names();
1302                 bool changed = false;
1303                 if (transition_names.size() != last_transition_names.size()) {
1304                         changed = true;
1305                 } else {
1306                         for (unsigned i = 0; i < transition_names.size(); ++i) {
1307                                 if (transition_names[i] != last_transition_names[i]) {
1308                                         changed = true;
1309                                         break;
1310                                 }
1311                         }
1312                 }
1313                 if (changed) {
1314                         transition_names_updated_callback(transition_names);
1315                         last_transition_names = transition_names;
1316                 }
1317         }
1318         if (name_updated_callback) {
1319                 string name = global_mixer->get_channel_name(channel);
1320                 if (name != last_name) {
1321                         name_updated_callback(name);
1322                         last_name = name;
1323                 }
1324         }
1325         if (color_updated_callback) {
1326                 string color = global_mixer->get_channel_color(channel);
1327                 if (color != last_color) {
1328                         color_updated_callback(color);
1329                         last_color = color;
1330                 }
1331         }
1332 }
1333
1334 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1335 {
1336         unique_lock<mutex> lock(frame_mutex);
1337         if (!has_current_frame && !has_ready_frame) {
1338                 return false;
1339         }
1340
1341         if (has_current_frame && has_ready_frame) {
1342                 // We have a new ready frame. Toss the current one.
1343                 parent->release_display_frame(&current_frame);
1344                 has_current_frame = false;
1345         }
1346         if (has_ready_frame) {
1347                 assert(!has_current_frame);
1348                 current_frame = ready_frame;
1349                 ready_frame.ready_fence.reset();  // Drop the refcount.
1350                 ready_frame.input_frames.clear();  // Drop the refcounts.
1351                 has_current_frame = true;
1352                 has_ready_frame = false;
1353         }
1354
1355         *frame = current_frame;
1356         return true;
1357 }
1358
1359 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1360 {
1361         new_frame_ready_callback = callback;
1362 }
1363
1364 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1365 {
1366         transition_names_updated_callback = callback;
1367 }
1368
1369 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1370 {
1371         name_updated_callback = callback;
1372 }
1373
1374 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1375 {
1376         color_updated_callback = callback;
1377 }
1378
1379 mutex RefCountedGLsync::fence_lock;