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