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