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