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