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