]> git.sesse.net Git - nageru/blob - mixer.cpp
Fix a deadlock issue when shutting down ALSA cards.
[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         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         DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
290         audio_mixer.reset_resampler(device);
291         audio_mixer.set_name(device, card->capture->get_description());
292 }
293
294
295 namespace {
296
297 int unwrap_timecode(uint16_t current_wrapped, int last)
298 {
299         uint16_t last_wrapped = last & 0xffff;
300         if (current_wrapped > last_wrapped) {
301                 return (last & ~0xffff) | current_wrapped;
302         } else {
303                 return 0x10000 + ((last & ~0xffff) | current_wrapped);
304         }
305 }
306
307 float find_peak(const float *samples, size_t num_samples)
308 {
309         float m = fabs(samples[0]);
310         for (size_t i = 1; i < num_samples; ++i) {
311                 m = max(m, fabs(samples[i]));
312         }
313         return m;
314 }
315
316 void deinterleave_samples(const vector<float> &in, vector<float> *out_l, vector<float> *out_r)
317 {
318         size_t num_samples = in.size() / 2;
319         out_l->resize(num_samples);
320         out_r->resize(num_samples);
321
322         const float *inptr = in.data();
323         float *lptr = &(*out_l)[0];
324         float *rptr = &(*out_r)[0];
325         for (size_t i = 0; i < num_samples; ++i) {
326                 *lptr++ = *inptr++;
327                 *rptr++ = *inptr++;
328         }
329 }
330
331 }  // namespace
332
333 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
334                      FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
335                      FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
336 {
337         DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
338         CaptureCard *card = &cards[card_index];
339
340         if (is_mode_scanning[card_index]) {
341                 if (video_format.has_signal) {
342                         // Found a stable signal, so stop scanning.
343                         is_mode_scanning[card_index] = false;
344                 } else {
345                         static constexpr double switch_time_s = 0.5;  // Should be enough time for the signal to stabilize.
346                         steady_clock::time_point now = steady_clock::now();
347                         double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
348                         if (sec_since_last_switch > switch_time_s) {
349                                 // It isn't this mode; try the next one.
350                                 mode_scanlist_index[card_index]++;
351                                 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
352                                 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
353                                 last_mode_scan_change[card_index] = now;
354                         }
355                 }
356         }
357
358         int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
359         assert(frame_length > 0);
360
361         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;
362         if (num_samples > OUTPUT_FREQUENCY / 10) {
363                 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",
364                         card_index, int(audio_frame.len), int(audio_offset),
365                         timecode, int(video_frame.len), int(video_offset), video_format.id);
366                 if (video_frame.owner) {
367                         video_frame.owner->release_frame(video_frame);
368                 }
369                 if (audio_frame.owner) {
370                         audio_frame.owner->release_frame(audio_frame);
371                 }
372                 return;
373         }
374
375         int dropped_frames = 0;
376         if (card->last_timecode != -1) {
377                 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
378         }
379
380         // Number of samples per frame if we need to insert silence.
381         // (Could be nonintegral, but resampling will save us then.)
382         const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
383
384         if (dropped_frames > MAX_FPS * 2) {
385                 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
386                         card_index, card->last_timecode, timecode);
387                 audio_mixer.reset_resampler(device);
388                 dropped_frames = 0;
389         } else if (dropped_frames > 0) {
390                 // Insert silence as needed.
391                 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
392                         card_index, dropped_frames, timecode);
393
394                 bool success;
395                 do {
396                         success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
397                 } while (!success);
398         }
399
400         audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length);
401
402         // Done with the audio, so release it.
403         if (audio_frame.owner) {
404                 audio_frame.owner->release_frame(audio_frame);
405         }
406
407         card->last_timecode = timecode;
408
409         size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
410         if (video_frame.len - video_offset == 0 ||
411             video_frame.len - video_offset != expected_length) {
412                 if (video_frame.len != 0) {
413                         printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
414                                 card_index, video_frame.len - video_offset, expected_length);
415                 }
416                 if (video_frame.owner) {
417                         video_frame.owner->release_frame(video_frame);
418                 }
419
420                 // Still send on the information that we _had_ a frame, even though it's corrupted,
421                 // so that pts can go up accordingly.
422                 {
423                         unique_lock<mutex> lock(bmusb_mutex);
424                         CaptureCard::NewFrame new_frame;
425                         new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
426                         new_frame.length = frame_length;
427                         new_frame.interlaced = false;
428                         new_frame.dropped_frames = dropped_frames;
429                         card->new_frames.push(move(new_frame));
430                         card->new_frames_changed.notify_all();
431                 }
432                 return;
433         }
434
435         PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
436
437         unsigned num_fields = video_format.interlaced ? 2 : 1;
438         steady_clock::time_point frame_upload_start;
439         if (video_format.interlaced) {
440                 // Send the two fields along as separate frames; the other side will need to add
441                 // a deinterlacer to actually get this right.
442                 assert(video_format.height % 2 == 0);
443                 video_format.height /= 2;
444                 assert(frame_length % 2 == 0);
445                 frame_length /= 2;
446                 num_fields = 2;
447                 frame_upload_start = steady_clock::now();
448         }
449         userdata->last_interlaced = video_format.interlaced;
450         userdata->last_has_signal = video_format.has_signal;
451         userdata->last_is_connected = video_format.is_connected;
452         userdata->last_frame_rate_nom = video_format.frame_rate_nom;
453         userdata->last_frame_rate_den = video_format.frame_rate_den;
454         RefCountedFrame frame(video_frame);
455
456         // Upload the textures.
457         size_t cbcr_width = video_format.width / 2;
458         size_t cbcr_offset = video_offset / 2;
459         size_t y_offset = video_frame.size / 2 + video_offset / 2;
460
461         for (unsigned field = 0; field < num_fields; ++field) {
462                 // Put the actual texture upload in a lambda that is executed in the main thread.
463                 // It is entirely possible to do this in the same thread (and it might even be
464                 // faster, depending on the GPU and driver), but it appears to be trickling
465                 // driver bugs very easily.
466                 //
467                 // Note that this means we must hold on to the actual frame data in <userdata>
468                 // until the upload command is run, but we hold on to <frame> much longer than that
469                 // (in fact, all the way until we no longer use the texture in rendering).
470                 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, userdata]() {
471                         unsigned field_start_line = (field == 1) ? video_format.second_field_start : video_format.extra_lines_top + field * (video_format.height + 22);
472
473                         if (userdata->tex_y[field] == 0 ||
474                             userdata->tex_cbcr[field] == 0 ||
475                             video_format.width != userdata->last_width[field] ||
476                             video_format.height != userdata->last_height[field]) {
477                                 // We changed resolution since last use of this texture, so we need to create
478                                 // a new object. Note that this each card has its own PBOFrameAllocator,
479                                 // we don't need to worry about these flip-flopping between resolutions.
480                                 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
481                                 check_error();
482                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
483                                 check_error();
484                                 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
485                                 check_error();
486                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
487                                 check_error();
488                                 userdata->last_width[field] = video_format.width;
489                                 userdata->last_height[field] = video_format.height;
490                         }
491
492                         GLuint pbo = userdata->pbo;
493                         check_error();
494                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
495                         check_error();
496
497                         size_t field_y_start = y_offset + video_format.width * field_start_line;
498                         size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
499
500                         if (global_flags.flush_pbos) {
501                                 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
502                                 check_error();
503                                 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
504                                 check_error();
505                         }
506
507                         glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
508                         check_error();
509                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
510                         check_error();
511                         glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
512                         check_error();
513                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
514                         check_error();
515                         glBindTexture(GL_TEXTURE_2D, 0);
516                         check_error();
517                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
518                         check_error();
519                 };
520
521                 if (field == 1) {
522                         // Don't upload the second field as fast as we can; wait until
523                         // the field time has approximately passed. (Otherwise, we could
524                         // get timing jitter against the other sources, and possibly also
525                         // against the video display, although the latter is not as critical.)
526                         // This requires our system clock to be reasonably close to the
527                         // video clock, but that's not an unreasonable assumption.
528                         steady_clock::time_point second_field_start = frame_upload_start +
529                                 nanoseconds(frame_length * 1000000000 / TIMEBASE);
530                         this_thread::sleep_until(second_field_start);
531                 }
532
533                 {
534                         unique_lock<mutex> lock(bmusb_mutex);
535                         CaptureCard::NewFrame new_frame;
536                         new_frame.frame = frame;
537                         new_frame.length = frame_length;
538                         new_frame.field = field;
539                         new_frame.interlaced = video_format.interlaced;
540                         new_frame.upload_func = upload_func;
541                         new_frame.dropped_frames = dropped_frames;
542                         card->new_frames.push(move(new_frame));
543                         card->new_frames_changed.notify_all();
544                 }
545         }
546 }
547
548 void Mixer::bm_hotplug_add(libusb_device *dev)
549 {
550         lock_guard<mutex> lock(hotplug_mutex);
551         hotplugged_cards.push_back(dev);
552 }
553
554 void Mixer::bm_hotplug_remove(unsigned card_index)
555 {
556         cards[card_index].new_frames_changed.notify_all();
557 }
558
559 void Mixer::thread_func()
560 {
561         eglBindAPI(EGL_OPENGL_API);
562         QOpenGLContext *context = create_context(mixer_surface);
563         if (!make_current(context, mixer_surface)) {
564                 printf("oops\n");
565                 exit(1);
566         }
567
568         steady_clock::time_point start, now;
569         start = steady_clock::now();
570
571         int frame = 0;
572         int stats_dropped_frames = 0;
573
574         while (!should_quit) {
575                 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
576                 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
577                 int num_samples[MAX_VIDEO_CARDS] = { 0 };
578
579                 unsigned master_card_index = theme->map_signal(master_clock_channel);
580                 assert(master_card_index < num_cards);
581
582                 get_one_frame_from_each_card(master_card_index, new_frames, has_new_frame, num_samples);
583                 schedule_audio_resampling_tasks(new_frames[master_card_index].dropped_frames, num_samples[master_card_index], new_frames[master_card_index].length);
584                 stats_dropped_frames += new_frames[master_card_index].dropped_frames;
585                 send_audio_level_callback();
586
587                 handle_hotplugged_cards();
588
589                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
590                         if (card_index == master_card_index || !has_new_frame[card_index]) {
591                                 continue;
592                         }
593                         if (new_frames[card_index].frame->len == 0) {
594                                 ++new_frames[card_index].dropped_frames;
595                         }
596                         if (new_frames[card_index].dropped_frames > 0) {
597                                 printf("Card %u dropped %d frames before this\n",
598                                         card_index, int(new_frames[card_index].dropped_frames));
599                         }
600                 }
601
602                 // If the first card is reporting a corrupted or otherwise dropped frame,
603                 // just increase the pts (skipping over this frame) and don't try to compute anything new.
604                 if (new_frames[master_card_index].frame->len == 0) {
605                         ++stats_dropped_frames;
606                         pts_int += new_frames[master_card_index].length;
607                         continue;
608                 }
609
610                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
611                         if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
612                                 continue;
613
614                         CaptureCard::NewFrame *new_frame = &new_frames[card_index];
615                         assert(new_frame->frame != nullptr);
616                         insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
617                         check_error();
618
619                         // The new texture might need uploading before use.
620                         if (new_frame->upload_func) {
621                                 new_frame->upload_func();
622                                 new_frame->upload_func = nullptr;
623                         }
624                 }
625
626                 int64_t frame_duration = new_frames[master_card_index].length;
627                 render_one_frame(frame_duration);
628                 ++frame;
629                 pts_int += frame_duration;
630
631                 now = steady_clock::now();
632                 double elapsed = duration<double>(now - start).count();
633                 if (frame % 100 == 0) {
634                         printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
635                                 frame, stats_dropped_frames, elapsed, frame / elapsed,
636                                 1e3 * elapsed / frame);
637                 //      chain->print_phase_timing();
638
639                         // Check our memory usage, to see if we are close to our mlockall()
640                         // limit (if at all set).
641                         rusage used;
642                         if (getrusage(RUSAGE_SELF, &used) == -1) {
643                                 perror("getrusage(RUSAGE_SELF)");
644                                 assert(false);
645                         }
646
647                         if (uses_mlock) {
648                                 rlimit limit;
649                                 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
650                                         perror("getrlimit(RLIMIT_MEMLOCK)");
651                                         assert(false);
652                                 }
653
654                                 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
655                                         long(used.ru_maxrss / 1024),
656                                         long(limit.rlim_cur / 1048576),
657                                         float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
658                         } else {
659                                 printf(", using %ld MB memory (not locked)",
660                                         long(used.ru_maxrss / 1024));
661                         }
662
663                         printf("\n");
664                 }
665
666
667                 if (should_cut.exchange(false)) {  // Test and clear.
668                         video_encoder->do_cut(frame);
669                 }
670
671 #if 0
672                 // Reset every 100 frames, so that local variations in frame times
673                 // (especially for the first few frames, when the shaders are
674                 // compiled etc.) don't make it hard to measure for the entire
675                 // remaining duration of the program.
676                 if (frame == 10000) {
677                         frame = 0;
678                         start = now;
679                 }
680 #endif
681                 check_error();
682         }
683
684         resource_pool->clean_context();
685 }
686
687 void Mixer::get_one_frame_from_each_card(unsigned master_card_index, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS], int num_samples[MAX_VIDEO_CARDS])
688 {
689 start:
690         // The first card is the master timer, so wait for it to have a new frame.
691         // TODO: Add a timeout.
692         unique_lock<mutex> lock(bmusb_mutex);
693         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(); });
694
695         if (cards[master_card_index].new_frames.empty()) {
696                 // We were woken up, but not due to a new frame. Deal with it
697                 // and then restart.
698                 assert(cards[master_card_index].capture->get_disconnected());
699                 handle_hotplugged_cards();
700                 goto start;
701         }
702
703         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
704                 CaptureCard *card = &cards[card_index];
705                 if (card->new_frames.empty()) {
706                         assert(card_index != master_card_index);
707                         card->queue_length_policy.update_policy(-1);
708                         continue;
709                 }
710                 new_frames[card_index] = move(card->new_frames.front());
711                 has_new_frame[card_index] = true;
712                 card->new_frames.pop();
713                 card->new_frames_changed.notify_all();
714
715                 int num_samples_times_timebase = OUTPUT_FREQUENCY * new_frames[card_index].length + card->fractional_samples;
716                 num_samples[card_index] = num_samples_times_timebase / TIMEBASE;
717                 card->fractional_samples = num_samples_times_timebase % TIMEBASE;
718                 assert(num_samples[card_index] >= 0);
719
720                 if (card_index == master_card_index) {
721                         // We don't use the queue length policy for the master card,
722                         // but we will if it stops being the master. Thus, clear out
723                         // the policy in case we switch in the future.
724                         card->queue_length_policy.reset(card_index);
725                 } else {
726                         // If we have excess frames compared to the policy for this card,
727                         // drop frames from the head.
728                         card->queue_length_policy.update_policy(card->new_frames.size());
729                         while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
730                                 card->new_frames.pop();
731                         }
732                 }
733         }
734 }
735
736 void Mixer::handle_hotplugged_cards()
737 {
738         // Check for cards that have been disconnected since last frame.
739         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
740                 CaptureCard *card = &cards[card_index];
741                 if (card->capture->get_disconnected()) {
742                         fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
743                         FakeCapture *capture = new FakeCapture(WIDTH, HEIGHT, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
744                         configure_card(card_index, capture, /*is_fake_capture=*/true);
745                         card->queue_length_policy.reset(card_index);
746                         card->capture->start_bm_capture();
747                 }
748         }
749
750         // Check for cards that have been connected since last frame.
751         vector<libusb_device *> hotplugged_cards_copy;
752         {
753                 lock_guard<mutex> lock(hotplug_mutex);
754                 swap(hotplugged_cards, hotplugged_cards_copy);
755         }
756         for (libusb_device *new_dev : hotplugged_cards_copy) {
757                 // Look for a fake capture card where we can stick this in.
758                 int free_card_index = -1;
759                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
760                         if (cards[card_index].is_fake_capture) {
761                                 free_card_index = int(card_index);
762                                 break;
763                         }
764                 }
765
766                 if (free_card_index == -1) {
767                         fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
768                         libusb_unref_device(new_dev);
769                 } else {
770                         // BMUSBCapture takes ownership.
771                         fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
772                         CaptureCard *card = &cards[free_card_index];
773                         BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
774                         configure_card(free_card_index, capture, /*is_fake_capture=*/false);
775                         card->queue_length_policy.reset(free_card_index);
776                         capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
777                         capture->start_bm_capture();
778                 }
779         }
780 }
781
782
783 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame)
784 {
785         // Resample the audio as needed, including from previously dropped frames.
786         assert(num_cards > 0);
787         for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
788                 const bool dropped_frame = (frame_num != dropped_frames);
789                 {
790                         // Signal to the audio thread to process this frame.
791                         // Note that if the frame is a dropped frame, we signal that
792                         // we don't want to use this frame as base for adjusting
793                         // the resampler rate. The reason for this is that the timing
794                         // of these frames is often way too late; they typically don't
795                         // “arrive” before we synthesize them. Thus, we could end up
796                         // in a situation where we have inserted e.g. five audio frames
797                         // into the queue before we then start pulling five of them
798                         // back out. This makes ResamplingQueue overestimate the delay,
799                         // causing undue resampler changes. (We _do_ use the last,
800                         // non-dropped frame; perhaps we should just discard that as well,
801                         // since dropped frames are expected to be rare, and it might be
802                         // better to just wait until we have a slightly more normal situation).
803                         unique_lock<mutex> lock(audio_mutex);
804                         bool adjust_rate = !dropped_frame;
805                         audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate});
806                         audio_task_queue_changed.notify_one();
807                 }
808                 if (dropped_frame) {
809                         // For dropped frames, increase the pts. Note that if the format changed
810                         // in the meantime, we have no way of detecting that; we just have to
811                         // assume the frame length is always the same.
812                         pts_int += length_per_frame;
813                 }
814         }
815 }
816
817 void Mixer::render_one_frame(int64_t duration)
818 {
819         // Get the main chain from the theme, and set its state immediately.
820         Theme::Chain theme_main_chain = theme->get_chain(0, pts(), WIDTH, HEIGHT, input_state);
821         EffectChain *chain = theme_main_chain.chain;
822         theme_main_chain.setup_chain();
823         //theme_main_chain.chain->enable_phase_timing(true);
824
825         GLuint y_tex, cbcr_tex;
826         bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
827         assert(got_frame);
828
829         // Render main chain.
830         GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, WIDTH, HEIGHT);
831         GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, WIDTH, HEIGHT);  // Saves texture bandwidth, although dithering gets messed up.
832         GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
833         check_error();
834         chain->render_to_fbo(fbo, WIDTH, HEIGHT);
835         resource_pool->release_fbo(fbo);
836
837         subsample_chroma(cbcr_full_tex, cbcr_tex);
838         resource_pool->release_2d_texture(cbcr_full_tex);
839
840         // Set the right state for rgba_tex.
841         glBindFramebuffer(GL_FRAMEBUFFER, 0);
842         glBindTexture(GL_TEXTURE_2D, rgba_tex);
843         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
844         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
845         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
846
847         const int64_t av_delay = TIMEBASE / 10;  // Corresponds to the fixed delay in resampling_queue.h. TODO: Make less hard-coded.
848         RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
849
850         // The live frame just shows the RGBA texture we just rendered.
851         // It owns rgba_tex now.
852         DisplayFrame live_frame;
853         live_frame.chain = display_chain.get();
854         live_frame.setup_chain = [this, rgba_tex]{
855                 display_input->set_texture_num(rgba_tex);
856         };
857         live_frame.ready_fence = fence;
858         live_frame.input_frames = {};
859         live_frame.temp_textures = { rgba_tex };
860         output_channel[OUTPUT_LIVE].output_frame(live_frame);
861
862         // Set up preview and any additional channels.
863         for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
864                 DisplayFrame display_frame;
865                 Theme::Chain chain = theme->get_chain(i, pts(), WIDTH, HEIGHT, input_state);  // FIXME: dimensions
866                 display_frame.chain = chain.chain;
867                 display_frame.setup_chain = chain.setup_chain;
868                 display_frame.ready_fence = fence;
869                 display_frame.input_frames = chain.input_frames;
870                 display_frame.temp_textures = {};
871                 output_channel[i].output_frame(display_frame);
872         }
873 }
874
875 void Mixer::send_audio_level_callback()
876 {
877         if (audio_level_callback == nullptr) {
878                 return;
879         }
880
881         unique_lock<mutex> lock(audio_measure_mutex);
882         double loudness_s = r128.loudness_S();
883         double loudness_i = r128.integrated();
884         double loudness_range_low = r128.range_min();
885         double loudness_range_high = r128.range_max();
886
887         audio_level_callback(loudness_s, to_db(peak),
888                 loudness_i, loudness_range_low, loudness_range_high,
889                 audio_mixer.get_gain_staging_db(),
890                 audio_mixer.get_final_makeup_gain_db(),
891                 correlation.get_correlation());
892 }
893
894 void Mixer::audio_thread_func()
895 {
896         while (!should_quit) {
897                 AudioTask task;
898
899                 {
900                         unique_lock<mutex> lock(audio_mutex);
901                         audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
902                         if (should_quit) {
903                                 return;
904                         }
905                         task = audio_task_queue.front();
906                         audio_task_queue.pop();
907                 }
908
909                 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
910                         task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
911                 process_audio_one_frame(task.pts_int, task.num_samples, rate_adjustment_policy);
912         }
913 }
914
915 void Mixer::process_audio_one_frame(int64_t frame_pts_int, int num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
916 {
917         vector<float> samples_out = audio_mixer.get_output(double(frame_pts_int) / TIMEBASE, num_samples, rate_adjustment_policy);
918
919         // Upsample 4x to find interpolated peak.
920         peak_resampler.inp_data = samples_out.data();
921         peak_resampler.inp_count = samples_out.size() / 2;
922
923         vector<float> interpolated_samples_out;
924         interpolated_samples_out.resize(samples_out.size());
925         {
926                 unique_lock<mutex> lock(audio_measure_mutex);
927
928                 while (peak_resampler.inp_count > 0) {  // About four iterations.
929                         peak_resampler.out_data = &interpolated_samples_out[0];
930                         peak_resampler.out_count = interpolated_samples_out.size() / 2;
931                         peak_resampler.process();
932                         size_t out_stereo_samples = interpolated_samples_out.size() / 2 - peak_resampler.out_count;
933                         peak = max<float>(peak, find_peak(interpolated_samples_out.data(), out_stereo_samples * 2));
934                         peak_resampler.out_data = nullptr;
935                 }
936         }
937
938         // Find R128 levels and L/R correlation.
939         vector<float> left, right;
940         deinterleave_samples(samples_out, &left, &right);
941         float *ptrs[] = { left.data(), right.data() };
942         {
943                 unique_lock<mutex> lock(audio_measure_mutex);
944                 r128.process(left.size(), ptrs);
945                 audio_mixer.set_current_loudness(r128.loudness_M());
946                 correlation.process_samples(samples_out);
947         }
948
949         // Send the samples to the sound card.
950         if (alsa) {
951                 alsa->write(samples_out);
952         }
953
954         // And finally add them to the output.
955         video_encoder->add_audio(frame_pts_int, move(samples_out));
956 }
957
958 void Mixer::subsample_chroma(GLuint src_tex, GLuint dst_tex)
959 {
960         GLuint vao;
961         glGenVertexArrays(1, &vao);
962         check_error();
963
964         glBindVertexArray(vao);
965         check_error();
966
967         // Extract Cb/Cr.
968         GLuint fbo = resource_pool->create_fbo(dst_tex);
969         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
970         glViewport(0, 0, WIDTH/2, HEIGHT/2);
971         check_error();
972
973         glUseProgram(cbcr_program_num);
974         check_error();
975
976         glActiveTexture(GL_TEXTURE0);
977         check_error();
978         glBindTexture(GL_TEXTURE_2D, src_tex);
979         check_error();
980         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
981         check_error();
982         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
983         check_error();
984         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
985         check_error();
986
987         float chroma_offset_0[] = { -0.5f / WIDTH, 0.0f };
988         set_uniform_vec2(cbcr_program_num, "foo", "chroma_offset_0", chroma_offset_0);
989
990         glBindBuffer(GL_ARRAY_BUFFER, cbcr_vbo);
991         check_error();
992
993         for (GLint attr_index : { cbcr_position_attribute_index, cbcr_texcoord_attribute_index }) {
994                 glEnableVertexAttribArray(attr_index);
995                 check_error();
996                 glVertexAttribPointer(attr_index, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
997                 check_error();
998         }
999
1000         glDrawArrays(GL_TRIANGLES, 0, 3);
1001         check_error();
1002
1003         for (GLint attr_index : { cbcr_position_attribute_index, cbcr_texcoord_attribute_index }) {
1004                 glDisableVertexAttribArray(attr_index);
1005                 check_error();
1006         }
1007
1008         glUseProgram(0);
1009         check_error();
1010         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1011         check_error();
1012
1013         resource_pool->release_fbo(fbo);
1014         glDeleteVertexArrays(1, &vao);
1015 }
1016
1017 void Mixer::release_display_frame(DisplayFrame *frame)
1018 {
1019         for (GLuint texnum : frame->temp_textures) {
1020                 resource_pool->release_2d_texture(texnum);
1021         }
1022         frame->temp_textures.clear();
1023         frame->ready_fence.reset();
1024         frame->input_frames.clear();
1025 }
1026
1027 void Mixer::start()
1028 {
1029         mixer_thread = thread(&Mixer::thread_func, this);
1030         audio_thread = thread(&Mixer::audio_thread_func, this);
1031 }
1032
1033 void Mixer::quit()
1034 {
1035         should_quit = true;
1036         audio_task_queue_changed.notify_one();
1037         mixer_thread.join();
1038         audio_thread.join();
1039 }
1040
1041 void Mixer::transition_clicked(int transition_num)
1042 {
1043         theme->transition_clicked(transition_num, pts());
1044 }
1045
1046 void Mixer::channel_clicked(int preview_num)
1047 {
1048         theme->channel_clicked(preview_num);
1049 }
1050
1051 void Mixer::reset_meters()
1052 {
1053         unique_lock<mutex> lock(audio_measure_mutex);
1054         peak_resampler.reset();
1055         peak = 0.0f;
1056         r128.reset();
1057         r128.integr_start();
1058         correlation.reset();
1059 }
1060
1061 void Mixer::start_mode_scanning(unsigned card_index)
1062 {
1063         assert(card_index < num_cards);
1064         if (is_mode_scanning[card_index]) {
1065                 return;
1066         }
1067         is_mode_scanning[card_index] = true;
1068         mode_scanlist[card_index].clear();
1069         for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1070                 mode_scanlist[card_index].push_back(mode.first);
1071         }
1072         assert(!mode_scanlist[card_index].empty());
1073         mode_scanlist_index[card_index] = 0;
1074         cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1075         last_mode_scan_change[card_index] = steady_clock::now();
1076 }
1077
1078 Mixer::OutputChannel::~OutputChannel()
1079 {
1080         if (has_current_frame) {
1081                 parent->release_display_frame(&current_frame);
1082         }
1083         if (has_ready_frame) {
1084                 parent->release_display_frame(&ready_frame);
1085         }
1086 }
1087
1088 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1089 {
1090         // Store this frame for display. Remove the ready frame if any
1091         // (it was seemingly never used).
1092         {
1093                 unique_lock<mutex> lock(frame_mutex);
1094                 if (has_ready_frame) {
1095                         parent->release_display_frame(&ready_frame);
1096                 }
1097                 ready_frame = frame;
1098                 has_ready_frame = true;
1099         }
1100
1101         if (new_frame_ready_callback) {
1102                 new_frame_ready_callback();
1103         }
1104
1105         // Reduce the number of callbacks by filtering duplicates. The reason
1106         // why we bother doing this is that Qt seemingly can get into a state
1107         // where its builds up an essentially unbounded queue of signals,
1108         // consuming more and more memory, and there's no good way of collapsing
1109         // user-defined signals or limiting the length of the queue.
1110         if (transition_names_updated_callback) {
1111                 vector<string> transition_names = global_mixer->get_transition_names();
1112                 bool changed = false;
1113                 if (transition_names.size() != last_transition_names.size()) {
1114                         changed = true;
1115                 } else {
1116                         for (unsigned i = 0; i < transition_names.size(); ++i) {
1117                                 if (transition_names[i] != last_transition_names[i]) {
1118                                         changed = true;
1119                                         break;
1120                                 }
1121                         }
1122                 }
1123                 if (changed) {
1124                         transition_names_updated_callback(transition_names);
1125                         last_transition_names = transition_names;
1126                 }
1127         }
1128         if (name_updated_callback) {
1129                 string name = global_mixer->get_channel_name(channel);
1130                 if (name != last_name) {
1131                         name_updated_callback(name);
1132                         last_name = name;
1133                 }
1134         }
1135         if (color_updated_callback) {
1136                 string color = global_mixer->get_channel_color(channel);
1137                 if (color != last_color) {
1138                         color_updated_callback(color);
1139                         last_color = color;
1140                 }
1141         }
1142 }
1143
1144 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1145 {
1146         unique_lock<mutex> lock(frame_mutex);
1147         if (!has_current_frame && !has_ready_frame) {
1148                 return false;
1149         }
1150
1151         if (has_current_frame && has_ready_frame) {
1152                 // We have a new ready frame. Toss the current one.
1153                 parent->release_display_frame(&current_frame);
1154                 has_current_frame = false;
1155         }
1156         if (has_ready_frame) {
1157                 assert(!has_current_frame);
1158                 current_frame = ready_frame;
1159                 ready_frame.ready_fence.reset();  // Drop the refcount.
1160                 ready_frame.input_frames.clear();  // Drop the refcounts.
1161                 has_current_frame = true;
1162                 has_ready_frame = false;
1163         }
1164
1165         *frame = current_frame;
1166         return true;
1167 }
1168
1169 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1170 {
1171         new_frame_ready_callback = callback;
1172 }
1173
1174 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1175 {
1176         transition_names_updated_callback = callback;
1177 }
1178
1179 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1180 {
1181         name_updated_callback = callback;
1182 }
1183
1184 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1185 {
1186         color_updated_callback = callback;
1187 }
1188
1189 mutex RefCountedGLsync::fence_lock;