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