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"
38 #include "decklink_output.h"
40 #include "disk_space_estimator.h"
42 #include "input_mapping.h"
43 #include "pbo_frame_allocator.h"
44 #include "ref_counted_gl_sync.h"
45 #include "resampling_queue.h"
47 #include "video_encoder.h"
52 using namespace movit;
54 using namespace std::chrono;
55 using namespace std::placeholders;
56 using namespace bmusb;
58 Mixer *global_mixer = nullptr;
59 bool uses_mlock = false;
63 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
66 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) { // :-)
67 input_state->buffered_frames[card_index][frame_num] =
68 input_state->buffered_frames[card_index][frame_num - 1];
70 input_state->buffered_frames[card_index][0] = { frame, field_num };
72 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
73 input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
80 void QueueLengthPolicy::update_policy(int queue_length)
82 if (queue_length < 0) { // Starvation.
83 if (been_at_safe_point_since_last_starvation && safe_queue_length < 5) {
85 fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frames\n",
86 card_index, safe_queue_length);
88 frames_with_at_least_one = 0;
89 been_at_safe_point_since_last_starvation = false;
92 if (queue_length > 0) {
93 if (queue_length >= int(safe_queue_length)) {
94 been_at_safe_point_since_last_starvation = true;
96 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 0) {
98 fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frames\n",
99 card_index, safe_queue_length);
100 frames_with_at_least_one = 0;
103 frames_with_at_least_one = 0;
107 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
109 num_cards(num_cards),
110 mixer_surface(create_surface(format)),
111 h264_encoder_surface(create_surface(format)),
112 decklink_output_surface(create_surface(format)),
113 audio_mixer(num_cards)
115 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
118 // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
119 // will be halved when sampling them, and we need to compensate here.
120 movit_texel_subpixel_precision /= 2.0;
122 resource_pool.reset(new ResourcePool);
123 theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get(), num_cards));
124 for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
125 output_channel[i].parent = this;
126 output_channel[i].channel = i;
129 ImageFormat inout_format;
130 inout_format.color_space = COLORSPACE_sRGB;
131 inout_format.gamma_curve = GAMMA_sRGB;
133 // Display chain; shows the live output produced by the main chain (its RGBA version).
134 display_chain.reset(new EffectChain(global_flags.width, global_flags.height, resource_pool.get()));
136 display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height); // FIXME: GL_UNSIGNED_BYTE is really wrong.
137 display_chain->add_input(display_input);
138 display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
139 display_chain->set_dither_bits(0); // Don't bother.
140 display_chain->finalize();
142 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));
144 // Start listening for clients only once VideoEncoder has written its header, if any.
147 // First try initializing the then PCI devices, then USB, then
148 // fill up with fake cards until we have the desired number of cards.
149 unsigned num_pci_devices = 0;
150 unsigned card_index = 0;
153 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
154 if (decklink_iterator != nullptr) {
155 for ( ; card_index < num_cards; ++card_index) {
157 if (decklink_iterator->Next(&decklink) != S_OK) {
161 DeckLinkCapture *capture = new DeckLinkCapture(decklink, card_index);
162 DeckLinkOutput *output = new DeckLinkOutput(resource_pool.get(), decklink_output_surface, global_flags.width, global_flags.height, card_index);
163 output->set_device(decklink);
164 configure_card(card_index, capture, /*is_fake_capture=*/false, output);
167 decklink_iterator->Release();
168 fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
170 fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
174 unsigned num_usb_devices = BMUSBCapture::num_cards();
175 for (unsigned usb_card_index = 0; usb_card_index < num_usb_devices && card_index < num_cards; ++usb_card_index, ++card_index) {
176 BMUSBCapture *capture = new BMUSBCapture(usb_card_index);
177 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, card_index));
178 configure_card(card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
180 fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
182 unsigned num_fake_cards = 0;
183 for ( ; card_index < num_cards; ++card_index, ++num_fake_cards) {
184 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
185 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
188 if (num_fake_cards > 0) {
189 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
192 BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
193 BMUSBCapture::start_bm_thread();
195 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
196 cards[card_index].queue_length_policy.reset(card_index);
199 chroma_subsampler.reset(new ChromaSubsampler(resource_pool.get()));
201 if (global_flags.enable_alsa_output) {
202 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
204 if (global_flags.output_card != -1) {
205 set_output_card(global_flags.output_card);
211 BMUSBCapture::stop_bm_thread();
213 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
215 unique_lock<mutex> lock(card_mutex);
216 cards[card_index].should_quit = true; // Unblock thread.
217 cards[card_index].new_frames_changed.notify_all();
219 cards[card_index].capture->stop_dequeue_thread();
220 if (cards[card_index].output) {
221 cards[card_index].output->end_output();
222 cards[card_index].output.reset();
226 video_encoder.reset(nullptr);
229 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture, DeckLinkOutput *output)
231 printf("Configuring card %d...\n", card_index);
233 CaptureCard *card = &cards[card_index];
234 if (card->capture != nullptr) {
235 card->capture->stop_dequeue_thread();
237 card->capture.reset(capture);
238 card->is_fake_capture = is_fake_capture;
239 if (card->output.get() != output) {
240 card->output.reset(output);
242 card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
243 if (card->frame_allocator == nullptr) {
244 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, global_flags.width, global_flags.height)); // 8 MB.
246 card->capture->set_video_frame_allocator(card->frame_allocator.get());
247 if (card->surface == nullptr) {
248 card->surface = create_surface_with_same_format(mixer_surface);
250 while (!card->new_frames.empty()) card->new_frames.pop();
251 card->last_timecode = -1;
252 card->capture->configure_card();
254 // NOTE: start_bm_capture() happens in thread_func().
256 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
257 audio_mixer.reset_resampler(device);
258 audio_mixer.set_display_name(device, card->capture->get_description());
259 audio_mixer.trigger_state_changed_callback();
262 void Mixer::set_output_card(int card_index)
264 if (card_index == output_card_index) {
267 unique_lock<mutex> lock(card_mutex);
268 if (output_card_index != -1) {
269 // Switch the old card from output to input.
270 CaptureCard *old_card = &cards[output_card_index];
271 old_card->output->end_output();
273 // Stop the fake card that we put into place.
274 // This needs to _not_ happen under the mutex, to avoid deadlock
275 // (delivering the last frame needs to take the mutex).
276 bmusb::CaptureInterface *fake_capture = old_card->capture.get();
278 fake_capture->stop_dequeue_thread();
280 old_card->capture = move(old_card->parked_capture);
281 old_card->is_fake_capture = false;
282 old_card->capture->start_bm_capture();
284 if (card_index != -1) {
285 CaptureCard *card = &cards[card_index];
286 bmusb::CaptureInterface *capture = card->capture.get();
288 capture->stop_dequeue_thread();
290 card->parked_capture = move(card->capture);
291 bmusb::CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
292 configure_card(card_index, fake_capture, /*is_fake_capture=*/true, card->output.release());
293 card->queue_length_policy.reset(card_index);
294 card->capture->start_bm_capture();
295 card->output->start_output(bmdModeHD720p5994, pts_int); // FIXME
297 output_card_index = card_index;
302 int unwrap_timecode(uint16_t current_wrapped, int last)
304 uint16_t last_wrapped = last & 0xffff;
305 if (current_wrapped > last_wrapped) {
306 return (last & ~0xffff) | current_wrapped;
308 return 0x10000 + ((last & ~0xffff) | current_wrapped);
314 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
315 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
316 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
318 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
319 CaptureCard *card = &cards[card_index];
321 if (is_mode_scanning[card_index]) {
322 if (video_format.has_signal) {
323 // Found a stable signal, so stop scanning.
324 is_mode_scanning[card_index] = false;
326 static constexpr double switch_time_s = 0.1; // Should be enough time for the signal to stabilize.
327 steady_clock::time_point now = steady_clock::now();
328 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
329 if (sec_since_last_switch > switch_time_s) {
330 // It isn't this mode; try the next one.
331 mode_scanlist_index[card_index]++;
332 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
333 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
334 last_mode_scan_change[card_index] = now;
339 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
340 assert(frame_length > 0);
342 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;
343 if (num_samples > OUTPUT_FREQUENCY / 10) {
344 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",
345 card_index, int(audio_frame.len), int(audio_offset),
346 timecode, int(video_frame.len), int(video_offset), video_format.id);
347 if (video_frame.owner) {
348 video_frame.owner->release_frame(video_frame);
350 if (audio_frame.owner) {
351 audio_frame.owner->release_frame(audio_frame);
356 int dropped_frames = 0;
357 if (card->last_timecode != -1) {
358 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
361 // Number of samples per frame if we need to insert silence.
362 // (Could be nonintegral, but resampling will save us then.)
363 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
365 if (dropped_frames > MAX_FPS * 2) {
366 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
367 card_index, card->last_timecode, timecode);
368 audio_mixer.reset_resampler(device);
370 } else if (dropped_frames > 0) {
371 // Insert silence as needed.
372 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
373 card_index, dropped_frames, timecode);
377 success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
381 audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length);
383 // Done with the audio, so release it.
384 if (audio_frame.owner) {
385 audio_frame.owner->release_frame(audio_frame);
388 card->last_timecode = timecode;
390 size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
391 if (video_frame.len - video_offset == 0 ||
392 video_frame.len - video_offset != expected_length) {
393 if (video_frame.len != 0) {
394 printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
395 card_index, video_frame.len - video_offset, expected_length);
397 if (video_frame.owner) {
398 video_frame.owner->release_frame(video_frame);
401 // Still send on the information that we _had_ a frame, even though it's corrupted,
402 // so that pts can go up accordingly.
404 unique_lock<mutex> lock(card_mutex);
405 CaptureCard::NewFrame new_frame;
406 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
407 new_frame.length = frame_length;
408 new_frame.interlaced = false;
409 new_frame.dropped_frames = dropped_frames;
410 card->new_frames.push(move(new_frame));
411 card->new_frames_changed.notify_all();
416 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
418 unsigned num_fields = video_format.interlaced ? 2 : 1;
419 steady_clock::time_point frame_upload_start;
420 bool interlaced_stride = false;
421 if (video_format.interlaced) {
422 // Send the two fields along as separate frames; the other side will need to add
423 // a deinterlacer to actually get this right.
424 assert(video_format.height % 2 == 0);
425 video_format.height /= 2;
426 assert(frame_length % 2 == 0);
429 if (video_format.second_field_start == 1) {
430 interlaced_stride = true;
432 frame_upload_start = steady_clock::now();
434 userdata->last_interlaced = video_format.interlaced;
435 userdata->last_has_signal = video_format.has_signal;
436 userdata->last_is_connected = video_format.is_connected;
437 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
438 userdata->last_frame_rate_den = video_format.frame_rate_den;
439 RefCountedFrame frame(video_frame);
441 // Upload the textures.
442 size_t cbcr_width = video_format.width / 2;
443 size_t cbcr_offset = video_offset / 2;
444 size_t y_offset = video_frame.size / 2 + video_offset / 2;
446 for (unsigned field = 0; field < num_fields; ++field) {
447 // Put the actual texture upload in a lambda that is executed in the main thread.
448 // It is entirely possible to do this in the same thread (and it might even be
449 // faster, depending on the GPU and driver), but it appears to be trickling
450 // driver bugs very easily.
452 // Note that this means we must hold on to the actual frame data in <userdata>
453 // until the upload command is run, but we hold on to <frame> much longer than that
454 // (in fact, all the way until we no longer use the texture in rendering).
455 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, interlaced_stride, userdata]() {
456 unsigned field_start_line;
458 field_start_line = video_format.second_field_start;
460 field_start_line = video_format.extra_lines_top;
463 if (userdata->tex_y[field] == 0 ||
464 userdata->tex_cbcr[field] == 0 ||
465 video_format.width != userdata->last_width[field] ||
466 video_format.height != userdata->last_height[field]) {
467 // We changed resolution since last use of this texture, so we need to create
468 // a new object. Note that this each card has its own PBOFrameAllocator,
469 // we don't need to worry about these flip-flopping between resolutions.
470 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
472 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
474 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
476 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
478 userdata->last_width[field] = video_format.width;
479 userdata->last_height[field] = video_format.height;
482 GLuint pbo = userdata->pbo;
484 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
487 size_t field_y_start = y_offset + video_format.width * field_start_line;
488 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
490 if (global_flags.flush_pbos) {
491 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
493 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
497 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
499 if (interlaced_stride) {
500 glPixelStorei(GL_UNPACK_ROW_LENGTH, cbcr_width * 2);
503 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
506 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
508 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
510 if (interlaced_stride) {
511 glPixelStorei(GL_UNPACK_ROW_LENGTH, video_format.width * 2);
514 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
517 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
519 glBindTexture(GL_TEXTURE_2D, 0);
521 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
523 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
528 // Don't upload the second field as fast as we can; wait until
529 // the field time has approximately passed. (Otherwise, we could
530 // get timing jitter against the other sources, and possibly also
531 // against the video display, although the latter is not as critical.)
532 // This requires our system clock to be reasonably close to the
533 // video clock, but that's not an unreasonable assumption.
534 steady_clock::time_point second_field_start = frame_upload_start +
535 nanoseconds(frame_length * 1000000000 / TIMEBASE);
536 this_thread::sleep_until(second_field_start);
540 unique_lock<mutex> lock(card_mutex);
541 CaptureCard::NewFrame new_frame;
542 new_frame.frame = frame;
543 new_frame.length = frame_length;
544 new_frame.field = field;
545 new_frame.interlaced = video_format.interlaced;
546 new_frame.upload_func = upload_func;
547 new_frame.dropped_frames = dropped_frames;
548 new_frame.received_timestamp = video_frame.received_timestamp; // Ignore the audio timestamp.
549 card->new_frames.push(move(new_frame));
550 card->new_frames_changed.notify_all();
555 void Mixer::bm_hotplug_add(libusb_device *dev)
557 lock_guard<mutex> lock(hotplug_mutex);
558 hotplugged_cards.push_back(dev);
561 void Mixer::bm_hotplug_remove(unsigned card_index)
563 cards[card_index].new_frames_changed.notify_all();
566 void Mixer::thread_func()
568 eglBindAPI(EGL_OPENGL_API);
569 QOpenGLContext *context = create_context(mixer_surface);
570 if (!make_current(context, mixer_surface)) {
575 // Start the actual capture. (We don't want to do it before we're actually ready
576 // to process output frames.)
577 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
578 if (int(card_index) != output_card_index) {
579 cards[card_index].capture->start_bm_capture();
583 steady_clock::time_point start, now;
584 start = steady_clock::now();
587 int stats_dropped_frames = 0;
589 while (!should_quit) {
590 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
591 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
593 bool master_card_is_output;
594 unsigned master_card_index;
595 if (output_card_index != -1) {
596 master_card_is_output = true;
597 master_card_index = output_card_index;
599 master_card_is_output = false;
600 master_card_index = theme->map_signal(master_clock_channel);
601 assert(master_card_index < num_cards);
604 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
605 schedule_audio_resampling_tasks(output_frame_info.dropped_frames, output_frame_info.num_samples, output_frame_info.frame_duration);
606 stats_dropped_frames += output_frame_info.dropped_frames;
608 handle_hotplugged_cards();
610 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
611 if (card_index == master_card_index || !has_new_frame[card_index]) {
614 if (new_frames[card_index].frame->len == 0) {
615 ++new_frames[card_index].dropped_frames;
617 if (new_frames[card_index].dropped_frames > 0) {
618 printf("Card %u dropped %d frames before this\n",
619 card_index, int(new_frames[card_index].dropped_frames));
623 // If the first card is reporting a corrupted or otherwise dropped frame,
624 // just increase the pts (skipping over this frame) and don't try to compute anything new.
625 if (!master_card_is_output && new_frames[master_card_index].frame->len == 0) {
626 ++stats_dropped_frames;
627 pts_int += new_frames[master_card_index].length;
631 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
632 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
635 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
636 assert(new_frame->frame != nullptr);
637 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
640 // The new texture might need uploading before use.
641 if (new_frame->upload_func) {
642 new_frame->upload_func();
643 new_frame->upload_func = nullptr;
647 int64_t frame_duration = output_frame_info.frame_duration;
648 render_one_frame(frame_duration);
650 pts_int += frame_duration;
652 now = steady_clock::now();
653 double elapsed = duration<double>(now - start).count();
654 if (frame % 100 == 0) {
655 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
656 frame, stats_dropped_frames, elapsed, frame / elapsed,
657 1e3 * elapsed / frame);
658 // chain->print_phase_timing();
660 // Check our memory usage, to see if we are close to our mlockall()
661 // limit (if at all set).
663 if (getrusage(RUSAGE_SELF, &used) == -1) {
664 perror("getrusage(RUSAGE_SELF)");
670 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
671 perror("getrlimit(RLIMIT_MEMLOCK)");
675 if (limit.rlim_cur == 0) {
676 printf(", using %ld MB memory (locked)",
677 long(used.ru_maxrss / 1024));
679 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
680 long(used.ru_maxrss / 1024),
681 long(limit.rlim_cur / 1048576),
682 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
685 printf(", using %ld MB memory (not locked)",
686 long(used.ru_maxrss / 1024));
693 if (should_cut.exchange(false)) { // Test and clear.
694 video_encoder->do_cut(frame);
698 // Reset every 100 frames, so that local variations in frame times
699 // (especially for the first few frames, when the shaders are
700 // compiled etc.) don't make it hard to measure for the entire
701 // remaining duration of the program.
702 if (frame == 10000) {
710 resource_pool->clean_context();
713 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
715 if (output_card_index != -1) {
716 // The output card (ie., cards[output_card_index].output) is the master clock,
717 // so no input card (ie., cards[card_index].capture) is.
720 return (card_index == master_card_index);
723 Mixer::OutputFrameInfo Mixer::get_one_frame_from_each_card(unsigned master_card_index, bool master_card_is_output, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS])
725 OutputFrameInfo output_frame_info;
727 unique_lock<mutex> lock(card_mutex, defer_lock);
728 if (master_card_is_output) {
729 // Clocked to the output, so wait for it to be ready for the next frame.
730 cards[master_card_index].output->wait_for_frame(pts_int, &output_frame_info.dropped_frames, &output_frame_info.frame_duration);
733 // Wait for the master card to have a new frame.
734 // TODO: Add a timeout.
736 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(); });
739 if (master_card_is_output) {
740 handle_hotplugged_cards();
741 } else if (cards[master_card_index].new_frames.empty()) {
742 // We were woken up, but not due to a new frame. Deal with it
744 assert(cards[master_card_index].capture->get_disconnected());
745 handle_hotplugged_cards();
749 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
750 CaptureCard *card = &cards[card_index];
751 if (card->new_frames.empty()) {
752 assert(!input_card_is_master_clock(card_index, master_card_index));
753 card->queue_length_policy.update_policy(-1);
756 new_frames[card_index] = move(card->new_frames.front());
757 has_new_frame[card_index] = true;
758 card->new_frames.pop();
759 card->new_frames_changed.notify_all();
761 if (input_card_is_master_clock(card_index, master_card_index)) {
762 // We don't use the queue length policy for the master card,
763 // but we will if it stops being the master. Thus, clear out
764 // the policy in case we switch in the future.
765 card->queue_length_policy.reset(card_index);
767 // If we have excess frames compared to the policy for this card,
768 // drop frames from the head.
769 card->queue_length_policy.update_policy(card->new_frames.size());
770 while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
771 card->new_frames.pop();
776 if (!master_card_is_output) {
777 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
778 output_frame_info.frame_duration = new_frames[master_card_index].length;
781 // This might get off by a fractional sample when changing master card
782 // between ones with different frame rates, but that's fine.
783 int num_samples_times_timebase = OUTPUT_FREQUENCY * output_frame_info.frame_duration + fractional_samples;
784 output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
785 fractional_samples = num_samples_times_timebase % TIMEBASE;
786 assert(output_frame_info.num_samples >= 0);
788 return output_frame_info;
791 void Mixer::handle_hotplugged_cards()
793 // Check for cards that have been disconnected since last frame.
794 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
795 CaptureCard *card = &cards[card_index];
796 if (card->capture->get_disconnected()) {
797 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
798 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
799 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
800 card->queue_length_policy.reset(card_index);
801 card->capture->start_bm_capture();
805 // Check for cards that have been connected since last frame.
806 vector<libusb_device *> hotplugged_cards_copy;
808 lock_guard<mutex> lock(hotplug_mutex);
809 swap(hotplugged_cards, hotplugged_cards_copy);
811 for (libusb_device *new_dev : hotplugged_cards_copy) {
812 // Look for a fake capture card where we can stick this in.
813 int free_card_index = -1;
814 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
815 if (cards[card_index].is_fake_capture) {
816 free_card_index = card_index;
821 if (free_card_index == -1) {
822 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
823 libusb_unref_device(new_dev);
825 // BMUSBCapture takes ownership.
826 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
827 CaptureCard *card = &cards[free_card_index];
828 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
829 configure_card(free_card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
830 card->queue_length_policy.reset(free_card_index);
831 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
832 capture->start_bm_capture();
838 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame)
840 // Resample the audio as needed, including from previously dropped frames.
841 assert(num_cards > 0);
842 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
843 const bool dropped_frame = (frame_num != dropped_frames);
845 // Signal to the audio thread to process this frame.
846 // Note that if the frame is a dropped frame, we signal that
847 // we don't want to use this frame as base for adjusting
848 // the resampler rate. The reason for this is that the timing
849 // of these frames is often way too late; they typically don't
850 // “arrive” before we synthesize them. Thus, we could end up
851 // in a situation where we have inserted e.g. five audio frames
852 // into the queue before we then start pulling five of them
853 // back out. This makes ResamplingQueue overestimate the delay,
854 // causing undue resampler changes. (We _do_ use the last,
855 // non-dropped frame; perhaps we should just discard that as well,
856 // since dropped frames are expected to be rare, and it might be
857 // better to just wait until we have a slightly more normal situation).
858 unique_lock<mutex> lock(audio_mutex);
859 bool adjust_rate = !dropped_frame;
860 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate});
861 audio_task_queue_changed.notify_one();
864 // For dropped frames, increase the pts. Note that if the format changed
865 // in the meantime, we have no way of detecting that; we just have to
866 // assume the frame length is always the same.
867 pts_int += length_per_frame;
872 void Mixer::render_one_frame(int64_t duration)
874 // Get the main chain from the theme, and set its state immediately.
875 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
876 EffectChain *chain = theme_main_chain.chain;
877 theme_main_chain.setup_chain();
878 //theme_main_chain.chain->enable_phase_timing(true);
880 GLuint y_tex, cbcr_tex;
881 bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
884 // Render main chain.
885 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, global_flags.width, global_flags.height);
886 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, global_flags.width, global_flags.height); // Saves texture bandwidth, although dithering gets messed up.
887 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
889 chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
890 resource_pool->release_fbo(fbo);
892 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
893 if (output_card_index != -1) {
894 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, theme_main_chain.input_frames, pts_int, duration);
896 resource_pool->release_2d_texture(cbcr_full_tex);
898 // Set the right state for rgba_tex.
899 glBindFramebuffer(GL_FRAMEBUFFER, 0);
900 glBindTexture(GL_TEXTURE_2D, rgba_tex);
901 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
902 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
903 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
905 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
906 RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
908 // The live frame just shows the RGBA texture we just rendered.
909 // It owns rgba_tex now.
910 DisplayFrame live_frame;
911 live_frame.chain = display_chain.get();
912 live_frame.setup_chain = [this, rgba_tex]{
913 display_input->set_texture_num(rgba_tex);
915 live_frame.ready_fence = fence;
916 live_frame.input_frames = {};
917 live_frame.temp_textures = { rgba_tex };
918 output_channel[OUTPUT_LIVE].output_frame(live_frame);
920 // Set up preview and any additional channels.
921 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
922 DisplayFrame display_frame;
923 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state); // FIXME: dimensions
924 display_frame.chain = chain.chain;
925 display_frame.setup_chain = chain.setup_chain;
926 display_frame.ready_fence = fence;
927 display_frame.input_frames = chain.input_frames;
928 display_frame.temp_textures = {};
929 output_channel[i].output_frame(display_frame);
933 void Mixer::audio_thread_func()
935 while (!should_quit) {
939 unique_lock<mutex> lock(audio_mutex);
940 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
944 task = audio_task_queue.front();
945 audio_task_queue.pop();
948 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
949 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
950 vector<float> samples_out = audio_mixer.get_output(
951 double(task.pts_int) / TIMEBASE,
953 rate_adjustment_policy);
955 // Send the samples to the sound card, then add them to the output.
957 alsa->write(samples_out);
959 if (output_card_index != -1) {
960 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
961 cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
963 video_encoder->add_audio(task.pts_int, move(samples_out));
967 void Mixer::release_display_frame(DisplayFrame *frame)
969 for (GLuint texnum : frame->temp_textures) {
970 resource_pool->release_2d_texture(texnum);
972 frame->temp_textures.clear();
973 frame->ready_fence.reset();
974 frame->input_frames.clear();
979 mixer_thread = thread(&Mixer::thread_func, this);
980 audio_thread = thread(&Mixer::audio_thread_func, this);
986 audio_task_queue_changed.notify_one();
991 void Mixer::transition_clicked(int transition_num)
993 theme->transition_clicked(transition_num, pts());
996 void Mixer::channel_clicked(int preview_num)
998 theme->channel_clicked(preview_num);
1001 void Mixer::start_mode_scanning(unsigned card_index)
1003 assert(card_index < num_cards);
1004 if (is_mode_scanning[card_index]) {
1007 is_mode_scanning[card_index] = true;
1008 mode_scanlist[card_index].clear();
1009 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1010 mode_scanlist[card_index].push_back(mode.first);
1012 assert(!mode_scanlist[card_index].empty());
1013 mode_scanlist_index[card_index] = 0;
1014 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1015 last_mode_scan_change[card_index] = steady_clock::now();
1018 Mixer::OutputChannel::~OutputChannel()
1020 if (has_current_frame) {
1021 parent->release_display_frame(¤t_frame);
1023 if (has_ready_frame) {
1024 parent->release_display_frame(&ready_frame);
1028 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1030 // Store this frame for display. Remove the ready frame if any
1031 // (it was seemingly never used).
1033 unique_lock<mutex> lock(frame_mutex);
1034 if (has_ready_frame) {
1035 parent->release_display_frame(&ready_frame);
1037 ready_frame = frame;
1038 has_ready_frame = true;
1041 if (new_frame_ready_callback) {
1042 new_frame_ready_callback();
1045 // Reduce the number of callbacks by filtering duplicates. The reason
1046 // why we bother doing this is that Qt seemingly can get into a state
1047 // where its builds up an essentially unbounded queue of signals,
1048 // consuming more and more memory, and there's no good way of collapsing
1049 // user-defined signals or limiting the length of the queue.
1050 if (transition_names_updated_callback) {
1051 vector<string> transition_names = global_mixer->get_transition_names();
1052 bool changed = false;
1053 if (transition_names.size() != last_transition_names.size()) {
1056 for (unsigned i = 0; i < transition_names.size(); ++i) {
1057 if (transition_names[i] != last_transition_names[i]) {
1064 transition_names_updated_callback(transition_names);
1065 last_transition_names = transition_names;
1068 if (name_updated_callback) {
1069 string name = global_mixer->get_channel_name(channel);
1070 if (name != last_name) {
1071 name_updated_callback(name);
1075 if (color_updated_callback) {
1076 string color = global_mixer->get_channel_color(channel);
1077 if (color != last_color) {
1078 color_updated_callback(color);
1084 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1086 unique_lock<mutex> lock(frame_mutex);
1087 if (!has_current_frame && !has_ready_frame) {
1091 if (has_current_frame && has_ready_frame) {
1092 // We have a new ready frame. Toss the current one.
1093 parent->release_display_frame(¤t_frame);
1094 has_current_frame = false;
1096 if (has_ready_frame) {
1097 assert(!has_current_frame);
1098 current_frame = ready_frame;
1099 ready_frame.ready_fence.reset(); // Drop the refcount.
1100 ready_frame.input_frames.clear(); // Drop the refcounts.
1101 has_current_frame = true;
1102 has_ready_frame = false;
1105 *frame = current_frame;
1109 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1111 new_frame_ready_callback = callback;
1114 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1116 transition_names_updated_callback = callback;
1119 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1121 name_updated_callback = callback;
1124 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1126 color_updated_callback = callback;
1129 mutex RefCountedGLsync::fence_lock;