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