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