]> git.sesse.net Git - nageru/blob - mixer.cpp
16a07540d442097deab64bcc60a094d47a31e5ce
[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
30 #include "bmusb/bmusb.h"
31 #include "context.h"
32 #include "defs.h"
33 #include "h264encode.h"
34 #include "pbo_frame_allocator.h"
35 #include "ref_counted_gl_sync.h"
36 #include "timebase.h"
37
38 class QOpenGLContext;
39
40 using namespace movit;
41 using namespace std;
42 using namespace std::placeholders;
43
44 Mixer *global_mixer = nullptr;
45
46 namespace {
47
48 void convert_fixed24_to_fp32(float *dst, size_t out_channels, const uint8_t *src, size_t in_channels, size_t num_samples)
49 {
50         for (size_t i = 0; i < num_samples; ++i) {
51                 for (size_t j = 0; j < out_channels; ++j) {
52                         uint32_t s1 = *src++;
53                         uint32_t s2 = *src++;
54                         uint32_t s3 = *src++;
55                         uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
56                         dst[i * out_channels + j] = int(s) * (1.0f / 4294967296.0f);
57                 }
58                 src += 3 * (in_channels - out_channels);
59         }
60 }
61
62 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
63 {
64         if (interlaced) {
65                 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) {  // :-)
66                         input_state->buffered_frames[card_index][frame_num] =
67                                 input_state->buffered_frames[card_index][frame_num - 1];
68                 }
69                 input_state->buffered_frames[card_index][0] = { frame, field_num };
70         } else {
71                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
72                         input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
73                 }
74         }
75 }
76
77 string generate_local_dump_filename(int frame)
78 {
79         time_t now = time(NULL);
80         tm now_tm;
81         localtime_r(&now, &now_tm);
82
83         char timestamp[256];
84         strftime(timestamp, sizeof(timestamp), "%F-%T%z", &now_tm);
85
86         // Use the frame number to disambiguate between two cuts starting
87         // on the same second.
88         char filename[256];
89         snprintf(filename, sizeof(filename), "%s%s-f%02d%s",
90                 LOCAL_DUMP_PREFIX, timestamp, frame % 100, LOCAL_DUMP_SUFFIX);
91         return filename;
92 }
93
94 }  // namespace
95
96 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
97         : httpd(WIDTH, HEIGHT),
98           num_cards(num_cards),
99           mixer_surface(create_surface(format)),
100           h264_encoder_surface(create_surface(format)),
101           correlation(OUTPUT_FREQUENCY),
102           level_compressor(OUTPUT_FREQUENCY),
103           limiter(OUTPUT_FREQUENCY),
104           compressor(OUTPUT_FREQUENCY)
105 {
106         httpd.open_output_file(generate_local_dump_filename(/*frame=*/0).c_str());
107         httpd.start(9095);
108
109         CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
110         check_error();
111
112         // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
113         // will be halved when sampling them, and we need to compensate here.
114         movit_texel_subpixel_precision /= 2.0;
115
116         resource_pool.reset(new ResourcePool);
117         theme.reset(new Theme("theme.lua", resource_pool.get(), num_cards));
118         for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
119                 output_channel[i].parent = this;
120         }
121
122         ImageFormat inout_format;
123         inout_format.color_space = COLORSPACE_sRGB;
124         inout_format.gamma_curve = GAMMA_sRGB;
125
126         // Display chain; shows the live output produced by the main chain (its RGBA version).
127         display_chain.reset(new EffectChain(WIDTH, HEIGHT, resource_pool.get()));
128         check_error();
129         display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, WIDTH, HEIGHT);  // FIXME: GL_UNSIGNED_BYTE is really wrong.
130         display_chain->add_input(display_input);
131         display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
132         display_chain->set_dither_bits(0);  // Don't bother.
133         display_chain->finalize();
134
135         h264_encoder.reset(new H264Encoder(h264_encoder_surface, WIDTH, HEIGHT, &httpd));
136
137         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
138                 printf("Configuring card %d...\n", card_index);
139                 CaptureCard *card = &cards[card_index];
140                 card->usb = new BMUSBCapture(card_index);
141                 card->usb->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
142                 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, WIDTH, HEIGHT));  // 8 MB.
143                 card->usb->set_video_frame_allocator(card->frame_allocator.get());
144                 card->surface = create_surface(format);
145                 card->usb->set_dequeue_thread_callbacks(
146                         [card]{
147                                 eglBindAPI(EGL_OPENGL_API);
148                                 card->context = create_context(card->surface);
149                                 if (!make_current(card->context, card->surface)) {
150                                         printf("failed to create bmusb context\n");
151                                         exit(1);
152                                 }
153                         },
154                         [this]{
155                                 resource_pool->clean_context();
156                         });
157                 card->resampling_queue.reset(new ResamplingQueue(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY, 2));
158                 card->usb->configure_card();
159         }
160
161         BMUSBCapture::start_bm_thread();
162
163         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
164                 cards[card_index].usb->start_bm_capture();
165         }
166
167         // Set up stuff for NV12 conversion.
168
169         // Cb/Cr shader.
170         string cbcr_vert_shader =
171                 "#version 130 \n"
172                 " \n"
173                 "in vec2 position; \n"
174                 "in vec2 texcoord; \n"
175                 "out vec2 tc0; \n"
176                 "uniform vec2 foo_chroma_offset_0; \n"
177                 " \n"
178                 "void main() \n"
179                 "{ \n"
180                 "    // The result of glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0) is: \n"
181                 "    // \n"
182                 "    //   2.000  0.000  0.000 -1.000 \n"
183                 "    //   0.000  2.000  0.000 -1.000 \n"
184                 "    //   0.000  0.000 -2.000 -1.000 \n"
185                 "    //   0.000  0.000  0.000  1.000 \n"
186                 "    gl_Position = vec4(2.0 * position.x - 1.0, 2.0 * position.y - 1.0, -1.0, 1.0); \n"
187                 "    vec2 flipped_tc = texcoord; \n"
188                 "    tc0 = flipped_tc + foo_chroma_offset_0; \n"
189                 "} \n";
190         string cbcr_frag_shader =
191                 "#version 130 \n"
192                 "in vec2 tc0; \n"
193                 "uniform sampler2D cbcr_tex; \n"
194                 "out vec4 FragColor; \n"
195                 "void main() { \n"
196                 "    FragColor = texture(cbcr_tex, tc0); \n"
197                 "} \n";
198         vector<string> frag_shader_outputs;
199         cbcr_program_num = resource_pool->compile_glsl_program(cbcr_vert_shader, cbcr_frag_shader, frag_shader_outputs);
200
201         r128.init(2, OUTPUT_FREQUENCY);
202         r128.integr_start();
203
204         locut.init(FILTER_HPF, 2);
205
206         // hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise,
207         // and there's a limit to how important the peak meter is.
208         peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0);
209
210         alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
211 }
212
213 Mixer::~Mixer()
214 {
215         resource_pool->release_glsl_program(cbcr_program_num);
216         BMUSBCapture::stop_bm_thread();
217
218         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
219                 {
220                         unique_lock<mutex> lock(bmusb_mutex);
221                         cards[card_index].should_quit = true;  // Unblock thread.
222                         cards[card_index].new_data_ready_changed.notify_all();
223                 }
224                 cards[card_index].usb->stop_dequeue_thread();
225         }
226
227         h264_encoder.reset(nullptr);
228 }
229
230 namespace {
231
232 int unwrap_timecode(uint16_t current_wrapped, int last)
233 {
234         uint16_t last_wrapped = last & 0xffff;
235         if (current_wrapped > last_wrapped) {
236                 return (last & ~0xffff) | current_wrapped;
237         } else {
238                 return 0x10000 + ((last & ~0xffff) | current_wrapped);
239         }
240 }
241
242 float find_peak(const float *samples, size_t num_samples)
243 {
244         float m = fabs(samples[0]);
245         for (size_t i = 1; i < num_samples; ++i) {
246                 m = max(m, fabs(samples[i]));
247         }
248         return m;
249 }
250
251 void deinterleave_samples(const vector<float> &in, vector<float> *out_l, vector<float> *out_r)
252 {
253         size_t num_samples = in.size() / 2;
254         out_l->resize(num_samples);
255         out_r->resize(num_samples);
256
257         const float *inptr = in.data();
258         float *lptr = &(*out_l)[0];
259         float *rptr = &(*out_r)[0];
260         for (size_t i = 0; i < num_samples; ++i) {
261                 *lptr++ = *inptr++;
262                 *rptr++ = *inptr++;
263         }
264 }
265
266 }  // namespace
267
268 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
269                      FrameAllocator::Frame video_frame, size_t video_offset, uint16_t video_format,
270                      FrameAllocator::Frame audio_frame, size_t audio_offset, uint16_t audio_format)
271 {
272         CaptureCard *card = &cards[card_index];
273
274         unsigned width, height, second_field_start, frame_rate_nom, frame_rate_den, extra_lines_top, extra_lines_bottom;
275         bool interlaced;
276
277         decode_video_format(video_format, &width, &height, &second_field_start, &extra_lines_top, &extra_lines_bottom,
278                             &frame_rate_nom, &frame_rate_den, &interlaced);  // Ignore return value for now.
279         int64_t frame_length = int64_t(TIMEBASE * frame_rate_den) / frame_rate_nom;
280
281         size_t num_samples = (audio_frame.len >= audio_offset) ? (audio_frame.len - audio_offset) / 8 / 3 : 0;
282         if (num_samples > OUTPUT_FREQUENCY / 10) {
283                 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",
284                         card_index, int(audio_frame.len), int(audio_offset),
285                         timecode, int(video_frame.len), int(video_offset), video_format);
286                 if (video_frame.owner) {
287                         video_frame.owner->release_frame(video_frame);
288                 }
289                 if (audio_frame.owner) {
290                         audio_frame.owner->release_frame(audio_frame);
291                 }
292                 return;
293         }
294
295         int64_t local_pts = card->next_local_pts;
296         int dropped_frames = 0;
297         if (card->last_timecode != -1) {
298                 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
299         }
300
301         // Convert the audio to stereo fp32 and add it.
302         vector<float> audio;
303         audio.resize(num_samples * 2);
304         convert_fixed24_to_fp32(&audio[0], 2, audio_frame.data + audio_offset, 8, num_samples);
305
306         // Add the audio.
307         {
308                 unique_lock<mutex> lock(card->audio_mutex);
309
310                 // Number of samples per frame if we need to insert silence.
311                 // (Could be nonintegral, but resampling will save us then.)
312                 int silence_samples = OUTPUT_FREQUENCY * frame_rate_den / frame_rate_nom;
313
314                 if (dropped_frames > MAX_FPS * 2) {
315                         fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
316                                 card_index, card->last_timecode, timecode);
317                         card->resampling_queue.reset(new ResamplingQueue(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY, 2));
318                         dropped_frames = 0;
319                 } else if (dropped_frames > 0) {
320                         // Insert silence as needed.
321                         fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
322                                 card_index, dropped_frames, timecode);
323                         vector<float> silence(silence_samples * 2, 0.0f);
324                         for (int i = 0; i < dropped_frames; ++i) {
325                                 card->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), silence.data(), silence_samples);
326                                 // Note that if the format changed in the meantime, we have
327                                 // no way of detecting that; we just have to assume the frame length
328                                 // is always the same.
329                                 local_pts += frame_length;
330                         }
331                 }
332                 if (num_samples == 0) {
333                         audio.resize(silence_samples * 2);
334                         num_samples = silence_samples;
335                 }
336                 card->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.data(), num_samples);
337                 card->next_local_pts = local_pts + frame_length;
338         }
339
340         card->last_timecode = timecode;
341
342         // Done with the audio, so release it.
343         if (audio_frame.owner) {
344                 audio_frame.owner->release_frame(audio_frame);
345         }
346
347         {
348                 // Wait until the previous frame was consumed.
349                 unique_lock<mutex> lock(bmusb_mutex);
350                 card->new_data_ready_changed.wait(lock, [card]{ return !card->new_data_ready || card->should_quit; });
351                 if (card->should_quit) return;
352         }
353
354         size_t expected_length = width * (height + extra_lines_top + extra_lines_bottom) * 2;
355         if (video_frame.len - video_offset == 0 ||
356             video_frame.len - video_offset != expected_length) {
357                 if (video_frame.len != 0) {
358                         printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
359                                 card_index, video_frame.len - video_offset, expected_length);
360                 }
361                 if (video_frame.owner) {
362                         video_frame.owner->release_frame(video_frame);
363                 }
364
365                 // Still send on the information that we _had_ a frame, even though it's corrupted,
366                 // so that pts can go up accordingly.
367                 {
368                         unique_lock<mutex> lock(bmusb_mutex);
369                         card->new_data_ready = true;
370                         card->new_frame = RefCountedFrame(FrameAllocator::Frame());
371                         card->new_frame_length = frame_length;
372                         card->new_frame_interlaced = false;
373                         card->new_data_ready_fence = nullptr;
374                         card->dropped_frames = dropped_frames;
375                         card->new_data_ready_changed.notify_all();
376                 }
377                 return;
378         }
379
380         PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
381
382         unsigned num_fields = interlaced ? 2 : 1;
383         timespec frame_upload_start;
384         if (interlaced) {
385                 // Send the two fields along as separate frames; the other side will need to add
386                 // a deinterlacer to actually get this right.
387                 assert(height % 2 == 0);
388                 height /= 2;
389                 assert(frame_length % 2 == 0);
390                 frame_length /= 2;
391                 num_fields = 2;
392                 clock_gettime(CLOCK_MONOTONIC, &frame_upload_start);
393         }
394         userdata->last_interlaced = interlaced;
395         userdata->last_frame_rate_nom = frame_rate_nom;
396         userdata->last_frame_rate_den = frame_rate_den;
397         RefCountedFrame new_frame(video_frame);
398
399         // Upload the textures.
400         size_t cbcr_width = width / 2;
401         size_t cbcr_offset = video_offset / 2;
402         size_t y_offset = video_frame.size / 2 + video_offset / 2;
403
404         for (unsigned field = 0; field < num_fields; ++field) {
405                 unsigned field_start_line = (field == 1) ? second_field_start : extra_lines_top + field * (height + 22);
406
407                 if (userdata->tex_y[field] == 0 ||
408                     userdata->tex_cbcr[field] == 0 ||
409                     width != userdata->last_width[field] ||
410                     height != userdata->last_height[field]) {
411                         // We changed resolution since last use of this texture, so we need to create
412                         // a new object. Note that this each card has its own PBOFrameAllocator,
413                         // we don't need to worry about these flip-flopping between resolutions.
414                         glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
415                         check_error();
416                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
417                         check_error();
418                         glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
419                         check_error();
420                         glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
421                         check_error();
422                         userdata->last_width[field] = width;
423                         userdata->last_height[field] = height;
424                 }
425
426                 GLuint pbo = userdata->pbo;
427                 check_error();
428                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
429                 check_error();
430                 glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
431                 check_error();
432
433                 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
434                 check_error();
435                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t)));
436                 check_error();
437                 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
438                 check_error();
439                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(y_offset + width * field_start_line));
440                 check_error();
441                 glBindTexture(GL_TEXTURE_2D, 0);
442                 check_error();
443                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
444                 check_error();
445                 GLsync fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
446                 check_error();
447                 assert(fence != nullptr);
448
449                 if (field == 1) {
450                         // Don't upload the second field as fast as we can; wait until
451                         // the field time has approximately passed. (Otherwise, we could
452                         // get timing jitter against the other sources, and possibly also
453                         // against the video display, although the latter is not as critical.)
454                         // This requires our system clock to be reasonably close to the
455                         // video clock, but that's not an unreasonable assumption.
456                         timespec second_field_start;
457                         second_field_start.tv_nsec = frame_upload_start.tv_nsec +
458                                 frame_length * 1000000000 / TIMEBASE;
459                         second_field_start.tv_sec = frame_upload_start.tv_sec +
460                                 second_field_start.tv_nsec / 1000000000;
461                         second_field_start.tv_nsec %= 1000000000;
462
463                         while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
464                                                &second_field_start, nullptr) == -1 &&
465                                errno == EINTR) ;
466                 }
467
468                 {
469                         unique_lock<mutex> lock(bmusb_mutex);
470                         card->new_data_ready = true;
471                         card->new_frame = new_frame;
472                         card->new_frame_length = frame_length;
473                         card->new_frame_field = field;
474                         card->new_frame_interlaced = interlaced;
475                         card->new_data_ready_fence = fence;
476                         card->dropped_frames = dropped_frames;
477                         card->new_data_ready_changed.notify_all();
478
479                         if (field != num_fields - 1) {
480                                 // Wait until the previous frame was consumed.
481                                 card->new_data_ready_changed.wait(lock, [card]{ return !card->new_data_ready || card->should_quit; });
482                                 if (card->should_quit) return;
483                         }
484                 }
485         }
486 }
487
488 void Mixer::thread_func()
489 {
490         eglBindAPI(EGL_OPENGL_API);
491         QOpenGLContext *context = create_context(mixer_surface);
492         if (!make_current(context, mixer_surface)) {
493                 printf("oops\n");
494                 exit(1);
495         }
496
497         struct timespec start, now;
498         clock_gettime(CLOCK_MONOTONIC, &start);
499
500         int frame = 0;
501         int stats_dropped_frames = 0;
502
503         while (!should_quit) {
504                 CaptureCard card_copy[MAX_CARDS];
505                 int num_samples[MAX_CARDS];
506
507                 {
508                         unique_lock<mutex> lock(bmusb_mutex);
509
510                         // The first card is the master timer, so wait for it to have a new frame.
511                         // TODO: Make configurable, and with a timeout.
512                         cards[0].new_data_ready_changed.wait(lock, [this]{ return cards[0].new_data_ready; });
513
514                         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
515                                 CaptureCard *card = &cards[card_index];
516                                 card_copy[card_index].usb = card->usb;
517                                 card_copy[card_index].new_data_ready = card->new_data_ready;
518                                 card_copy[card_index].new_frame = card->new_frame;
519                                 card_copy[card_index].new_frame_length = card->new_frame_length;
520                                 card_copy[card_index].new_frame_field = card->new_frame_field;
521                                 card_copy[card_index].new_frame_interlaced = card->new_frame_interlaced;
522                                 card_copy[card_index].new_data_ready_fence = card->new_data_ready_fence;
523                                 card_copy[card_index].dropped_frames = card->dropped_frames;
524                                 card->new_data_ready = false;
525                                 card->new_data_ready_changed.notify_all();
526
527                                 int num_samples_times_timebase = OUTPUT_FREQUENCY * card->new_frame_length + card->fractional_samples;
528                                 num_samples[card_index] = num_samples_times_timebase / TIMEBASE;
529                                 card->fractional_samples = num_samples_times_timebase % TIMEBASE;
530                                 assert(num_samples[card_index] >= 0);
531                         }
532                 }
533
534                 // Resample the audio as needed, including from previously dropped frames.
535                 assert(num_cards > 0);
536                 for (unsigned frame_num = 0; frame_num < card_copy[0].dropped_frames + 1; ++frame_num) {
537                         {
538                                 // Signal to the audio thread to process this frame.
539                                 unique_lock<mutex> lock(audio_mutex);
540                                 audio_task_queue.push(AudioTask{pts_int, num_samples[0]});
541                                 audio_task_queue_changed.notify_one();
542                         }
543                         if (frame_num != card_copy[0].dropped_frames) {
544                                 // For dropped frames, increase the pts. Note that if the format changed
545                                 // in the meantime, we have no way of detecting that; we just have to
546                                 // assume the frame length is always the same.
547                                 ++stats_dropped_frames;
548                                 pts_int += card_copy[0].new_frame_length;
549                         }
550                 }
551
552                 if (audio_level_callback != nullptr) {
553                         unique_lock<mutex> lock(compressor_mutex);
554                         double loudness_s = r128.loudness_S();
555                         double loudness_i = r128.integrated();
556                         double loudness_range_low = r128.range_min();
557                         double loudness_range_high = r128.range_max();
558
559                         audio_level_callback(loudness_s, 20.0 * log10(peak),
560                                              loudness_i, loudness_range_low, loudness_range_high,
561                                              gain_staging_db, 20.0 * log10(final_makeup_gain),
562                                              correlation.get_correlation());
563                 }
564
565                 for (unsigned card_index = 1; card_index < num_cards; ++card_index) {
566                         if (card_copy[card_index].new_data_ready && card_copy[card_index].new_frame->len == 0) {
567                                 ++card_copy[card_index].dropped_frames;
568                         }
569                         if (card_copy[card_index].dropped_frames > 0) {
570                                 printf("Card %u dropped %d frames before this\n",
571                                         card_index, int(card_copy[card_index].dropped_frames));
572                         }
573                 }
574
575                 // If the first card is reporting a corrupted or otherwise dropped frame,
576                 // just increase the pts (skipping over this frame) and don't try to compute anything new.
577                 if (card_copy[0].new_frame->len == 0) {
578                         ++stats_dropped_frames;
579                         pts_int += card_copy[0].new_frame_length;
580                         continue;
581                 }
582
583                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
584                         CaptureCard *card = &card_copy[card_index];
585                         if (!card->new_data_ready || card->new_frame->len == 0)
586                                 continue;
587
588                         assert(card->new_frame != nullptr);
589                         insert_new_frame(card->new_frame, card->new_frame_field, card->new_frame_interlaced, card_index, &input_state);
590                         check_error();
591
592                         // The new texture might still be uploaded,
593                         // tell the GPU to wait until it's there.
594                         if (card->new_data_ready_fence) {
595                                 glWaitSync(card->new_data_ready_fence, /*flags=*/0, GL_TIMEOUT_IGNORED);
596                                 check_error();
597                                 glDeleteSync(card->new_data_ready_fence);
598                                 check_error();
599                         }
600                 }
601
602                 // Get the main chain from the theme, and set its state immediately.
603                 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), WIDTH, HEIGHT, input_state);
604                 EffectChain *chain = theme_main_chain.chain;
605                 theme_main_chain.setup_chain();
606                 //theme_main_chain.chain->enable_phase_timing(true);
607
608                 GLuint y_tex, cbcr_tex;
609                 bool got_frame = h264_encoder->begin_frame(&y_tex, &cbcr_tex);
610                 assert(got_frame);
611
612                 // Render main chain.
613                 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, WIDTH, HEIGHT);
614                 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, WIDTH, HEIGHT);  // Saves texture bandwidth, although dithering gets messed up.
615                 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
616                 check_error();
617                 chain->render_to_fbo(fbo, WIDTH, HEIGHT);
618                 resource_pool->release_fbo(fbo);
619
620                 subsample_chroma(cbcr_full_tex, cbcr_tex);
621                 resource_pool->release_2d_texture(cbcr_full_tex);
622
623                 // Set the right state for rgba_tex.
624                 glBindFramebuffer(GL_FRAMEBUFFER, 0);
625                 glBindTexture(GL_TEXTURE_2D, rgba_tex);
626                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
627                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
628                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
629
630                 RefCountedGLsync fence(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
631                 check_error();
632
633                 const int64_t av_delay = TIMEBASE / 10;  // Corresponds to the fixed delay in resampling_queue.h. TODO: Make less hard-coded.
634                 h264_encoder->end_frame(fence, pts_int + av_delay, theme_main_chain.input_frames);
635                 ++frame;
636                 pts_int += card_copy[0].new_frame_length;
637
638                 // The live frame just shows the RGBA texture we just rendered.
639                 // It owns rgba_tex now.
640                 DisplayFrame live_frame;
641                 live_frame.chain = display_chain.get();
642                 live_frame.setup_chain = [this, rgba_tex]{
643                         display_input->set_texture_num(rgba_tex);
644                 };
645                 live_frame.ready_fence = fence;
646                 live_frame.input_frames = {};
647                 live_frame.temp_textures = { rgba_tex };
648                 output_channel[OUTPUT_LIVE].output_frame(live_frame);
649
650                 // Set up preview and any additional channels.
651                 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
652                         DisplayFrame display_frame;
653                         Theme::Chain chain = theme->get_chain(i, pts(), WIDTH, HEIGHT, input_state);  // FIXME: dimensions
654                         display_frame.chain = chain.chain;
655                         display_frame.setup_chain = chain.setup_chain;
656                         display_frame.ready_fence = fence;
657                         display_frame.input_frames = chain.input_frames;
658                         display_frame.temp_textures = {};
659                         output_channel[i].output_frame(display_frame);
660                 }
661
662                 clock_gettime(CLOCK_MONOTONIC, &now);
663                 double elapsed = now.tv_sec - start.tv_sec +
664                         1e-9 * (now.tv_nsec - start.tv_nsec);
665                 if (frame % 100 == 0) {
666                         printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)\n",
667                                 frame, stats_dropped_frames, elapsed, frame / elapsed,
668                                 1e3 * elapsed / frame);
669                 //      chain->print_phase_timing();
670                 }
671
672                 if (should_cut.exchange(false)) {  // Test and clear.
673                         string filename = generate_local_dump_filename(frame);
674                         printf("Starting new recording: %s\n", filename.c_str());
675                         h264_encoder->shutdown();
676                         httpd.close_output_file();
677                         httpd.open_output_file(filename.c_str());
678                         h264_encoder.reset(new H264Encoder(h264_encoder_surface, WIDTH, HEIGHT, &httpd));
679                 }
680
681 #if 0
682                 // Reset every 100 frames, so that local variations in frame times
683                 // (especially for the first few frames, when the shaders are
684                 // compiled etc.) don't make it hard to measure for the entire
685                 // remaining duration of the program.
686                 if (frame == 10000) {
687                         frame = 0;
688                         start = now;
689                 }
690 #endif
691                 check_error();
692         }
693
694         resource_pool->clean_context();
695 }
696
697 void Mixer::audio_thread_func()
698 {
699         while (!should_quit) {
700                 AudioTask task;
701
702                 {
703                         unique_lock<mutex> lock(audio_mutex);
704                         audio_task_queue_changed.wait(lock, [this]{ return !audio_task_queue.empty(); });
705                         task = audio_task_queue.front();
706                         audio_task_queue.pop();
707                 }
708
709                 process_audio_one_frame(task.pts_int, task.num_samples);
710         }
711 }
712
713 void Mixer::process_audio_one_frame(int64_t frame_pts_int, int num_samples)
714 {
715         vector<float> samples_card;
716         vector<float> samples_out;
717
718         // TODO: Allow mixing audio from several sources.
719         unsigned selected_audio_card = theme->map_signal(audio_source_channel);
720         assert(selected_audio_card < num_cards);
721
722         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
723                 samples_card.resize(num_samples * 2);
724                 {
725                         unique_lock<mutex> lock(cards[card_index].audio_mutex);
726                         if (!cards[card_index].resampling_queue->get_output_samples(double(frame_pts_int) / TIMEBASE, &samples_card[0], num_samples)) {
727                                 printf("Card %d reported previous underrun.\n", card_index);
728                         }
729                 }
730                 if (card_index == selected_audio_card) {
731                         samples_out = move(samples_card);
732                 }
733         }
734
735         // Cut away everything under 120 Hz (or whatever the cutoff is);
736         // we don't need it for voice, and it will reduce headroom
737         // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
738         // should be dampened.)
739         if (locut_enabled) {
740                 locut.render(samples_out.data(), samples_out.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
741         }
742
743         // Apply a level compressor to get the general level right.
744         // Basically, if it's over about -40 dBFS, we squeeze it down to that level
745         // (or more precisely, near it, since we don't use infinite ratio),
746         // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
747         // entirely arbitrary, but from practical tests with speech, it seems to
748         // put ut around -23 LUFS, so it's a reasonable starting point for later use.
749         {
750                 unique_lock<mutex> lock(compressor_mutex);
751                 if (level_compressor_enabled) {
752                         float threshold = 0.01f;   // -40 dBFS.
753                         float ratio = 20.0f;
754                         float attack_time = 0.5f;
755                         float release_time = 20.0f;
756                         float makeup_gain = pow(10.0f, (ref_level_dbfs - (-40.0f)) / 20.0f);  // +26 dB.
757                         level_compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
758                         gain_staging_db = 20.0 * log10(level_compressor.get_attenuation() * makeup_gain);
759                 } else {
760                         // Just apply the gain we already had.
761                         float g = pow(10.0f, gain_staging_db / 20.0f);
762                         for (size_t i = 0; i < samples_out.size(); ++i) {
763                                 samples_out[i] *= g;
764                         }
765                 }
766         }
767
768 #if 0
769         printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
770                 level_compressor.get_level(), 20.0 * log10(level_compressor.get_level()),
771                 level_compressor.get_attenuation(), 20.0 * log10(level_compressor.get_attenuation()),
772                 20.0 * log10(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
773 #endif
774
775 //      float limiter_att, compressor_att;
776
777         // The real compressor.
778         if (compressor_enabled) {
779                 float threshold = pow(10.0f, compressor_threshold_dbfs / 20.0f);
780                 float ratio = 20.0f;
781                 float attack_time = 0.005f;
782                 float release_time = 0.040f;
783                 float makeup_gain = 2.0f;  // +6 dB.
784                 compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
785 //              compressor_att = compressor.get_attenuation();
786         }
787
788         // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
789         // Note that since ratio is not infinite, we could go slightly higher than this.
790         if (limiter_enabled) {
791                 float threshold = pow(10.0f, limiter_threshold_dbfs / 20.0f);
792                 float ratio = 30.0f;
793                 float attack_time = 0.0f;  // Instant.
794                 float release_time = 0.020f;
795                 float makeup_gain = 1.0f;  // 0 dB.
796                 limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
797 //              limiter_att = limiter.get_attenuation();
798         }
799
800 //      printf("limiter=%+5.1f  compressor=%+5.1f\n", 20.0*log10(limiter_att), 20.0*log10(compressor_att));
801
802         // Upsample 4x to find interpolated peak.
803         peak_resampler.inp_data = samples_out.data();
804         peak_resampler.inp_count = samples_out.size() / 2;
805
806         vector<float> interpolated_samples_out;
807         interpolated_samples_out.resize(samples_out.size());
808         while (peak_resampler.inp_count > 0) {  // About four iterations.
809                 peak_resampler.out_data = &interpolated_samples_out[0];
810                 peak_resampler.out_count = interpolated_samples_out.size() / 2;
811                 peak_resampler.process();
812                 size_t out_stereo_samples = interpolated_samples_out.size() / 2 - peak_resampler.out_count;
813                 peak = max<float>(peak, find_peak(interpolated_samples_out.data(), out_stereo_samples * 2));
814                 peak_resampler.out_data = nullptr;
815         }
816
817         // At this point, we are most likely close to +0 LU, but all of our
818         // measurements have been on raw sample values, not R128 values.
819         // So we have a final makeup gain to get us to +0 LU; the gain
820         // adjustments required should be relatively small, and also, the
821         // offset shouldn't change much (only if the type of audio changes
822         // significantly). Thus, we shoot for updating this value basically
823         // “whenever we process buffers”, since the R128 calculation isn't exactly
824         // something we get out per-sample.
825         //
826         // Note that there's a feedback loop here, so we choose a very slow filter
827         // (half-time of 100 seconds).
828         double target_loudness_factor, alpha;
829         {
830                 unique_lock<mutex> lock(compressor_mutex);
831                 double loudness_lu = r128.loudness_M() - ref_level_lufs;
832                 double current_makeup_lu = 20.0f * log10(final_makeup_gain);
833                 target_loudness_factor = pow(10.0f, -loudness_lu / 20.0f);
834
835                 // If we're outside +/- 5 LU uncorrected, we don't count it as
836                 // a normal signal (probably silence) and don't change the
837                 // correction factor; just apply what we already have.
838                 if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
839                         alpha = 0.0;
840                 } else {
841                         // Formula adapted from
842                         // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
843                         const double half_time_s = 100.0;
844                         const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
845                         alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
846                 }
847
848                 double m = final_makeup_gain;
849                 for (size_t i = 0; i < samples_out.size(); i += 2) {
850                         samples_out[i + 0] *= m;
851                         samples_out[i + 1] *= m;
852                         m += (target_loudness_factor - m) * alpha;
853                 }
854                 final_makeup_gain = m;
855         }
856
857         // Find R128 levels and L/R correlation.
858         vector<float> left, right;
859         deinterleave_samples(samples_out, &left, &right);
860         float *ptrs[] = { left.data(), right.data() };
861         {
862                 unique_lock<mutex> lock(compressor_mutex);
863                 r128.process(left.size(), ptrs);
864                 correlation.process_samples(samples_out);
865         }
866
867         // Send the samples to the sound card.
868         if (alsa) {
869                 alsa->write(samples_out);
870         }
871
872         // And finally add them to the output.
873         h264_encoder->add_audio(frame_pts_int, move(samples_out));
874 }
875
876 void Mixer::subsample_chroma(GLuint src_tex, GLuint dst_tex)
877 {
878         GLuint vao;
879         glGenVertexArrays(1, &vao);
880         check_error();
881
882         float vertices[] = {
883                 0.0f, 2.0f,
884                 0.0f, 0.0f,
885                 2.0f, 0.0f
886         };
887
888         glBindVertexArray(vao);
889         check_error();
890
891         // Extract Cb/Cr.
892         GLuint fbo = resource_pool->create_fbo(dst_tex);
893         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
894         glViewport(0, 0, WIDTH/2, HEIGHT/2);
895         check_error();
896
897         glUseProgram(cbcr_program_num);
898         check_error();
899
900         glActiveTexture(GL_TEXTURE0);
901         check_error();
902         glBindTexture(GL_TEXTURE_2D, src_tex);
903         check_error();
904         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
905         check_error();
906         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
907         check_error();
908         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
909         check_error();
910
911         float chroma_offset_0[] = { -0.5f / WIDTH, 0.0f };
912         set_uniform_vec2(cbcr_program_num, "foo", "chroma_offset_0", chroma_offset_0);
913
914         GLuint position_vbo = fill_vertex_attribute(cbcr_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
915         GLuint texcoord_vbo = fill_vertex_attribute(cbcr_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices);  // Same as vertices.
916
917         glDrawArrays(GL_TRIANGLES, 0, 3);
918         check_error();
919
920         cleanup_vertex_attribute(cbcr_program_num, "position", position_vbo);
921         cleanup_vertex_attribute(cbcr_program_num, "texcoord", texcoord_vbo);
922
923         glUseProgram(0);
924         check_error();
925
926         resource_pool->release_fbo(fbo);
927         glDeleteVertexArrays(1, &vao);
928 }
929
930 void Mixer::release_display_frame(DisplayFrame *frame)
931 {
932         for (GLuint texnum : frame->temp_textures) {
933                 resource_pool->release_2d_texture(texnum);
934         }
935         frame->temp_textures.clear();
936         frame->ready_fence.reset();
937         frame->input_frames.clear();
938 }
939
940 void Mixer::start()
941 {
942         mixer_thread = thread(&Mixer::thread_func, this);
943         audio_thread = thread(&Mixer::audio_thread_func, this);
944 }
945
946 void Mixer::quit()
947 {
948         should_quit = true;
949         mixer_thread.join();
950         audio_thread.join();
951 }
952
953 void Mixer::transition_clicked(int transition_num)
954 {
955         theme->transition_clicked(transition_num, pts());
956 }
957
958 void Mixer::channel_clicked(int preview_num)
959 {
960         theme->channel_clicked(preview_num);
961 }
962
963 void Mixer::reset_meters()
964 {
965         peak_resampler.reset();
966         peak = 0.0f;
967         r128.reset();
968         r128.integr_start();
969         correlation.reset();
970 }
971
972 Mixer::OutputChannel::~OutputChannel()
973 {
974         if (has_current_frame) {
975                 parent->release_display_frame(&current_frame);
976         }
977         if (has_ready_frame) {
978                 parent->release_display_frame(&ready_frame);
979         }
980 }
981
982 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
983 {
984         // Store this frame for display. Remove the ready frame if any
985         // (it was seemingly never used).
986         {
987                 unique_lock<mutex> lock(frame_mutex);
988                 if (has_ready_frame) {
989                         parent->release_display_frame(&ready_frame);
990                 }
991                 ready_frame = frame;
992                 has_ready_frame = true;
993         }
994
995         if (has_new_frame_ready_callback) {
996                 new_frame_ready_callback();
997         }
998 }
999
1000 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1001 {
1002         unique_lock<mutex> lock(frame_mutex);
1003         if (!has_current_frame && !has_ready_frame) {
1004                 return false;
1005         }
1006
1007         if (has_current_frame && has_ready_frame) {
1008                 // We have a new ready frame. Toss the current one.
1009                 parent->release_display_frame(&current_frame);
1010                 has_current_frame = false;
1011         }
1012         if (has_ready_frame) {
1013                 assert(!has_current_frame);
1014                 current_frame = ready_frame;
1015                 ready_frame.ready_fence.reset();  // Drop the refcount.
1016                 ready_frame.input_frames.clear();  // Drop the refcounts.
1017                 has_current_frame = true;
1018                 has_ready_frame = false;
1019         }
1020
1021         *frame = current_frame;
1022         return true;
1023 }
1024
1025 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1026 {
1027         new_frame_ready_callback = callback;
1028         has_new_frame_ready_callback = true;
1029 }