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