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