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