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