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