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