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>
18 #include <sys/resource.h>
24 #include <condition_variable>
33 #include "bmusb/bmusb.h"
34 #include "bmusb/fake_capture.h"
37 #include "decklink_capture.h"
39 #include "disk_space_estimator.h"
41 #include "pbo_frame_allocator.h"
42 #include "ref_counted_gl_sync.h"
44 #include "video_encoder.h"
48 using namespace movit;
50 using namespace std::chrono;
51 using namespace std::placeholders;
52 using namespace bmusb;
54 Mixer *global_mixer = nullptr;
55 bool uses_mlock = false;
59 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
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];
66 input_state->buffered_frames[card_index][0] = { frame, field_num };
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 };
76 void QueueLengthPolicy::update_policy(int queue_length)
78 if (queue_length < 0) { // Starvation.
79 if (been_at_safe_point_since_last_starvation && safe_queue_length < 5) {
81 fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frames\n",
82 card_index, safe_queue_length);
84 frames_with_at_least_one = 0;
85 been_at_safe_point_since_last_starvation = false;
88 if (queue_length > 0) {
89 if (queue_length >= int(safe_queue_length)) {
90 been_at_safe_point_since_last_starvation = true;
92 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 0) {
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;
99 frames_with_at_least_one = 0;
103 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
105 num_cards(num_cards),
106 mixer_surface(create_surface(format)),
107 h264_encoder_surface(create_surface(format)),
108 audio_mixer(num_cards)
110 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
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;
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;
124 ImageFormat inout_format;
125 inout_format.color_space = COLORSPACE_sRGB;
126 inout_format.gamma_curve = GAMMA_sRGB;
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()));
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();
137 video_encoder.reset(new VideoEncoder(resource_pool.get(), h264_encoder_surface, global_flags.va_display, WIDTH, HEIGHT, &httpd, global_disk_space_estimator));
139 // Start listening for clients only once VideoEncoder has written its header, if any.
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;
148 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
149 if (decklink_iterator != nullptr) {
150 for ( ; card_index < num_cards; ++card_index) {
152 if (decklink_iterator->Next(&decklink) != S_OK) {
156 configure_card(card_index, new DeckLinkCapture(decklink, card_index), /*is_fake_capture=*/false);
159 decklink_iterator->Release();
160 fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
162 fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
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);
171 fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
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);
179 if (num_fake_cards > 0) {
180 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
183 BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
184 BMUSBCapture::start_bm_thread();
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();
191 // Set up stuff for NV12 conversion.
194 string cbcr_vert_shader =
197 "in vec2 position; \n"
198 "in vec2 texcoord; \n"
200 "uniform vec2 foo_chroma_offset_0; \n"
204 " // The result of glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0) is: \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"
214 string cbcr_frag_shader =
217 "uniform sampler2D cbcr_tex; \n"
218 "out vec4 FragColor; \n"
220 " FragColor = texture(cbcr_tex, tc0); \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);
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");
234 if (global_flags.enable_alsa_output) {
235 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
241 resource_pool->release_glsl_program(cbcr_program_num);
242 glDeleteBuffers(1, &cbcr_vbo);
243 BMUSBCapture::stop_bm_thread();
245 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
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();
251 cards[card_index].capture->stop_dequeue_thread();
254 video_encoder.reset(nullptr);
257 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture)
259 printf("Configuring card %d...\n", card_index);
261 CaptureCard *card = &cards[card_index];
262 if (card->capture != nullptr) {
263 card->capture->stop_dequeue_thread();
264 delete card->capture;
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.
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);
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();
281 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
282 audio_mixer.reset_resampler(device);
283 audio_mixer.set_display_name(device, card->capture->get_description());
284 audio_mixer.trigger_state_changed_callback();
290 int unwrap_timecode(uint16_t current_wrapped, int last)
292 uint16_t last_wrapped = last & 0xffff;
293 if (current_wrapped > last_wrapped) {
294 return (last & ~0xffff) | current_wrapped;
296 return 0x10000 + ((last & ~0xffff) | current_wrapped);
302 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
303 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
304 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
306 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
307 CaptureCard *card = &cards[card_index];
309 if (is_mode_scanning[card_index]) {
310 if (video_format.has_signal) {
311 // Found a stable signal, so stop scanning.
312 is_mode_scanning[card_index] = false;
314 static constexpr double switch_time_s = 0.5; // Should be enough time for the signal to stabilize.
315 steady_clock::time_point now = steady_clock::now();
316 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
317 if (sec_since_last_switch > switch_time_s) {
318 // It isn't this mode; try the next one.
319 mode_scanlist_index[card_index]++;
320 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
321 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
322 last_mode_scan_change[card_index] = now;
327 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
328 assert(frame_length > 0);
330 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;
331 if (num_samples > OUTPUT_FREQUENCY / 10) {
332 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",
333 card_index, int(audio_frame.len), int(audio_offset),
334 timecode, int(video_frame.len), int(video_offset), video_format.id);
335 if (video_frame.owner) {
336 video_frame.owner->release_frame(video_frame);
338 if (audio_frame.owner) {
339 audio_frame.owner->release_frame(audio_frame);
344 int dropped_frames = 0;
345 if (card->last_timecode != -1) {
346 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
349 // Number of samples per frame if we need to insert silence.
350 // (Could be nonintegral, but resampling will save us then.)
351 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
353 if (dropped_frames > MAX_FPS * 2) {
354 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
355 card_index, card->last_timecode, timecode);
356 audio_mixer.reset_resampler(device);
358 } else if (dropped_frames > 0) {
359 // Insert silence as needed.
360 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
361 card_index, dropped_frames, timecode);
365 success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
369 audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length);
371 // Done with the audio, so release it.
372 if (audio_frame.owner) {
373 audio_frame.owner->release_frame(audio_frame);
376 card->last_timecode = timecode;
378 size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
379 if (video_frame.len - video_offset == 0 ||
380 video_frame.len - video_offset != expected_length) {
381 if (video_frame.len != 0) {
382 printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
383 card_index, video_frame.len - video_offset, expected_length);
385 if (video_frame.owner) {
386 video_frame.owner->release_frame(video_frame);
389 // Still send on the information that we _had_ a frame, even though it's corrupted,
390 // so that pts can go up accordingly.
392 unique_lock<mutex> lock(bmusb_mutex);
393 CaptureCard::NewFrame new_frame;
394 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
395 new_frame.length = frame_length;
396 new_frame.interlaced = false;
397 new_frame.dropped_frames = dropped_frames;
398 card->new_frames.push(move(new_frame));
399 card->new_frames_changed.notify_all();
404 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
406 unsigned num_fields = video_format.interlaced ? 2 : 1;
407 steady_clock::time_point frame_upload_start;
408 if (video_format.interlaced) {
409 // Send the two fields along as separate frames; the other side will need to add
410 // a deinterlacer to actually get this right.
411 assert(video_format.height % 2 == 0);
412 video_format.height /= 2;
413 assert(frame_length % 2 == 0);
416 frame_upload_start = steady_clock::now();
418 userdata->last_interlaced = video_format.interlaced;
419 userdata->last_has_signal = video_format.has_signal;
420 userdata->last_is_connected = video_format.is_connected;
421 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
422 userdata->last_frame_rate_den = video_format.frame_rate_den;
423 RefCountedFrame frame(video_frame);
425 // Upload the textures.
426 size_t cbcr_width = video_format.width / 2;
427 size_t cbcr_offset = video_offset / 2;
428 size_t y_offset = video_frame.size / 2 + video_offset / 2;
430 for (unsigned field = 0; field < num_fields; ++field) {
431 // Put the actual texture upload in a lambda that is executed in the main thread.
432 // It is entirely possible to do this in the same thread (and it might even be
433 // faster, depending on the GPU and driver), but it appears to be trickling
434 // driver bugs very easily.
436 // Note that this means we must hold on to the actual frame data in <userdata>
437 // until the upload command is run, but we hold on to <frame> much longer than that
438 // (in fact, all the way until we no longer use the texture in rendering).
439 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, userdata]() {
440 unsigned field_start_line = (field == 1) ? video_format.second_field_start : video_format.extra_lines_top + field * (video_format.height + 22);
442 if (userdata->tex_y[field] == 0 ||
443 userdata->tex_cbcr[field] == 0 ||
444 video_format.width != userdata->last_width[field] ||
445 video_format.height != userdata->last_height[field]) {
446 // We changed resolution since last use of this texture, so we need to create
447 // a new object. Note that this each card has its own PBOFrameAllocator,
448 // we don't need to worry about these flip-flopping between resolutions.
449 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
451 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
453 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
455 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
457 userdata->last_width[field] = video_format.width;
458 userdata->last_height[field] = video_format.height;
461 GLuint pbo = userdata->pbo;
463 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
466 size_t field_y_start = y_offset + video_format.width * field_start_line;
467 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
469 if (global_flags.flush_pbos) {
470 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
472 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
476 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
478 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
480 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
482 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
484 glBindTexture(GL_TEXTURE_2D, 0);
486 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
491 // Don't upload the second field as fast as we can; wait until
492 // the field time has approximately passed. (Otherwise, we could
493 // get timing jitter against the other sources, and possibly also
494 // against the video display, although the latter is not as critical.)
495 // This requires our system clock to be reasonably close to the
496 // video clock, but that's not an unreasonable assumption.
497 steady_clock::time_point second_field_start = frame_upload_start +
498 nanoseconds(frame_length * 1000000000 / TIMEBASE);
499 this_thread::sleep_until(second_field_start);
503 unique_lock<mutex> lock(bmusb_mutex);
504 CaptureCard::NewFrame new_frame;
505 new_frame.frame = frame;
506 new_frame.length = frame_length;
507 new_frame.field = field;
508 new_frame.interlaced = video_format.interlaced;
509 new_frame.upload_func = upload_func;
510 new_frame.dropped_frames = dropped_frames;
511 card->new_frames.push(move(new_frame));
512 card->new_frames_changed.notify_all();
517 void Mixer::bm_hotplug_add(libusb_device *dev)
519 lock_guard<mutex> lock(hotplug_mutex);
520 hotplugged_cards.push_back(dev);
523 void Mixer::bm_hotplug_remove(unsigned card_index)
525 cards[card_index].new_frames_changed.notify_all();
528 void Mixer::thread_func()
530 eglBindAPI(EGL_OPENGL_API);
531 QOpenGLContext *context = create_context(mixer_surface);
532 if (!make_current(context, mixer_surface)) {
537 steady_clock::time_point start, now;
538 start = steady_clock::now();
541 int stats_dropped_frames = 0;
543 while (!should_quit) {
544 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
545 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
546 int num_samples[MAX_VIDEO_CARDS] = { 0 };
548 unsigned master_card_index = theme->map_signal(master_clock_channel);
549 assert(master_card_index < num_cards);
551 get_one_frame_from_each_card(master_card_index, new_frames, has_new_frame, num_samples);
552 schedule_audio_resampling_tasks(new_frames[master_card_index].dropped_frames, num_samples[master_card_index], new_frames[master_card_index].length);
553 stats_dropped_frames += new_frames[master_card_index].dropped_frames;
555 handle_hotplugged_cards();
557 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
558 if (card_index == master_card_index || !has_new_frame[card_index]) {
561 if (new_frames[card_index].frame->len == 0) {
562 ++new_frames[card_index].dropped_frames;
564 if (new_frames[card_index].dropped_frames > 0) {
565 printf("Card %u dropped %d frames before this\n",
566 card_index, int(new_frames[card_index].dropped_frames));
570 // If the first card is reporting a corrupted or otherwise dropped frame,
571 // just increase the pts (skipping over this frame) and don't try to compute anything new.
572 if (new_frames[master_card_index].frame->len == 0) {
573 ++stats_dropped_frames;
574 pts_int += new_frames[master_card_index].length;
578 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
579 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
582 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
583 assert(new_frame->frame != nullptr);
584 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
587 // The new texture might need uploading before use.
588 if (new_frame->upload_func) {
589 new_frame->upload_func();
590 new_frame->upload_func = nullptr;
594 int64_t frame_duration = new_frames[master_card_index].length;
595 render_one_frame(frame_duration);
597 pts_int += frame_duration;
599 now = steady_clock::now();
600 double elapsed = duration<double>(now - start).count();
601 if (frame % 100 == 0) {
602 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
603 frame, stats_dropped_frames, elapsed, frame / elapsed,
604 1e3 * elapsed / frame);
605 // chain->print_phase_timing();
607 // Check our memory usage, to see if we are close to our mlockall()
608 // limit (if at all set).
610 if (getrusage(RUSAGE_SELF, &used) == -1) {
611 perror("getrusage(RUSAGE_SELF)");
617 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
618 perror("getrlimit(RLIMIT_MEMLOCK)");
622 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
623 long(used.ru_maxrss / 1024),
624 long(limit.rlim_cur / 1048576),
625 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
627 printf(", using %ld MB memory (not locked)",
628 long(used.ru_maxrss / 1024));
635 if (should_cut.exchange(false)) { // Test and clear.
636 video_encoder->do_cut(frame);
640 // Reset every 100 frames, so that local variations in frame times
641 // (especially for the first few frames, when the shaders are
642 // compiled etc.) don't make it hard to measure for the entire
643 // remaining duration of the program.
644 if (frame == 10000) {
652 resource_pool->clean_context();
655 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])
658 // The first card is the master timer, so wait for it to have a new frame.
659 // TODO: Add a timeout.
660 unique_lock<mutex> lock(bmusb_mutex);
661 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(); });
663 if (cards[master_card_index].new_frames.empty()) {
664 // We were woken up, but not due to a new frame. Deal with it
666 assert(cards[master_card_index].capture->get_disconnected());
667 handle_hotplugged_cards();
671 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
672 CaptureCard *card = &cards[card_index];
673 if (card->new_frames.empty()) {
674 assert(card_index != master_card_index);
675 card->queue_length_policy.update_policy(-1);
678 new_frames[card_index] = move(card->new_frames.front());
679 has_new_frame[card_index] = true;
680 card->new_frames.pop();
681 card->new_frames_changed.notify_all();
683 int num_samples_times_timebase = OUTPUT_FREQUENCY * new_frames[card_index].length + card->fractional_samples;
684 num_samples[card_index] = num_samples_times_timebase / TIMEBASE;
685 card->fractional_samples = num_samples_times_timebase % TIMEBASE;
686 assert(num_samples[card_index] >= 0);
688 if (card_index == master_card_index) {
689 // We don't use the queue length policy for the master card,
690 // but we will if it stops being the master. Thus, clear out
691 // the policy in case we switch in the future.
692 card->queue_length_policy.reset(card_index);
694 // If we have excess frames compared to the policy for this card,
695 // drop frames from the head.
696 card->queue_length_policy.update_policy(card->new_frames.size());
697 while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
698 card->new_frames.pop();
704 void Mixer::handle_hotplugged_cards()
706 // Check for cards that have been disconnected since last frame.
707 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
708 CaptureCard *card = &cards[card_index];
709 if (card->capture->get_disconnected()) {
710 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
711 FakeCapture *capture = new FakeCapture(WIDTH, HEIGHT, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
712 configure_card(card_index, capture, /*is_fake_capture=*/true);
713 card->queue_length_policy.reset(card_index);
714 card->capture->start_bm_capture();
718 // Check for cards that have been connected since last frame.
719 vector<libusb_device *> hotplugged_cards_copy;
721 lock_guard<mutex> lock(hotplug_mutex);
722 swap(hotplugged_cards, hotplugged_cards_copy);
724 for (libusb_device *new_dev : hotplugged_cards_copy) {
725 // Look for a fake capture card where we can stick this in.
726 int free_card_index = -1;
727 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
728 if (cards[card_index].is_fake_capture) {
729 free_card_index = int(card_index);
734 if (free_card_index == -1) {
735 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
736 libusb_unref_device(new_dev);
738 // BMUSBCapture takes ownership.
739 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
740 CaptureCard *card = &cards[free_card_index];
741 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
742 configure_card(free_card_index, capture, /*is_fake_capture=*/false);
743 card->queue_length_policy.reset(free_card_index);
744 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
745 capture->start_bm_capture();
751 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame)
753 // Resample the audio as needed, including from previously dropped frames.
754 assert(num_cards > 0);
755 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
756 const bool dropped_frame = (frame_num != dropped_frames);
758 // Signal to the audio thread to process this frame.
759 // Note that if the frame is a dropped frame, we signal that
760 // we don't want to use this frame as base for adjusting
761 // the resampler rate. The reason for this is that the timing
762 // of these frames is often way too late; they typically don't
763 // “arrive” before we synthesize them. Thus, we could end up
764 // in a situation where we have inserted e.g. five audio frames
765 // into the queue before we then start pulling five of them
766 // back out. This makes ResamplingQueue overestimate the delay,
767 // causing undue resampler changes. (We _do_ use the last,
768 // non-dropped frame; perhaps we should just discard that as well,
769 // since dropped frames are expected to be rare, and it might be
770 // better to just wait until we have a slightly more normal situation).
771 unique_lock<mutex> lock(audio_mutex);
772 bool adjust_rate = !dropped_frame;
773 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate});
774 audio_task_queue_changed.notify_one();
777 // For dropped frames, increase the pts. Note that if the format changed
778 // in the meantime, we have no way of detecting that; we just have to
779 // assume the frame length is always the same.
780 pts_int += length_per_frame;
785 void Mixer::render_one_frame(int64_t duration)
787 // Get the main chain from the theme, and set its state immediately.
788 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), WIDTH, HEIGHT, input_state);
789 EffectChain *chain = theme_main_chain.chain;
790 theme_main_chain.setup_chain();
791 //theme_main_chain.chain->enable_phase_timing(true);
793 GLuint y_tex, cbcr_tex;
794 bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
797 // Render main chain.
798 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, WIDTH, HEIGHT);
799 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, WIDTH, HEIGHT); // Saves texture bandwidth, although dithering gets messed up.
800 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
802 chain->render_to_fbo(fbo, WIDTH, HEIGHT);
803 resource_pool->release_fbo(fbo);
805 subsample_chroma(cbcr_full_tex, cbcr_tex);
806 resource_pool->release_2d_texture(cbcr_full_tex);
808 // Set the right state for rgba_tex.
809 glBindFramebuffer(GL_FRAMEBUFFER, 0);
810 glBindTexture(GL_TEXTURE_2D, rgba_tex);
811 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
812 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
813 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
815 const int64_t av_delay = TIMEBASE / 10; // Corresponds to the fixed delay in resampling_queue.h. TODO: Make less hard-coded.
816 RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
818 // The live frame just shows the RGBA texture we just rendered.
819 // It owns rgba_tex now.
820 DisplayFrame live_frame;
821 live_frame.chain = display_chain.get();
822 live_frame.setup_chain = [this, rgba_tex]{
823 display_input->set_texture_num(rgba_tex);
825 live_frame.ready_fence = fence;
826 live_frame.input_frames = {};
827 live_frame.temp_textures = { rgba_tex };
828 output_channel[OUTPUT_LIVE].output_frame(live_frame);
830 // Set up preview and any additional channels.
831 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
832 DisplayFrame display_frame;
833 Theme::Chain chain = theme->get_chain(i, pts(), WIDTH, HEIGHT, input_state); // FIXME: dimensions
834 display_frame.chain = chain.chain;
835 display_frame.setup_chain = chain.setup_chain;
836 display_frame.ready_fence = fence;
837 display_frame.input_frames = chain.input_frames;
838 display_frame.temp_textures = {};
839 output_channel[i].output_frame(display_frame);
843 void Mixer::audio_thread_func()
845 while (!should_quit) {
849 unique_lock<mutex> lock(audio_mutex);
850 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
854 task = audio_task_queue.front();
855 audio_task_queue.pop();
858 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
859 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
860 vector<float> samples_out = audio_mixer.get_output(
861 double(task.pts_int) / TIMEBASE,
863 rate_adjustment_policy);
865 // Send the samples to the sound card, then add them to the output.
867 alsa->write(samples_out);
869 video_encoder->add_audio(task.pts_int, move(samples_out));
873 void Mixer::subsample_chroma(GLuint src_tex, GLuint dst_tex)
876 glGenVertexArrays(1, &vao);
879 glBindVertexArray(vao);
883 GLuint fbo = resource_pool->create_fbo(dst_tex);
884 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
885 glViewport(0, 0, WIDTH/2, HEIGHT/2);
888 glUseProgram(cbcr_program_num);
891 glActiveTexture(GL_TEXTURE0);
893 glBindTexture(GL_TEXTURE_2D, src_tex);
895 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
897 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
899 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
902 float chroma_offset_0[] = { -0.5f / WIDTH, 0.0f };
903 set_uniform_vec2(cbcr_program_num, "foo", "chroma_offset_0", chroma_offset_0);
905 glBindBuffer(GL_ARRAY_BUFFER, cbcr_vbo);
908 for (GLint attr_index : { cbcr_position_attribute_index, cbcr_texcoord_attribute_index }) {
909 glEnableVertexAttribArray(attr_index);
911 glVertexAttribPointer(attr_index, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
915 glDrawArrays(GL_TRIANGLES, 0, 3);
918 for (GLint attr_index : { cbcr_position_attribute_index, cbcr_texcoord_attribute_index }) {
919 glDisableVertexAttribArray(attr_index);
925 glBindFramebuffer(GL_FRAMEBUFFER, 0);
928 resource_pool->release_fbo(fbo);
929 glDeleteVertexArrays(1, &vao);
932 void Mixer::release_display_frame(DisplayFrame *frame)
934 for (GLuint texnum : frame->temp_textures) {
935 resource_pool->release_2d_texture(texnum);
937 frame->temp_textures.clear();
938 frame->ready_fence.reset();
939 frame->input_frames.clear();
944 mixer_thread = thread(&Mixer::thread_func, this);
945 audio_thread = thread(&Mixer::audio_thread_func, this);
951 audio_task_queue_changed.notify_one();
956 void Mixer::transition_clicked(int transition_num)
958 theme->transition_clicked(transition_num, pts());
961 void Mixer::channel_clicked(int preview_num)
963 theme->channel_clicked(preview_num);
966 void Mixer::start_mode_scanning(unsigned card_index)
968 assert(card_index < num_cards);
969 if (is_mode_scanning[card_index]) {
972 is_mode_scanning[card_index] = true;
973 mode_scanlist[card_index].clear();
974 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
975 mode_scanlist[card_index].push_back(mode.first);
977 assert(!mode_scanlist[card_index].empty());
978 mode_scanlist_index[card_index] = 0;
979 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
980 last_mode_scan_change[card_index] = steady_clock::now();
983 Mixer::OutputChannel::~OutputChannel()
985 if (has_current_frame) {
986 parent->release_display_frame(¤t_frame);
988 if (has_ready_frame) {
989 parent->release_display_frame(&ready_frame);
993 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
995 // Store this frame for display. Remove the ready frame if any
996 // (it was seemingly never used).
998 unique_lock<mutex> lock(frame_mutex);
999 if (has_ready_frame) {
1000 parent->release_display_frame(&ready_frame);
1002 ready_frame = frame;
1003 has_ready_frame = true;
1006 if (new_frame_ready_callback) {
1007 new_frame_ready_callback();
1010 // Reduce the number of callbacks by filtering duplicates. The reason
1011 // why we bother doing this is that Qt seemingly can get into a state
1012 // where its builds up an essentially unbounded queue of signals,
1013 // consuming more and more memory, and there's no good way of collapsing
1014 // user-defined signals or limiting the length of the queue.
1015 if (transition_names_updated_callback) {
1016 vector<string> transition_names = global_mixer->get_transition_names();
1017 bool changed = false;
1018 if (transition_names.size() != last_transition_names.size()) {
1021 for (unsigned i = 0; i < transition_names.size(); ++i) {
1022 if (transition_names[i] != last_transition_names[i]) {
1029 transition_names_updated_callback(transition_names);
1030 last_transition_names = transition_names;
1033 if (name_updated_callback) {
1034 string name = global_mixer->get_channel_name(channel);
1035 if (name != last_name) {
1036 name_updated_callback(name);
1040 if (color_updated_callback) {
1041 string color = global_mixer->get_channel_color(channel);
1042 if (color != last_color) {
1043 color_updated_callback(color);
1049 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1051 unique_lock<mutex> lock(frame_mutex);
1052 if (!has_current_frame && !has_ready_frame) {
1056 if (has_current_frame && has_ready_frame) {
1057 // We have a new ready frame. Toss the current one.
1058 parent->release_display_frame(¤t_frame);
1059 has_current_frame = false;
1061 if (has_ready_frame) {
1062 assert(!has_current_frame);
1063 current_frame = ready_frame;
1064 ready_frame.ready_fence.reset(); // Drop the refcount.
1065 ready_frame.input_frames.clear(); // Drop the refcounts.
1066 has_current_frame = true;
1067 has_ready_frame = false;
1070 *frame = current_frame;
1074 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1076 new_frame_ready_callback = callback;
1079 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1081 transition_names_updated_callback = callback;
1084 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1086 name_updated_callback = callback;
1089 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1091 color_updated_callback = callback;
1094 mutex RefCountedGLsync::fence_lock;