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