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