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>
17 #include <sys/resource.h>
20 #include <condition_variable>
31 #include "DeckLinkAPI.h"
33 #include "alsa_output.h"
34 #include "bmusb/bmusb.h"
35 #include "bmusb/fake_capture.h"
36 #include "chroma_subsampler.h"
38 #include "decklink_capture.h"
39 #include "decklink_output.h"
41 #include "disk_space_estimator.h"
43 #include "input_mapping.h"
44 #include "pbo_frame_allocator.h"
45 #include "ref_counted_gl_sync.h"
46 #include "resampling_queue.h"
48 #include "timecode_renderer.h"
49 #include "video_encoder.h"
54 using namespace movit;
56 using namespace std::chrono;
57 using namespace std::placeholders;
58 using namespace bmusb;
60 Mixer *global_mixer = nullptr;
61 bool uses_mlock = false;
65 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
68 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) { // :-)
69 input_state->buffered_frames[card_index][frame_num] =
70 input_state->buffered_frames[card_index][frame_num - 1];
72 input_state->buffered_frames[card_index][0] = { frame, field_num };
74 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
75 input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
80 void ensure_texture_resolution(PBOFrameAllocator::Userdata *userdata, unsigned field, unsigned width, unsigned height)
82 if (userdata->tex_y[field] == 0 ||
83 userdata->tex_cbcr[field] == 0 ||
84 width != userdata->last_width[field] ||
85 height != userdata->last_height[field]) {
86 size_t cbcr_width = width / 2;
88 // We changed resolution since last use of this texture, so we need to create
89 // a new object. Note that this each card has its own PBOFrameAllocator,
90 // we don't need to worry about these flip-flopping between resolutions.
91 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
93 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
95 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
97 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
99 userdata->last_width[field] = width;
100 userdata->last_height[field] = height;
104 void upload_texture(GLuint tex, GLuint width, GLuint height, GLuint stride, bool interlaced_stride, GLenum format, GLintptr offset)
106 if (interlaced_stride) {
109 if (global_flags.flush_pbos) {
110 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, offset, stride * height);
114 glBindTexture(GL_TEXTURE_2D, tex);
116 if (interlaced_stride) {
117 glPixelStorei(GL_UNPACK_ROW_LENGTH, width * 2);
120 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
124 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(offset));
126 glBindTexture(GL_TEXTURE_2D, 0);
128 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
134 void QueueLengthPolicy::update_policy(unsigned queue_length)
136 if (queue_length == 0) { // Starvation.
137 if (been_at_safe_point_since_last_starvation && safe_queue_length < unsigned(global_flags.max_input_queue_frames)) {
139 fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frame(s)\n",
140 card_index, safe_queue_length);
142 frames_with_at_least_one = 0;
143 been_at_safe_point_since_last_starvation = false;
146 if (queue_length >= 1) {
147 if (queue_length >= safe_queue_length) {
148 been_at_safe_point_since_last_starvation = true;
150 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 1) {
152 fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frame(s)\n",
153 card_index, safe_queue_length);
154 frames_with_at_least_one = 0;
157 frames_with_at_least_one = 0;
161 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
163 num_cards(num_cards),
164 mixer_surface(create_surface(format)),
165 h264_encoder_surface(create_surface(format)),
166 decklink_output_surface(create_surface(format)),
167 audio_mixer(num_cards)
169 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
172 // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
173 // will be halved when sampling them, and we need to compensate here.
174 movit_texel_subpixel_precision /= 2.0;
176 resource_pool.reset(new ResourcePool);
177 theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get(), num_cards));
178 for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
179 output_channel[i].parent = this;
180 output_channel[i].channel = i;
183 ImageFormat inout_format;
184 inout_format.color_space = COLORSPACE_sRGB;
185 inout_format.gamma_curve = GAMMA_sRGB;
187 // Display chain; shows the live output produced by the main chain (its RGBA version).
188 display_chain.reset(new EffectChain(global_flags.width, global_flags.height, resource_pool.get()));
190 display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height); // FIXME: GL_UNSIGNED_BYTE is really wrong.
191 display_chain->add_input(display_input);
192 display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
193 display_chain->set_dither_bits(0); // Don't bother.
194 display_chain->finalize();
196 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));
198 // Start listening for clients only once VideoEncoder has written its header, if any.
201 // First try initializing the then PCI devices, then USB, then
202 // fill up with fake cards until we have the desired number of cards.
203 unsigned num_pci_devices = 0;
204 unsigned card_index = 0;
207 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
208 if (decklink_iterator != nullptr) {
209 for ( ; card_index < num_cards; ++card_index) {
211 if (decklink_iterator->Next(&decklink) != S_OK) {
215 DeckLinkCapture *capture = new DeckLinkCapture(decklink, card_index);
216 DeckLinkOutput *output = new DeckLinkOutput(resource_pool.get(), decklink_output_surface, global_flags.width, global_flags.height, card_index);
217 output->set_device(decklink);
218 configure_card(card_index, capture, /*is_fake_capture=*/false, output);
221 decklink_iterator->Release();
222 fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
224 fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
228 unsigned num_usb_devices = BMUSBCapture::num_cards();
229 for (unsigned usb_card_index = 0; usb_card_index < num_usb_devices && card_index < num_cards; ++usb_card_index, ++card_index) {
230 BMUSBCapture *capture = new BMUSBCapture(usb_card_index);
231 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, card_index));
232 configure_card(card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
234 fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
236 unsigned num_fake_cards = 0;
237 for ( ; card_index < num_cards; ++card_index, ++num_fake_cards) {
238 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
239 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
242 if (num_fake_cards > 0) {
243 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
246 BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
247 BMUSBCapture::start_bm_thread();
249 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
250 cards[card_index].queue_length_policy.reset(card_index);
253 chroma_subsampler.reset(new ChromaSubsampler(resource_pool.get()));
255 timecode_renderer.reset(new TimecodeRenderer(resource_pool.get(), global_flags.width, global_flags.height));
256 display_timecode_in_stream = global_flags.display_timecode_in_stream;
257 display_timecode_on_stdout = global_flags.display_timecode_on_stdout;
259 if (global_flags.enable_alsa_output) {
260 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
262 if (global_flags.output_card != -1) {
263 desired_output_card_index = global_flags.output_card;
264 set_output_card_internal(global_flags.output_card);
270 BMUSBCapture::stop_bm_thread();
272 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
274 unique_lock<mutex> lock(card_mutex);
275 cards[card_index].should_quit = true; // Unblock thread.
276 cards[card_index].new_frames_changed.notify_all();
278 cards[card_index].capture->stop_dequeue_thread();
279 if (cards[card_index].output) {
280 cards[card_index].output->end_output();
281 cards[card_index].output.reset();
285 video_encoder.reset(nullptr);
288 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture, DeckLinkOutput *output)
290 printf("Configuring card %d...\n", card_index);
292 CaptureCard *card = &cards[card_index];
293 if (card->capture != nullptr) {
294 card->capture->stop_dequeue_thread();
296 card->capture.reset(capture);
297 card->is_fake_capture = is_fake_capture;
298 if (card->output.get() != output) {
299 card->output.reset(output);
301 card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
302 if (card->frame_allocator == nullptr) {
303 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, global_flags.width, global_flags.height)); // 8 MB.
305 card->capture->set_video_frame_allocator(card->frame_allocator.get());
306 if (card->surface == nullptr) {
307 card->surface = create_surface_with_same_format(mixer_surface);
309 while (!card->new_frames.empty()) card->new_frames.pop_front();
310 card->last_timecode = -1;
311 card->capture->configure_card();
313 // NOTE: start_bm_capture() happens in thread_func().
315 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
316 audio_mixer.reset_resampler(device);
317 audio_mixer.set_display_name(device, card->capture->get_description());
318 audio_mixer.trigger_state_changed_callback();
321 void Mixer::set_output_card_internal(int card_index)
323 // We don't really need to take card_mutex, since we're in the mixer
324 // thread and don't mess with any queues (which is the only thing that happens
325 // from other threads), but it's probably the safest in the long run.
326 unique_lock<mutex> lock(card_mutex);
327 if (output_card_index != -1) {
328 // Switch the old card from output to input.
329 CaptureCard *old_card = &cards[output_card_index];
330 old_card->output->end_output();
332 // Stop the fake card that we put into place.
333 // This needs to _not_ happen under the mutex, to avoid deadlock
334 // (delivering the last frame needs to take the mutex).
335 bmusb::CaptureInterface *fake_capture = old_card->capture.get();
337 fake_capture->stop_dequeue_thread();
339 old_card->capture = move(old_card->parked_capture);
340 old_card->is_fake_capture = false;
341 old_card->capture->start_bm_capture();
343 if (card_index != -1) {
344 CaptureCard *card = &cards[card_index];
345 bmusb::CaptureInterface *capture = card->capture.get();
346 // TODO: DeckLinkCapture::stop_dequeue_thread can actually take
347 // several seconds to complete (blocking on DisableVideoInput);
348 // see if we can maybe do it asynchronously.
350 capture->stop_dequeue_thread();
352 card->parked_capture = move(card->capture);
353 bmusb::CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
354 configure_card(card_index, fake_capture, /*is_fake_capture=*/true, card->output.release());
355 card->queue_length_policy.reset(card_index);
356 card->capture->start_bm_capture();
357 desired_output_video_mode = output_video_mode = card->output->pick_video_mode(desired_output_video_mode);
358 card->output->start_output(desired_output_video_mode, pts_int);
360 output_card_index = card_index;
365 int unwrap_timecode(uint16_t current_wrapped, int last)
367 uint16_t last_wrapped = last & 0xffff;
368 if (current_wrapped > last_wrapped) {
369 return (last & ~0xffff) | current_wrapped;
371 return 0x10000 + ((last & ~0xffff) | current_wrapped);
377 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
378 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
379 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
381 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
382 CaptureCard *card = &cards[card_index];
384 if (is_mode_scanning[card_index]) {
385 if (video_format.has_signal) {
386 // Found a stable signal, so stop scanning.
387 is_mode_scanning[card_index] = false;
389 static constexpr double switch_time_s = 0.1; // Should be enough time for the signal to stabilize.
390 steady_clock::time_point now = steady_clock::now();
391 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
392 if (sec_since_last_switch > switch_time_s) {
393 // It isn't this mode; try the next one.
394 mode_scanlist_index[card_index]++;
395 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
396 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
397 last_mode_scan_change[card_index] = now;
402 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
403 assert(frame_length > 0);
405 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;
406 if (num_samples > OUTPUT_FREQUENCY / 10) {
407 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",
408 card_index, int(audio_frame.len), int(audio_offset),
409 timecode, int(video_frame.len), int(video_offset), video_format.id);
410 if (video_frame.owner) {
411 video_frame.owner->release_frame(video_frame);
413 if (audio_frame.owner) {
414 audio_frame.owner->release_frame(audio_frame);
419 int dropped_frames = 0;
420 if (card->last_timecode != -1) {
421 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
424 // Number of samples per frame if we need to insert silence.
425 // (Could be nonintegral, but resampling will save us then.)
426 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
428 if (dropped_frames > MAX_FPS * 2) {
429 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
430 card_index, card->last_timecode, timecode);
431 audio_mixer.reset_resampler(device);
433 } else if (dropped_frames > 0) {
434 // Insert silence as needed.
435 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
436 card_index, dropped_frames, timecode);
440 success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
444 audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length, audio_frame.received_timestamp);
446 // Done with the audio, so release it.
447 if (audio_frame.owner) {
448 audio_frame.owner->release_frame(audio_frame);
451 card->last_timecode = timecode;
453 size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
454 if (video_frame.len - video_offset == 0 ||
455 video_frame.len - video_offset != expected_length) {
456 if (video_frame.len != 0) {
457 printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
458 card_index, video_frame.len - video_offset, expected_length);
460 if (video_frame.owner) {
461 video_frame.owner->release_frame(video_frame);
464 // Still send on the information that we _had_ a frame, even though it's corrupted,
465 // so that pts can go up accordingly.
467 unique_lock<mutex> lock(card_mutex);
468 CaptureCard::NewFrame new_frame;
469 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
470 new_frame.length = frame_length;
471 new_frame.interlaced = false;
472 new_frame.dropped_frames = dropped_frames;
473 new_frame.received_timestamp = video_frame.received_timestamp;
474 card->new_frames.push_back(move(new_frame));
475 card->new_frames_changed.notify_all();
480 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
482 unsigned num_fields = video_format.interlaced ? 2 : 1;
483 steady_clock::time_point frame_upload_start;
484 bool interlaced_stride = false;
485 if (video_format.interlaced) {
486 // Send the two fields along as separate frames; the other side will need to add
487 // a deinterlacer to actually get this right.
488 assert(video_format.height % 2 == 0);
489 video_format.height /= 2;
490 assert(frame_length % 2 == 0);
493 if (video_format.second_field_start == 1) {
494 interlaced_stride = true;
496 frame_upload_start = steady_clock::now();
498 userdata->last_interlaced = video_format.interlaced;
499 userdata->last_has_signal = video_format.has_signal;
500 userdata->last_is_connected = video_format.is_connected;
501 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
502 userdata->last_frame_rate_den = video_format.frame_rate_den;
503 RefCountedFrame frame(video_frame);
505 // Upload the textures.
506 size_t cbcr_width = video_format.width / 2;
507 size_t cbcr_offset = video_offset / 2;
508 size_t y_offset = video_frame.size / 2 + video_offset / 2;
510 for (unsigned field = 0; field < num_fields; ++field) {
511 // Put the actual texture upload in a lambda that is executed in the main thread.
512 // It is entirely possible to do this in the same thread (and it might even be
513 // faster, depending on the GPU and driver), but it appears to be trickling
514 // driver bugs very easily.
516 // Note that this means we must hold on to the actual frame data in <userdata>
517 // until the upload command is run, but we hold on to <frame> much longer than that
518 // (in fact, all the way until we no longer use the texture in rendering).
519 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, interlaced_stride, userdata]() {
520 unsigned field_start_line;
522 field_start_line = video_format.second_field_start;
524 field_start_line = video_format.extra_lines_top;
526 size_t field_y_start = y_offset + video_format.width * field_start_line;
527 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
529 ensure_texture_resolution(userdata, field, video_format.width, video_format.height);
531 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, userdata->pbo);
534 upload_texture(userdata->tex_y[field], video_format.width, video_format.height, video_format.width, interlaced_stride, GL_RED, field_y_start);
535 upload_texture(userdata->tex_cbcr[field], cbcr_width, video_format.height, cbcr_width * sizeof(uint16_t), interlaced_stride, GL_RG, field_cbcr_start);
537 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
542 // Don't upload the second field as fast as we can; wait until
543 // the field time has approximately passed. (Otherwise, we could
544 // get timing jitter against the other sources, and possibly also
545 // against the video display, although the latter is not as critical.)
546 // This requires our system clock to be reasonably close to the
547 // video clock, but that's not an unreasonable assumption.
548 steady_clock::time_point second_field_start = frame_upload_start +
549 nanoseconds(frame_length * 1000000000 / TIMEBASE);
550 this_thread::sleep_until(second_field_start);
554 unique_lock<mutex> lock(card_mutex);
555 CaptureCard::NewFrame new_frame;
556 new_frame.frame = frame;
557 new_frame.length = frame_length;
558 new_frame.field = field;
559 new_frame.interlaced = video_format.interlaced;
560 new_frame.upload_func = upload_func;
561 new_frame.dropped_frames = dropped_frames;
562 new_frame.received_timestamp = video_frame.received_timestamp; // Ignore the audio timestamp.
563 card->new_frames.push_back(move(new_frame));
564 card->new_frames_changed.notify_all();
569 void Mixer::bm_hotplug_add(libusb_device *dev)
571 lock_guard<mutex> lock(hotplug_mutex);
572 hotplugged_cards.push_back(dev);
575 void Mixer::bm_hotplug_remove(unsigned card_index)
577 cards[card_index].new_frames_changed.notify_all();
580 void Mixer::thread_func()
582 pthread_setname_np(pthread_self(), "Mixer_OpenGL");
584 eglBindAPI(EGL_OPENGL_API);
585 QOpenGLContext *context = create_context(mixer_surface);
586 if (!make_current(context, mixer_surface)) {
591 // Start the actual capture. (We don't want to do it before we're actually ready
592 // to process output frames.)
593 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
594 if (int(card_index) != output_card_index) {
595 cards[card_index].capture->start_bm_capture();
599 steady_clock::time_point start, now;
600 start = steady_clock::now();
602 int stats_dropped_frames = 0;
604 while (!should_quit) {
605 if (desired_output_card_index != output_card_index) {
606 set_output_card_internal(desired_output_card_index);
608 if (output_card_index != -1 &&
609 desired_output_video_mode != output_video_mode) {
610 DeckLinkOutput *output = cards[output_card_index].output.get();
611 output->end_output();
612 desired_output_video_mode = output_video_mode = output->pick_video_mode(desired_output_video_mode);
613 output->start_output(desired_output_video_mode, pts_int);
616 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
617 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
619 bool master_card_is_output;
620 unsigned master_card_index;
621 if (output_card_index != -1) {
622 master_card_is_output = true;
623 master_card_index = output_card_index;
625 master_card_is_output = false;
626 master_card_index = theme->map_signal(master_clock_channel);
627 assert(master_card_index < num_cards);
630 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
631 schedule_audio_resampling_tasks(output_frame_info.dropped_frames, output_frame_info.num_samples, output_frame_info.frame_duration, output_frame_info.is_preroll, output_frame_info.frame_timestamp);
632 stats_dropped_frames += output_frame_info.dropped_frames;
634 handle_hotplugged_cards();
636 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
637 if (card_index == master_card_index || !has_new_frame[card_index]) {
640 if (new_frames[card_index].frame->len == 0) {
641 ++new_frames[card_index].dropped_frames;
643 if (new_frames[card_index].dropped_frames > 0) {
644 printf("Card %u dropped %d frames before this\n",
645 card_index, int(new_frames[card_index].dropped_frames));
649 // If the first card is reporting a corrupted or otherwise dropped frame,
650 // just increase the pts (skipping over this frame) and don't try to compute anything new.
651 if (!master_card_is_output && new_frames[master_card_index].frame->len == 0) {
652 ++stats_dropped_frames;
653 pts_int += new_frames[master_card_index].length;
657 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
658 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
661 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
662 assert(new_frame->frame != nullptr);
663 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
666 // The new texture might need uploading before use.
667 if (new_frame->upload_func) {
668 new_frame->upload_func();
669 new_frame->upload_func = nullptr;
673 int64_t frame_duration = output_frame_info.frame_duration;
674 render_one_frame(frame_duration);
676 pts_int += frame_duration;
678 now = steady_clock::now();
679 double elapsed = duration<double>(now - start).count();
680 if (frame_num % 100 == 0) {
681 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
682 frame_num, stats_dropped_frames, elapsed, frame_num / elapsed,
683 1e3 * elapsed / frame_num);
684 // chain->print_phase_timing();
686 // Check our memory usage, to see if we are close to our mlockall()
687 // limit (if at all set).
689 if (getrusage(RUSAGE_SELF, &used) == -1) {
690 perror("getrusage(RUSAGE_SELF)");
696 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
697 perror("getrlimit(RLIMIT_MEMLOCK)");
701 if (limit.rlim_cur == 0) {
702 printf(", using %ld MB memory (locked)",
703 long(used.ru_maxrss / 1024));
705 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
706 long(used.ru_maxrss / 1024),
707 long(limit.rlim_cur / 1048576),
708 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
711 printf(", using %ld MB memory (not locked)",
712 long(used.ru_maxrss / 1024));
719 if (should_cut.exchange(false)) { // Test and clear.
720 video_encoder->do_cut(frame_num);
724 // Reset every 100 frames, so that local variations in frame times
725 // (especially for the first few frames, when the shaders are
726 // compiled etc.) don't make it hard to measure for the entire
727 // remaining duration of the program.
728 if (frame == 10000) {
736 resource_pool->clean_context();
739 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
741 if (output_card_index != -1) {
742 // The output card (ie., cards[output_card_index].output) is the master clock,
743 // so no input card (ie., cards[card_index].capture) is.
746 return (card_index == master_card_index);
749 void Mixer::trim_queue(CaptureCard *card, unsigned card_index)
751 // Count the number of frames in the queue, including any frames
752 // we dropped. It's hard to know exactly how we should deal with
753 // dropped (corrupted) input frames; they don't help our goal of
754 // avoiding starvation, but they still add to the problem of latency.
755 // Since dropped frames is going to mean a bump in the signal anyway,
756 // we err on the side of having more stable latency instead.
757 unsigned queue_length = 0;
758 for (const CaptureCard::NewFrame &frame : card->new_frames) {
759 queue_length += frame.dropped_frames + 1;
761 card->queue_length_policy.update_policy(queue_length);
763 // If needed, drop frames until the queue is below the safe limit.
764 // We prefer to drop from the head, because all else being equal,
765 // we'd like more recent frames (less latency).
766 unsigned dropped_frames = 0;
767 while (queue_length > card->queue_length_policy.get_safe_queue_length()) {
768 assert(!card->new_frames.empty());
769 assert(queue_length > card->new_frames.front().dropped_frames);
770 queue_length -= card->new_frames.front().dropped_frames;
772 if (queue_length <= card->queue_length_policy.get_safe_queue_length()) {
773 // No need to drop anything.
777 card->new_frames.pop_front();
778 card->new_frames_changed.notify_all();
783 if (dropped_frames > 0) {
784 fprintf(stderr, "Card %u dropped %u frame(s) to keep latency down.\n",
785 card_index, dropped_frames);
790 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])
792 OutputFrameInfo output_frame_info;
794 unique_lock<mutex> lock(card_mutex, defer_lock);
795 if (master_card_is_output) {
796 // Clocked to the output, so wait for it to be ready for the next frame.
797 cards[master_card_index].output->wait_for_frame(pts_int, &output_frame_info.dropped_frames, &output_frame_info.frame_duration, &output_frame_info.is_preroll, &output_frame_info.frame_timestamp);
800 // Wait for the master card to have a new frame.
801 // TODO: Add a timeout.
802 output_frame_info.is_preroll = false;
804 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(); });
807 if (master_card_is_output) {
808 handle_hotplugged_cards();
809 } else if (cards[master_card_index].new_frames.empty()) {
810 // We were woken up, but not due to a new frame. Deal with it
812 assert(cards[master_card_index].capture->get_disconnected());
813 handle_hotplugged_cards();
817 if (!master_card_is_output) {
818 output_frame_info.frame_timestamp =
819 cards[master_card_index].new_frames.front().received_timestamp;
822 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
823 CaptureCard *card = &cards[card_index];
824 if (input_card_is_master_clock(card_index, master_card_index)) {
825 // We don't use the queue length policy for the master card,
826 // but we will if it stops being the master. Thus, clear out
827 // the policy in case we switch in the future.
828 card->queue_length_policy.reset(card_index);
829 assert(!card->new_frames.empty());
831 trim_queue(card, card_index);
833 if (!card->new_frames.empty()) {
834 new_frames[card_index] = move(card->new_frames.front());
835 has_new_frame[card_index] = true;
836 card->new_frames.pop_front();
837 card->new_frames_changed.notify_all();
841 if (!master_card_is_output) {
842 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
843 output_frame_info.frame_duration = new_frames[master_card_index].length;
846 // This might get off by a fractional sample when changing master card
847 // between ones with different frame rates, but that's fine.
848 int num_samples_times_timebase = OUTPUT_FREQUENCY * output_frame_info.frame_duration + fractional_samples;
849 output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
850 fractional_samples = num_samples_times_timebase % TIMEBASE;
851 assert(output_frame_info.num_samples >= 0);
853 return output_frame_info;
856 void Mixer::handle_hotplugged_cards()
858 // Check for cards that have been disconnected since last frame.
859 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
860 CaptureCard *card = &cards[card_index];
861 if (card->capture->get_disconnected()) {
862 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
863 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
864 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
865 card->queue_length_policy.reset(card_index);
866 card->capture->start_bm_capture();
870 // Check for cards that have been connected since last frame.
871 vector<libusb_device *> hotplugged_cards_copy;
873 lock_guard<mutex> lock(hotplug_mutex);
874 swap(hotplugged_cards, hotplugged_cards_copy);
876 for (libusb_device *new_dev : hotplugged_cards_copy) {
877 // Look for a fake capture card where we can stick this in.
878 int free_card_index = -1;
879 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
880 if (cards[card_index].is_fake_capture) {
881 free_card_index = card_index;
886 if (free_card_index == -1) {
887 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
888 libusb_unref_device(new_dev);
890 // BMUSBCapture takes ownership.
891 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
892 CaptureCard *card = &cards[free_card_index];
893 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
894 configure_card(free_card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
895 card->queue_length_policy.reset(free_card_index);
896 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
897 capture->start_bm_capture();
903 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame, bool is_preroll, steady_clock::time_point frame_timestamp)
905 // Resample the audio as needed, including from previously dropped frames.
906 assert(num_cards > 0);
907 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
908 const bool dropped_frame = (frame_num != dropped_frames);
910 // Signal to the audio thread to process this frame.
911 // Note that if the frame is a dropped frame, we signal that
912 // we don't want to use this frame as base for adjusting
913 // the resampler rate. The reason for this is that the timing
914 // of these frames is often way too late; they typically don't
915 // “arrive” before we synthesize them. Thus, we could end up
916 // in a situation where we have inserted e.g. five audio frames
917 // into the queue before we then start pulling five of them
918 // back out. This makes ResamplingQueue overestimate the delay,
919 // causing undue resampler changes. (We _do_ use the last,
920 // non-dropped frame; perhaps we should just discard that as well,
921 // since dropped frames are expected to be rare, and it might be
922 // better to just wait until we have a slightly more normal situation).
923 unique_lock<mutex> lock(audio_mutex);
924 bool adjust_rate = !dropped_frame && !is_preroll;
925 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
926 audio_task_queue_changed.notify_one();
929 // For dropped frames, increase the pts. Note that if the format changed
930 // in the meantime, we have no way of detecting that; we just have to
931 // assume the frame length is always the same.
932 pts_int += length_per_frame;
937 void Mixer::render_one_frame(int64_t duration)
939 // Determine the time code for this frame before we start rendering.
940 string timecode_text = timecode_renderer->get_timecode_text(double(pts_int) / TIMEBASE, frame_num);
941 if (display_timecode_on_stdout) {
942 printf("Timecode: '%s'\n", timecode_text.c_str());
945 // Get the main chain from the theme, and set its state immediately.
946 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
947 EffectChain *chain = theme_main_chain.chain;
948 theme_main_chain.setup_chain();
949 //theme_main_chain.chain->enable_phase_timing(true);
951 GLuint y_tex, cbcr_tex;
952 bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
955 // Render main chain.
956 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, global_flags.width, global_flags.height);
957 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, global_flags.width, global_flags.height); // Saves texture bandwidth, although dithering gets messed up.
958 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
960 chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
962 if (display_timecode_in_stream) {
963 // Render the timecode on top.
964 timecode_renderer->render_timecode(fbo, timecode_text);
967 resource_pool->release_fbo(fbo);
969 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
970 if (output_card_index != -1) {
971 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, theme_main_chain.input_frames, pts_int, duration);
973 resource_pool->release_2d_texture(cbcr_full_tex);
975 // Set the right state for rgba_tex.
976 glBindFramebuffer(GL_FRAMEBUFFER, 0);
977 glBindTexture(GL_TEXTURE_2D, rgba_tex);
978 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
979 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
980 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
982 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
983 RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
985 // The live frame just shows the RGBA texture we just rendered.
986 // It owns rgba_tex now.
987 DisplayFrame live_frame;
988 live_frame.chain = display_chain.get();
989 live_frame.setup_chain = [this, rgba_tex]{
990 display_input->set_texture_num(rgba_tex);
992 live_frame.ready_fence = fence;
993 live_frame.input_frames = {};
994 live_frame.temp_textures = { rgba_tex };
995 output_channel[OUTPUT_LIVE].output_frame(live_frame);
997 // Set up preview and any additional channels.
998 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
999 DisplayFrame display_frame;
1000 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state); // FIXME: dimensions
1001 display_frame.chain = chain.chain;
1002 display_frame.setup_chain = chain.setup_chain;
1003 display_frame.ready_fence = fence;
1004 display_frame.input_frames = chain.input_frames;
1005 display_frame.temp_textures = {};
1006 output_channel[i].output_frame(display_frame);
1010 void Mixer::audio_thread_func()
1012 pthread_setname_np(pthread_self(), "Mixer_Audio");
1014 while (!should_quit) {
1018 unique_lock<mutex> lock(audio_mutex);
1019 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
1023 task = audio_task_queue.front();
1024 audio_task_queue.pop();
1027 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
1028 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
1029 vector<float> samples_out = audio_mixer.get_output(
1030 task.frame_timestamp,
1032 rate_adjustment_policy);
1034 // Send the samples to the sound card, then add them to the output.
1036 alsa->write(samples_out);
1038 if (output_card_index != -1) {
1039 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
1040 cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
1042 video_encoder->add_audio(task.pts_int, move(samples_out));
1046 void Mixer::release_display_frame(DisplayFrame *frame)
1048 for (GLuint texnum : frame->temp_textures) {
1049 resource_pool->release_2d_texture(texnum);
1051 frame->temp_textures.clear();
1052 frame->ready_fence.reset();
1053 frame->input_frames.clear();
1058 mixer_thread = thread(&Mixer::thread_func, this);
1059 audio_thread = thread(&Mixer::audio_thread_func, this);
1065 audio_task_queue_changed.notify_one();
1066 mixer_thread.join();
1067 audio_thread.join();
1070 void Mixer::transition_clicked(int transition_num)
1072 theme->transition_clicked(transition_num, pts());
1075 void Mixer::channel_clicked(int preview_num)
1077 theme->channel_clicked(preview_num);
1080 void Mixer::start_mode_scanning(unsigned card_index)
1082 assert(card_index < num_cards);
1083 if (is_mode_scanning[card_index]) {
1086 is_mode_scanning[card_index] = true;
1087 mode_scanlist[card_index].clear();
1088 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1089 mode_scanlist[card_index].push_back(mode.first);
1091 assert(!mode_scanlist[card_index].empty());
1092 mode_scanlist_index[card_index] = 0;
1093 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1094 last_mode_scan_change[card_index] = steady_clock::now();
1097 map<uint32_t, bmusb::VideoMode> Mixer::get_available_output_video_modes() const
1099 assert(desired_output_card_index != -1);
1100 unique_lock<mutex> lock(card_mutex);
1101 return cards[desired_output_card_index].output->get_available_video_modes();
1104 Mixer::OutputChannel::~OutputChannel()
1106 if (has_current_frame) {
1107 parent->release_display_frame(¤t_frame);
1109 if (has_ready_frame) {
1110 parent->release_display_frame(&ready_frame);
1114 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1116 // Store this frame for display. Remove the ready frame if any
1117 // (it was seemingly never used).
1119 unique_lock<mutex> lock(frame_mutex);
1120 if (has_ready_frame) {
1121 parent->release_display_frame(&ready_frame);
1123 ready_frame = frame;
1124 has_ready_frame = true;
1127 if (new_frame_ready_callback) {
1128 new_frame_ready_callback();
1131 // Reduce the number of callbacks by filtering duplicates. The reason
1132 // why we bother doing this is that Qt seemingly can get into a state
1133 // where its builds up an essentially unbounded queue of signals,
1134 // consuming more and more memory, and there's no good way of collapsing
1135 // user-defined signals or limiting the length of the queue.
1136 if (transition_names_updated_callback) {
1137 vector<string> transition_names = global_mixer->get_transition_names();
1138 bool changed = false;
1139 if (transition_names.size() != last_transition_names.size()) {
1142 for (unsigned i = 0; i < transition_names.size(); ++i) {
1143 if (transition_names[i] != last_transition_names[i]) {
1150 transition_names_updated_callback(transition_names);
1151 last_transition_names = transition_names;
1154 if (name_updated_callback) {
1155 string name = global_mixer->get_channel_name(channel);
1156 if (name != last_name) {
1157 name_updated_callback(name);
1161 if (color_updated_callback) {
1162 string color = global_mixer->get_channel_color(channel);
1163 if (color != last_color) {
1164 color_updated_callback(color);
1170 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1172 unique_lock<mutex> lock(frame_mutex);
1173 if (!has_current_frame && !has_ready_frame) {
1177 if (has_current_frame && has_ready_frame) {
1178 // We have a new ready frame. Toss the current one.
1179 parent->release_display_frame(¤t_frame);
1180 has_current_frame = false;
1182 if (has_ready_frame) {
1183 assert(!has_current_frame);
1184 current_frame = ready_frame;
1185 ready_frame.ready_fence.reset(); // Drop the refcount.
1186 ready_frame.input_frames.clear(); // Drop the refcounts.
1187 has_current_frame = true;
1188 has_ready_frame = false;
1191 *frame = current_frame;
1195 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1197 new_frame_ready_callback = callback;
1200 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1202 transition_names_updated_callback = callback;
1205 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1207 name_updated_callback = callback;
1210 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1212 color_updated_callback = callback;
1215 mutex RefCountedGLsync::fence_lock;