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