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>
16 #include <sys/resource.h>
19 #include <condition_variable>
30 #include "DeckLinkAPI.h"
32 #include "alsa_output.h"
33 #include "bmusb/bmusb.h"
34 #include "bmusb/fake_capture.h"
35 #include "chroma_subsampler.h"
37 #include "decklink_capture.h"
39 #include "disk_space_estimator.h"
41 #include "input_mapping.h"
42 #include "pbo_frame_allocator.h"
43 #include "ref_counted_gl_sync.h"
44 #include "resampling_queue.h"
46 #include "video_encoder.h"
51 using namespace movit;
53 using namespace std::chrono;
54 using namespace std::placeholders;
55 using namespace bmusb;
57 Mixer *global_mixer = nullptr;
58 bool uses_mlock = false;
62 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
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];
69 input_state->buffered_frames[card_index][0] = { frame, field_num };
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 };
79 void QueueLengthPolicy::update_policy(int queue_length)
81 if (queue_length < 0) { // Starvation.
82 if (been_at_safe_point_since_last_starvation && safe_queue_length < 5) {
84 fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frames\n",
85 card_index, safe_queue_length);
87 frames_with_at_least_one = 0;
88 been_at_safe_point_since_last_starvation = false;
91 if (queue_length > 0) {
92 if (queue_length >= int(safe_queue_length)) {
93 been_at_safe_point_since_last_starvation = true;
95 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 0) {
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;
102 frames_with_at_least_one = 0;
106 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
108 num_cards(num_cards),
109 mixer_surface(create_surface(format)),
110 h264_encoder_surface(create_surface(format)),
111 audio_mixer(num_cards)
113 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
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;
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;
127 ImageFormat inout_format;
128 inout_format.color_space = COLORSPACE_sRGB;
129 inout_format.gamma_curve = GAMMA_sRGB;
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()));
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();
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));
142 // Start listening for clients only once VideoEncoder has written its header, if any.
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;
151 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
152 if (decklink_iterator != nullptr) {
153 for ( ; card_index < num_cards; ++card_index) {
155 if (decklink_iterator->Next(&decklink) != S_OK) {
159 configure_card(card_index, new DeckLinkCapture(decklink, card_index), /*is_fake_capture=*/false);
162 decklink_iterator->Release();
163 fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
165 fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
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);
174 fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
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);
182 if (num_fake_cards > 0) {
183 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
186 BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
187 BMUSBCapture::start_bm_thread();
189 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
190 cards[card_index].queue_length_policy.reset(card_index);
193 chroma_subsampler.reset(new ChromaSubsampler(resource_pool.get()));
195 if (global_flags.enable_alsa_output) {
196 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
202 BMUSBCapture::stop_bm_thread();
204 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
206 unique_lock<mutex> lock(card_mutex);
207 cards[card_index].should_quit = true; // Unblock thread.
208 cards[card_index].new_frames_changed.notify_all();
210 cards[card_index].capture->stop_dequeue_thread();
213 video_encoder.reset(nullptr);
216 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture)
218 printf("Configuring card %d...\n", card_index);
220 CaptureCard *card = &cards[card_index];
221 if (card->capture != nullptr) {
222 card->capture->stop_dequeue_thread();
223 delete card->capture;
225 card->capture = capture;
226 card->is_fake_capture = is_fake_capture;
227 card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
228 if (card->frame_allocator == nullptr) {
229 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, global_flags.width, global_flags.height)); // 8 MB.
231 card->capture->set_video_frame_allocator(card->frame_allocator.get());
232 if (card->surface == nullptr) {
233 card->surface = create_surface_with_same_format(mixer_surface);
235 while (!card->new_frames.empty()) card->new_frames.pop();
236 card->last_timecode = -1;
237 card->capture->configure_card();
239 // NOTE: start_bm_capture() happens in thread_func().
241 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
242 audio_mixer.reset_resampler(device);
243 audio_mixer.set_display_name(device, card->capture->get_description());
244 audio_mixer.trigger_state_changed_callback();
250 int unwrap_timecode(uint16_t current_wrapped, int last)
252 uint16_t last_wrapped = last & 0xffff;
253 if (current_wrapped > last_wrapped) {
254 return (last & ~0xffff) | current_wrapped;
256 return 0x10000 + ((last & ~0xffff) | current_wrapped);
262 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
263 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
264 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
266 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
267 CaptureCard *card = &cards[card_index];
269 if (is_mode_scanning[card_index]) {
270 if (video_format.has_signal) {
271 // Found a stable signal, so stop scanning.
272 is_mode_scanning[card_index] = false;
274 static constexpr double switch_time_s = 0.1; // Should be enough time for the signal to stabilize.
275 steady_clock::time_point now = steady_clock::now();
276 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
277 if (sec_since_last_switch > switch_time_s) {
278 // It isn't this mode; try the next one.
279 mode_scanlist_index[card_index]++;
280 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
281 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
282 last_mode_scan_change[card_index] = now;
287 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
288 assert(frame_length > 0);
290 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;
291 if (num_samples > OUTPUT_FREQUENCY / 10) {
292 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",
293 card_index, int(audio_frame.len), int(audio_offset),
294 timecode, int(video_frame.len), int(video_offset), video_format.id);
295 if (video_frame.owner) {
296 video_frame.owner->release_frame(video_frame);
298 if (audio_frame.owner) {
299 audio_frame.owner->release_frame(audio_frame);
304 int dropped_frames = 0;
305 if (card->last_timecode != -1) {
306 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
309 // Number of samples per frame if we need to insert silence.
310 // (Could be nonintegral, but resampling will save us then.)
311 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
313 if (dropped_frames > MAX_FPS * 2) {
314 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
315 card_index, card->last_timecode, timecode);
316 audio_mixer.reset_resampler(device);
318 } else if (dropped_frames > 0) {
319 // Insert silence as needed.
320 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
321 card_index, dropped_frames, timecode);
325 success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
329 audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length);
331 // Done with the audio, so release it.
332 if (audio_frame.owner) {
333 audio_frame.owner->release_frame(audio_frame);
336 card->last_timecode = timecode;
338 size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
339 if (video_frame.len - video_offset == 0 ||
340 video_frame.len - video_offset != expected_length) {
341 if (video_frame.len != 0) {
342 printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
343 card_index, video_frame.len - video_offset, expected_length);
345 if (video_frame.owner) {
346 video_frame.owner->release_frame(video_frame);
349 // Still send on the information that we _had_ a frame, even though it's corrupted,
350 // so that pts can go up accordingly.
352 unique_lock<mutex> lock(card_mutex);
353 CaptureCard::NewFrame new_frame;
354 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
355 new_frame.length = frame_length;
356 new_frame.interlaced = false;
357 new_frame.dropped_frames = dropped_frames;
358 card->new_frames.push(move(new_frame));
359 card->new_frames_changed.notify_all();
364 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
366 unsigned num_fields = video_format.interlaced ? 2 : 1;
367 steady_clock::time_point frame_upload_start;
368 bool interlaced_stride = false;
369 if (video_format.interlaced) {
370 // Send the two fields along as separate frames; the other side will need to add
371 // a deinterlacer to actually get this right.
372 assert(video_format.height % 2 == 0);
373 video_format.height /= 2;
374 assert(frame_length % 2 == 0);
377 if (video_format.second_field_start == 1) {
378 interlaced_stride = true;
380 frame_upload_start = steady_clock::now();
382 userdata->last_interlaced = video_format.interlaced;
383 userdata->last_has_signal = video_format.has_signal;
384 userdata->last_is_connected = video_format.is_connected;
385 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
386 userdata->last_frame_rate_den = video_format.frame_rate_den;
387 RefCountedFrame frame(video_frame);
389 // Upload the textures.
390 size_t cbcr_width = video_format.width / 2;
391 size_t cbcr_offset = video_offset / 2;
392 size_t y_offset = video_frame.size / 2 + video_offset / 2;
394 for (unsigned field = 0; field < num_fields; ++field) {
395 // Put the actual texture upload in a lambda that is executed in the main thread.
396 // It is entirely possible to do this in the same thread (and it might even be
397 // faster, depending on the GPU and driver), but it appears to be trickling
398 // driver bugs very easily.
400 // Note that this means we must hold on to the actual frame data in <userdata>
401 // until the upload command is run, but we hold on to <frame> much longer than that
402 // (in fact, all the way until we no longer use the texture in rendering).
403 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, interlaced_stride, userdata]() {
404 unsigned field_start_line;
406 field_start_line = video_format.second_field_start;
408 field_start_line = video_format.extra_lines_top;
411 if (userdata->tex_y[field] == 0 ||
412 userdata->tex_cbcr[field] == 0 ||
413 video_format.width != userdata->last_width[field] ||
414 video_format.height != userdata->last_height[field]) {
415 // We changed resolution since last use of this texture, so we need to create
416 // a new object. Note that this each card has its own PBOFrameAllocator,
417 // we don't need to worry about these flip-flopping between resolutions.
418 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
420 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
422 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
424 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
426 userdata->last_width[field] = video_format.width;
427 userdata->last_height[field] = video_format.height;
430 GLuint pbo = userdata->pbo;
432 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
435 size_t field_y_start = y_offset + video_format.width * field_start_line;
436 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
438 if (global_flags.flush_pbos) {
439 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
441 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
445 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
447 if (interlaced_stride) {
448 glPixelStorei(GL_UNPACK_ROW_LENGTH, cbcr_width * 2);
451 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
454 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
456 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
458 if (interlaced_stride) {
459 glPixelStorei(GL_UNPACK_ROW_LENGTH, video_format.width * 2);
462 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
465 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
467 glBindTexture(GL_TEXTURE_2D, 0);
469 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
471 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
476 // Don't upload the second field as fast as we can; wait until
477 // the field time has approximately passed. (Otherwise, we could
478 // get timing jitter against the other sources, and possibly also
479 // against the video display, although the latter is not as critical.)
480 // This requires our system clock to be reasonably close to the
481 // video clock, but that's not an unreasonable assumption.
482 steady_clock::time_point second_field_start = frame_upload_start +
483 nanoseconds(frame_length * 1000000000 / TIMEBASE);
484 this_thread::sleep_until(second_field_start);
488 unique_lock<mutex> lock(card_mutex);
489 CaptureCard::NewFrame new_frame;
490 new_frame.frame = frame;
491 new_frame.length = frame_length;
492 new_frame.field = field;
493 new_frame.interlaced = video_format.interlaced;
494 new_frame.upload_func = upload_func;
495 new_frame.dropped_frames = dropped_frames;
496 new_frame.received_timestamp = video_frame.received_timestamp; // Ignore the audio timestamp.
497 card->new_frames.push(move(new_frame));
498 card->new_frames_changed.notify_all();
503 void Mixer::bm_hotplug_add(libusb_device *dev)
505 lock_guard<mutex> lock(hotplug_mutex);
506 hotplugged_cards.push_back(dev);
509 void Mixer::bm_hotplug_remove(unsigned card_index)
511 cards[card_index].new_frames_changed.notify_all();
514 void Mixer::thread_func()
516 eglBindAPI(EGL_OPENGL_API);
517 QOpenGLContext *context = create_context(mixer_surface);
518 if (!make_current(context, mixer_surface)) {
523 // Start the actual capture. (We don't want to do it before we're actually ready
524 // to process output frames.)
525 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
526 cards[card_index].capture->start_bm_capture();
529 steady_clock::time_point start, now;
530 start = steady_clock::now();
533 int stats_dropped_frames = 0;
535 while (!should_quit) {
536 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
537 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
539 unsigned master_card_index = theme->map_signal(master_clock_channel);
540 assert(master_card_index < num_cards);
542 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, new_frames, has_new_frame);
543 schedule_audio_resampling_tasks(output_frame_info.dropped_frames, output_frame_info.num_samples, output_frame_info.frame_duration);
544 stats_dropped_frames += output_frame_info.dropped_frames;
546 handle_hotplugged_cards();
548 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
549 if (card_index == master_card_index || !has_new_frame[card_index]) {
552 if (new_frames[card_index].frame->len == 0) {
553 ++new_frames[card_index].dropped_frames;
555 if (new_frames[card_index].dropped_frames > 0) {
556 printf("Card %u dropped %d frames before this\n",
557 card_index, int(new_frames[card_index].dropped_frames));
561 // If the first card is reporting a corrupted or otherwise dropped frame,
562 // just increase the pts (skipping over this frame) and don't try to compute anything new.
563 if (new_frames[master_card_index].frame->len == 0) {
564 ++stats_dropped_frames;
565 pts_int += new_frames[master_card_index].length;
569 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
570 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
573 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
574 assert(new_frame->frame != nullptr);
575 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
578 // The new texture might need uploading before use.
579 if (new_frame->upload_func) {
580 new_frame->upload_func();
581 new_frame->upload_func = nullptr;
585 int64_t frame_duration = output_frame_info.frame_duration;
586 render_one_frame(frame_duration);
588 pts_int += frame_duration;
590 now = steady_clock::now();
591 double elapsed = duration<double>(now - start).count();
592 if (frame % 100 == 0) {
593 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
594 frame, stats_dropped_frames, elapsed, frame / elapsed,
595 1e3 * elapsed / frame);
596 // chain->print_phase_timing();
598 // Check our memory usage, to see if we are close to our mlockall()
599 // limit (if at all set).
601 if (getrusage(RUSAGE_SELF, &used) == -1) {
602 perror("getrusage(RUSAGE_SELF)");
608 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
609 perror("getrlimit(RLIMIT_MEMLOCK)");
613 if (limit.rlim_cur == 0) {
614 printf(", using %ld MB memory (locked)",
615 long(used.ru_maxrss / 1024));
617 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
618 long(used.ru_maxrss / 1024),
619 long(limit.rlim_cur / 1048576),
620 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
623 printf(", using %ld MB memory (not locked)",
624 long(used.ru_maxrss / 1024));
631 if (should_cut.exchange(false)) { // Test and clear.
632 video_encoder->do_cut(frame);
636 // Reset every 100 frames, so that local variations in frame times
637 // (especially for the first few frames, when the shaders are
638 // compiled etc.) don't make it hard to measure for the entire
639 // remaining duration of the program.
640 if (frame == 10000) {
648 resource_pool->clean_context();
651 Mixer::OutputFrameInfo Mixer::get_one_frame_from_each_card(unsigned master_card_index, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS])
653 OutputFrameInfo output_frame_info;
656 // The first card is the master timer, so wait for it to have a new frame.
657 // TODO: Add a timeout.
658 unique_lock<mutex> lock(card_mutex);
659 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 if (cards[master_card_index].new_frames.empty()) {
662 // We were woken up, but not due to a new frame. Deal with it
664 assert(cards[master_card_index].capture->get_disconnected());
665 handle_hotplugged_cards();
669 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
670 CaptureCard *card = &cards[card_index];
671 if (card->new_frames.empty()) {
672 assert(card_index != master_card_index);
673 card->queue_length_policy.update_policy(-1);
676 new_frames[card_index] = move(card->new_frames.front());
677 has_new_frame[card_index] = true;
678 card->new_frames.pop();
679 card->new_frames_changed.notify_all();
681 if (card_index == master_card_index) {
682 // We don't use the queue length policy for the master card,
683 // but we will if it stops being the master. Thus, clear out
684 // the policy in case we switch in the future.
685 card->queue_length_policy.reset(card_index);
687 // If we have excess frames compared to the policy for this card,
688 // drop frames from the head.
689 card->queue_length_policy.update_policy(card->new_frames.size());
690 while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
691 card->new_frames.pop();
696 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
697 output_frame_info.frame_duration = new_frames[master_card_index].length;
699 // This might get off by a fractional sample when changing master card
700 // between ones with different frame rates, but that's fine.
701 int num_samples_times_timebase = OUTPUT_FREQUENCY * output_frame_info.frame_duration + fractional_samples;
702 output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
703 fractional_samples = num_samples_times_timebase % TIMEBASE;
704 assert(output_frame_info.num_samples >= 0);
706 return output_frame_info;
709 void Mixer::handle_hotplugged_cards()
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();
723 // Check for cards that have been connected since last frame.
724 vector<libusb_device *> hotplugged_cards_copy;
726 lock_guard<mutex> lock(hotplug_mutex);
727 swap(hotplugged_cards, hotplugged_cards_copy);
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);
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);
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();
756 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame)
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);
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();
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;
790 void Mixer::render_one_frame(int64_t duration)
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);
798 GLuint y_tex, cbcr_tex;
799 bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
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);
807 chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
808 resource_pool->release_fbo(fbo);
810 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
811 resource_pool->release_2d_texture(cbcr_full_tex);
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);
820 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
821 RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
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);
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);
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);
848 void Mixer::audio_thread_func()
850 while (!should_quit) {
854 unique_lock<mutex> lock(audio_mutex);
855 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
859 task = audio_task_queue.front();
860 audio_task_queue.pop();
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,
868 rate_adjustment_policy);
870 // Send the samples to the sound card, then add them to the output.
872 alsa->write(samples_out);
874 decklink_output->send_audio(task.pts_int, samples_out);
875 video_encoder->add_audio(task.pts_int, move(samples_out));
879 void Mixer::release_display_frame(DisplayFrame *frame)
881 for (GLuint texnum : frame->temp_textures) {
882 resource_pool->release_2d_texture(texnum);
884 frame->temp_textures.clear();
885 frame->ready_fence.reset();
886 frame->input_frames.clear();
891 mixer_thread = thread(&Mixer::thread_func, this);
892 audio_thread = thread(&Mixer::audio_thread_func, this);
898 audio_task_queue_changed.notify_one();
903 void Mixer::transition_clicked(int transition_num)
905 theme->transition_clicked(transition_num, pts());
908 void Mixer::channel_clicked(int preview_num)
910 theme->channel_clicked(preview_num);
913 void Mixer::start_mode_scanning(unsigned card_index)
915 assert(card_index < num_cards);
916 if (is_mode_scanning[card_index]) {
919 is_mode_scanning[card_index] = true;
920 mode_scanlist[card_index].clear();
921 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
922 mode_scanlist[card_index].push_back(mode.first);
924 assert(!mode_scanlist[card_index].empty());
925 mode_scanlist_index[card_index] = 0;
926 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
927 last_mode_scan_change[card_index] = steady_clock::now();
930 Mixer::OutputChannel::~OutputChannel()
932 if (has_current_frame) {
933 parent->release_display_frame(¤t_frame);
935 if (has_ready_frame) {
936 parent->release_display_frame(&ready_frame);
940 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
942 // Store this frame for display. Remove the ready frame if any
943 // (it was seemingly never used).
945 unique_lock<mutex> lock(frame_mutex);
946 if (has_ready_frame) {
947 parent->release_display_frame(&ready_frame);
950 has_ready_frame = true;
953 if (new_frame_ready_callback) {
954 new_frame_ready_callback();
957 // Reduce the number of callbacks by filtering duplicates. The reason
958 // why we bother doing this is that Qt seemingly can get into a state
959 // where its builds up an essentially unbounded queue of signals,
960 // consuming more and more memory, and there's no good way of collapsing
961 // user-defined signals or limiting the length of the queue.
962 if (transition_names_updated_callback) {
963 vector<string> transition_names = global_mixer->get_transition_names();
964 bool changed = false;
965 if (transition_names.size() != last_transition_names.size()) {
968 for (unsigned i = 0; i < transition_names.size(); ++i) {
969 if (transition_names[i] != last_transition_names[i]) {
976 transition_names_updated_callback(transition_names);
977 last_transition_names = transition_names;
980 if (name_updated_callback) {
981 string name = global_mixer->get_channel_name(channel);
982 if (name != last_name) {
983 name_updated_callback(name);
987 if (color_updated_callback) {
988 string color = global_mixer->get_channel_color(channel);
989 if (color != last_color) {
990 color_updated_callback(color);
996 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
998 unique_lock<mutex> lock(frame_mutex);
999 if (!has_current_frame && !has_ready_frame) {
1003 if (has_current_frame && has_ready_frame) {
1004 // We have a new ready frame. Toss the current one.
1005 parent->release_display_frame(¤t_frame);
1006 has_current_frame = false;
1008 if (has_ready_frame) {
1009 assert(!has_current_frame);
1010 current_frame = ready_frame;
1011 ready_frame.ready_fence.reset(); // Drop the refcount.
1012 ready_frame.input_frames.clear(); // Drop the refcounts.
1013 has_current_frame = true;
1014 has_ready_frame = false;
1017 *frame = current_frame;
1021 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1023 new_frame_ready_callback = callback;
1026 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1028 transition_names_updated_callback = callback;
1031 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1033 name_updated_callback = callback;
1036 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1038 color_updated_callback = callback;
1041 mutex RefCountedGLsync::fence_lock;