7 #include <movit/effect_chain.h>
8 #include <movit/effect_util.h>
9 #include <movit/flat_input.h>
10 #include <movit/image_format.h>
11 #include <movit/init.h>
12 #include <movit/resource_pool.h>
13 #include <movit/util.h>
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"
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(WIDTH, HEIGHT, resource_pool.get()));
134 display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, WIDTH, 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, WIDTH, 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(WIDTH, 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 (card_index = 0; card_index < num_cards; ++card_index) {
190 cards[card_index].queue_length_policy.reset(card_index);
191 cards[card_index].capture->start_bm_capture();
194 // Set up stuff for NV12 conversion.
197 string cbcr_vert_shader =
200 "in vec2 position; \n"
201 "in vec2 texcoord; \n"
203 "uniform vec2 foo_chroma_offset_0; \n"
207 " // The result of glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0) is: \n"
209 " // 2.000 0.000 0.000 -1.000 \n"
210 " // 0.000 2.000 0.000 -1.000 \n"
211 " // 0.000 0.000 -2.000 -1.000 \n"
212 " // 0.000 0.000 0.000 1.000 \n"
213 " gl_Position = vec4(2.0 * position.x - 1.0, 2.0 * position.y - 1.0, -1.0, 1.0); \n"
214 " vec2 flipped_tc = texcoord; \n"
215 " tc0 = flipped_tc + foo_chroma_offset_0; \n"
217 string cbcr_frag_shader =
220 "uniform sampler2D cbcr_tex; \n"
221 "out vec4 FragColor; \n"
223 " FragColor = texture(cbcr_tex, tc0); \n"
225 vector<string> frag_shader_outputs;
226 cbcr_program_num = resource_pool->compile_glsl_program(cbcr_vert_shader, cbcr_frag_shader, frag_shader_outputs);
233 cbcr_vbo = generate_vbo(2, GL_FLOAT, sizeof(vertices), vertices);
234 cbcr_position_attribute_index = glGetAttribLocation(cbcr_program_num, "position");
235 cbcr_texcoord_attribute_index = glGetAttribLocation(cbcr_program_num, "texcoord");
237 if (global_flags.enable_alsa_output) {
238 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
244 resource_pool->release_glsl_program(cbcr_program_num);
245 glDeleteBuffers(1, &cbcr_vbo);
246 BMUSBCapture::stop_bm_thread();
248 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
250 unique_lock<mutex> lock(bmusb_mutex);
251 cards[card_index].should_quit = true; // Unblock thread.
252 cards[card_index].new_frames_changed.notify_all();
254 cards[card_index].capture->stop_dequeue_thread();
257 video_encoder.reset(nullptr);
260 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture)
262 printf("Configuring card %d...\n", card_index);
264 CaptureCard *card = &cards[card_index];
265 if (card->capture != nullptr) {
266 card->capture->stop_dequeue_thread();
267 delete card->capture;
269 card->capture = capture;
270 card->is_fake_capture = is_fake_capture;
271 card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
272 if (card->frame_allocator == nullptr) {
273 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, WIDTH, HEIGHT)); // 8 MB.
275 card->capture->set_video_frame_allocator(card->frame_allocator.get());
276 if (card->surface == nullptr) {
277 card->surface = create_surface_with_same_format(mixer_surface);
279 while (!card->new_frames.empty()) card->new_frames.pop();
280 card->fractional_samples = 0;
281 card->last_timecode = -1;
282 card->capture->configure_card();
284 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
285 audio_mixer.reset_resampler(device);
286 audio_mixer.set_display_name(device, card->capture->get_description());
287 audio_mixer.trigger_state_changed_callback();
293 int unwrap_timecode(uint16_t current_wrapped, int last)
295 uint16_t last_wrapped = last & 0xffff;
296 if (current_wrapped > last_wrapped) {
297 return (last & ~0xffff) | current_wrapped;
299 return 0x10000 + ((last & ~0xffff) | current_wrapped);
305 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
306 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
307 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
309 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
310 CaptureCard *card = &cards[card_index];
312 if (is_mode_scanning[card_index]) {
313 if (video_format.has_signal) {
314 // Found a stable signal, so stop scanning.
315 is_mode_scanning[card_index] = false;
317 static constexpr double switch_time_s = 0.5; // Should be enough time for the signal to stabilize.
318 steady_clock::time_point now = steady_clock::now();
319 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
320 if (sec_since_last_switch > switch_time_s) {
321 // It isn't this mode; try the next one.
322 mode_scanlist_index[card_index]++;
323 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
324 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
325 last_mode_scan_change[card_index] = now;
330 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
331 assert(frame_length > 0);
333 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;
334 if (num_samples > OUTPUT_FREQUENCY / 10) {
335 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",
336 card_index, int(audio_frame.len), int(audio_offset),
337 timecode, int(video_frame.len), int(video_offset), video_format.id);
338 if (video_frame.owner) {
339 video_frame.owner->release_frame(video_frame);
341 if (audio_frame.owner) {
342 audio_frame.owner->release_frame(audio_frame);
347 int dropped_frames = 0;
348 if (card->last_timecode != -1) {
349 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
352 // Number of samples per frame if we need to insert silence.
353 // (Could be nonintegral, but resampling will save us then.)
354 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
356 if (dropped_frames > MAX_FPS * 2) {
357 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
358 card_index, card->last_timecode, timecode);
359 audio_mixer.reset_resampler(device);
361 } else if (dropped_frames > 0) {
362 // Insert silence as needed.
363 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
364 card_index, dropped_frames, timecode);
368 success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
372 audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length);
374 // Done with the audio, so release it.
375 if (audio_frame.owner) {
376 audio_frame.owner->release_frame(audio_frame);
379 card->last_timecode = timecode;
381 size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
382 if (video_frame.len - video_offset == 0 ||
383 video_frame.len - video_offset != expected_length) {
384 if (video_frame.len != 0) {
385 printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
386 card_index, video_frame.len - video_offset, expected_length);
388 if (video_frame.owner) {
389 video_frame.owner->release_frame(video_frame);
392 // Still send on the information that we _had_ a frame, even though it's corrupted,
393 // so that pts can go up accordingly.
395 unique_lock<mutex> lock(bmusb_mutex);
396 CaptureCard::NewFrame new_frame;
397 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
398 new_frame.length = frame_length;
399 new_frame.interlaced = false;
400 new_frame.dropped_frames = dropped_frames;
401 card->new_frames.push(move(new_frame));
402 card->new_frames_changed.notify_all();
407 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
409 unsigned num_fields = video_format.interlaced ? 2 : 1;
410 steady_clock::time_point frame_upload_start;
411 if (video_format.interlaced) {
412 // Send the two fields along as separate frames; the other side will need to add
413 // a deinterlacer to actually get this right.
414 assert(video_format.height % 2 == 0);
415 video_format.height /= 2;
416 assert(frame_length % 2 == 0);
419 frame_upload_start = steady_clock::now();
421 userdata->last_interlaced = video_format.interlaced;
422 userdata->last_has_signal = video_format.has_signal;
423 userdata->last_is_connected = video_format.is_connected;
424 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
425 userdata->last_frame_rate_den = video_format.frame_rate_den;
426 RefCountedFrame frame(video_frame);
428 // Upload the textures.
429 size_t cbcr_width = video_format.width / 2;
430 size_t cbcr_offset = video_offset / 2;
431 size_t y_offset = video_frame.size / 2 + video_offset / 2;
433 for (unsigned field = 0; field < num_fields; ++field) {
434 // Put the actual texture upload in a lambda that is executed in the main thread.
435 // It is entirely possible to do this in the same thread (and it might even be
436 // faster, depending on the GPU and driver), but it appears to be trickling
437 // driver bugs very easily.
439 // Note that this means we must hold on to the actual frame data in <userdata>
440 // until the upload command is run, but we hold on to <frame> much longer than that
441 // (in fact, all the way until we no longer use the texture in rendering).
442 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, userdata]() {
443 unsigned field_start_line = (field == 1) ? video_format.second_field_start : video_format.extra_lines_top + field * (video_format.height + 22);
445 if (userdata->tex_y[field] == 0 ||
446 userdata->tex_cbcr[field] == 0 ||
447 video_format.width != userdata->last_width[field] ||
448 video_format.height != userdata->last_height[field]) {
449 // We changed resolution since last use of this texture, so we need to create
450 // a new object. Note that this each card has its own PBOFrameAllocator,
451 // we don't need to worry about these flip-flopping between resolutions.
452 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
454 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
456 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
458 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
460 userdata->last_width[field] = video_format.width;
461 userdata->last_height[field] = video_format.height;
464 GLuint pbo = userdata->pbo;
466 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
469 size_t field_y_start = y_offset + video_format.width * field_start_line;
470 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
472 if (global_flags.flush_pbos) {
473 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
475 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
479 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
481 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
483 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
485 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
487 glBindTexture(GL_TEXTURE_2D, 0);
489 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
494 // Don't upload the second field as fast as we can; wait until
495 // the field time has approximately passed. (Otherwise, we could
496 // get timing jitter against the other sources, and possibly also
497 // against the video display, although the latter is not as critical.)
498 // This requires our system clock to be reasonably close to the
499 // video clock, but that's not an unreasonable assumption.
500 steady_clock::time_point second_field_start = frame_upload_start +
501 nanoseconds(frame_length * 1000000000 / TIMEBASE);
502 this_thread::sleep_until(second_field_start);
506 unique_lock<mutex> lock(bmusb_mutex);
507 CaptureCard::NewFrame new_frame;
508 new_frame.frame = frame;
509 new_frame.length = frame_length;
510 new_frame.field = field;
511 new_frame.interlaced = video_format.interlaced;
512 new_frame.upload_func = upload_func;
513 new_frame.dropped_frames = dropped_frames;
514 card->new_frames.push(move(new_frame));
515 card->new_frames_changed.notify_all();
520 void Mixer::bm_hotplug_add(libusb_device *dev)
522 lock_guard<mutex> lock(hotplug_mutex);
523 hotplugged_cards.push_back(dev);
526 void Mixer::bm_hotplug_remove(unsigned card_index)
528 cards[card_index].new_frames_changed.notify_all();
531 void Mixer::thread_func()
533 eglBindAPI(EGL_OPENGL_API);
534 QOpenGLContext *context = create_context(mixer_surface);
535 if (!make_current(context, mixer_surface)) {
540 steady_clock::time_point start, now;
541 start = steady_clock::now();
544 int stats_dropped_frames = 0;
546 while (!should_quit) {
547 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
548 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
549 int num_samples[MAX_VIDEO_CARDS] = { 0 };
551 unsigned master_card_index = theme->map_signal(master_clock_channel);
552 assert(master_card_index < num_cards);
554 get_one_frame_from_each_card(master_card_index, new_frames, has_new_frame, num_samples);
555 schedule_audio_resampling_tasks(new_frames[master_card_index].dropped_frames, num_samples[master_card_index], new_frames[master_card_index].length);
556 stats_dropped_frames += new_frames[master_card_index].dropped_frames;
558 handle_hotplugged_cards();
560 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
561 if (card_index == master_card_index || !has_new_frame[card_index]) {
564 if (new_frames[card_index].frame->len == 0) {
565 ++new_frames[card_index].dropped_frames;
567 if (new_frames[card_index].dropped_frames > 0) {
568 printf("Card %u dropped %d frames before this\n",
569 card_index, int(new_frames[card_index].dropped_frames));
573 // If the first card is reporting a corrupted or otherwise dropped frame,
574 // just increase the pts (skipping over this frame) and don't try to compute anything new.
575 if (new_frames[master_card_index].frame->len == 0) {
576 ++stats_dropped_frames;
577 pts_int += new_frames[master_card_index].length;
581 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
582 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
585 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
586 assert(new_frame->frame != nullptr);
587 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
590 // The new texture might need uploading before use.
591 if (new_frame->upload_func) {
592 new_frame->upload_func();
593 new_frame->upload_func = nullptr;
597 int64_t frame_duration = new_frames[master_card_index].length;
598 render_one_frame(frame_duration);
600 pts_int += frame_duration;
602 now = steady_clock::now();
603 double elapsed = duration<double>(now - start).count();
604 if (frame % 100 == 0) {
605 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
606 frame, stats_dropped_frames, elapsed, frame / elapsed,
607 1e3 * elapsed / frame);
608 // chain->print_phase_timing();
610 // Check our memory usage, to see if we are close to our mlockall()
611 // limit (if at all set).
613 if (getrusage(RUSAGE_SELF, &used) == -1) {
614 perror("getrusage(RUSAGE_SELF)");
620 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
621 perror("getrlimit(RLIMIT_MEMLOCK)");
625 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
626 long(used.ru_maxrss / 1024),
627 long(limit.rlim_cur / 1048576),
628 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
630 printf(", using %ld MB memory (not locked)",
631 long(used.ru_maxrss / 1024));
638 if (should_cut.exchange(false)) { // Test and clear.
639 video_encoder->do_cut(frame);
643 // Reset every 100 frames, so that local variations in frame times
644 // (especially for the first few frames, when the shaders are
645 // compiled etc.) don't make it hard to measure for the entire
646 // remaining duration of the program.
647 if (frame == 10000) {
655 resource_pool->clean_context();
658 void Mixer::get_one_frame_from_each_card(unsigned master_card_index, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS], int num_samples[MAX_VIDEO_CARDS])
661 // The first card is the master timer, so wait for it to have a new frame.
662 // TODO: Add a timeout.
663 unique_lock<mutex> lock(bmusb_mutex);
664 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(); });
666 if (cards[master_card_index].new_frames.empty()) {
667 // We were woken up, but not due to a new frame. Deal with it
669 assert(cards[master_card_index].capture->get_disconnected());
670 handle_hotplugged_cards();
674 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
675 CaptureCard *card = &cards[card_index];
676 if (card->new_frames.empty()) {
677 assert(card_index != master_card_index);
678 card->queue_length_policy.update_policy(-1);
681 new_frames[card_index] = move(card->new_frames.front());
682 has_new_frame[card_index] = true;
683 card->new_frames.pop();
684 card->new_frames_changed.notify_all();
686 int num_samples_times_timebase = OUTPUT_FREQUENCY * new_frames[card_index].length + card->fractional_samples;
687 num_samples[card_index] = num_samples_times_timebase / TIMEBASE;
688 card->fractional_samples = num_samples_times_timebase % TIMEBASE;
689 assert(num_samples[card_index] >= 0);
691 if (card_index == master_card_index) {
692 // We don't use the queue length policy for the master card,
693 // but we will if it stops being the master. Thus, clear out
694 // the policy in case we switch in the future.
695 card->queue_length_policy.reset(card_index);
697 // If we have excess frames compared to the policy for this card,
698 // drop frames from the head.
699 card->queue_length_policy.update_policy(card->new_frames.size());
700 while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
701 card->new_frames.pop();
707 void Mixer::handle_hotplugged_cards()
709 // Check for cards that have been disconnected since last frame.
710 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
711 CaptureCard *card = &cards[card_index];
712 if (card->capture->get_disconnected()) {
713 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
714 FakeCapture *capture = new FakeCapture(WIDTH, HEIGHT, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
715 configure_card(card_index, capture, /*is_fake_capture=*/true);
716 card->queue_length_policy.reset(card_index);
717 card->capture->start_bm_capture();
721 // Check for cards that have been connected since last frame.
722 vector<libusb_device *> hotplugged_cards_copy;
724 lock_guard<mutex> lock(hotplug_mutex);
725 swap(hotplugged_cards, hotplugged_cards_copy);
727 for (libusb_device *new_dev : hotplugged_cards_copy) {
728 // Look for a fake capture card where we can stick this in.
729 int free_card_index = -1;
730 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
731 if (cards[card_index].is_fake_capture) {
732 free_card_index = int(card_index);
737 if (free_card_index == -1) {
738 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
739 libusb_unref_device(new_dev);
741 // BMUSBCapture takes ownership.
742 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
743 CaptureCard *card = &cards[free_card_index];
744 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
745 configure_card(free_card_index, capture, /*is_fake_capture=*/false);
746 card->queue_length_policy.reset(free_card_index);
747 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
748 capture->start_bm_capture();
754 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame)
756 // Resample the audio as needed, including from previously dropped frames.
757 assert(num_cards > 0);
758 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
759 const bool dropped_frame = (frame_num != dropped_frames);
761 // Signal to the audio thread to process this frame.
762 // Note that if the frame is a dropped frame, we signal that
763 // we don't want to use this frame as base for adjusting
764 // the resampler rate. The reason for this is that the timing
765 // of these frames is often way too late; they typically don't
766 // “arrive” before we synthesize them. Thus, we could end up
767 // in a situation where we have inserted e.g. five audio frames
768 // into the queue before we then start pulling five of them
769 // back out. This makes ResamplingQueue overestimate the delay,
770 // causing undue resampler changes. (We _do_ use the last,
771 // non-dropped frame; perhaps we should just discard that as well,
772 // since dropped frames are expected to be rare, and it might be
773 // better to just wait until we have a slightly more normal situation).
774 unique_lock<mutex> lock(audio_mutex);
775 bool adjust_rate = !dropped_frame;
776 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate});
777 audio_task_queue_changed.notify_one();
780 // For dropped frames, increase the pts. Note that if the format changed
781 // in the meantime, we have no way of detecting that; we just have to
782 // assume the frame length is always the same.
783 pts_int += length_per_frame;
788 void Mixer::render_one_frame(int64_t duration)
790 // Get the main chain from the theme, and set its state immediately.
791 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), WIDTH, HEIGHT, input_state);
792 EffectChain *chain = theme_main_chain.chain;
793 theme_main_chain.setup_chain();
794 //theme_main_chain.chain->enable_phase_timing(true);
796 GLuint y_tex, cbcr_tex;
797 bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
800 // Render main chain.
801 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, WIDTH, HEIGHT);
802 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, WIDTH, HEIGHT); // Saves texture bandwidth, although dithering gets messed up.
803 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
805 chain->render_to_fbo(fbo, WIDTH, HEIGHT);
806 resource_pool->release_fbo(fbo);
808 subsample_chroma(cbcr_full_tex, cbcr_tex);
809 resource_pool->release_2d_texture(cbcr_full_tex);
811 // Set the right state for rgba_tex.
812 glBindFramebuffer(GL_FRAMEBUFFER, 0);
813 glBindTexture(GL_TEXTURE_2D, rgba_tex);
814 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
815 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
816 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
818 const int64_t av_delay = TIMEBASE / 10; // Corresponds to the fixed delay in resampling_queue.h. TODO: Make less hard-coded.
819 RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
821 // The live frame just shows the RGBA texture we just rendered.
822 // It owns rgba_tex now.
823 DisplayFrame live_frame;
824 live_frame.chain = display_chain.get();
825 live_frame.setup_chain = [this, rgba_tex]{
826 display_input->set_texture_num(rgba_tex);
828 live_frame.ready_fence = fence;
829 live_frame.input_frames = {};
830 live_frame.temp_textures = { rgba_tex };
831 output_channel[OUTPUT_LIVE].output_frame(live_frame);
833 // Set up preview and any additional channels.
834 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
835 DisplayFrame display_frame;
836 Theme::Chain chain = theme->get_chain(i, pts(), WIDTH, HEIGHT, input_state); // FIXME: dimensions
837 display_frame.chain = chain.chain;
838 display_frame.setup_chain = chain.setup_chain;
839 display_frame.ready_fence = fence;
840 display_frame.input_frames = chain.input_frames;
841 display_frame.temp_textures = {};
842 output_channel[i].output_frame(display_frame);
846 void Mixer::audio_thread_func()
848 while (!should_quit) {
852 unique_lock<mutex> lock(audio_mutex);
853 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
857 task = audio_task_queue.front();
858 audio_task_queue.pop();
861 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
862 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
863 vector<float> samples_out = audio_mixer.get_output(
864 double(task.pts_int) / TIMEBASE,
866 rate_adjustment_policy);
868 // Send the samples to the sound card, then add them to the output.
870 alsa->write(samples_out);
872 video_encoder->add_audio(task.pts_int, move(samples_out));
876 void Mixer::subsample_chroma(GLuint src_tex, GLuint dst_tex)
879 glGenVertexArrays(1, &vao);
882 glBindVertexArray(vao);
886 GLuint fbo = resource_pool->create_fbo(dst_tex);
887 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
888 glViewport(0, 0, WIDTH/2, HEIGHT/2);
891 glUseProgram(cbcr_program_num);
894 glActiveTexture(GL_TEXTURE0);
896 glBindTexture(GL_TEXTURE_2D, src_tex);
898 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
900 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
902 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
905 float chroma_offset_0[] = { -0.5f / WIDTH, 0.0f };
906 set_uniform_vec2(cbcr_program_num, "foo", "chroma_offset_0", chroma_offset_0);
908 glBindBuffer(GL_ARRAY_BUFFER, cbcr_vbo);
911 for (GLint attr_index : { cbcr_position_attribute_index, cbcr_texcoord_attribute_index }) {
912 glEnableVertexAttribArray(attr_index);
914 glVertexAttribPointer(attr_index, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
918 glDrawArrays(GL_TRIANGLES, 0, 3);
921 for (GLint attr_index : { cbcr_position_attribute_index, cbcr_texcoord_attribute_index }) {
922 glDisableVertexAttribArray(attr_index);
928 glBindFramebuffer(GL_FRAMEBUFFER, 0);
931 resource_pool->release_fbo(fbo);
932 glDeleteVertexArrays(1, &vao);
935 void Mixer::release_display_frame(DisplayFrame *frame)
937 for (GLuint texnum : frame->temp_textures) {
938 resource_pool->release_2d_texture(texnum);
940 frame->temp_textures.clear();
941 frame->ready_fence.reset();
942 frame->input_frames.clear();
947 mixer_thread = thread(&Mixer::thread_func, this);
948 audio_thread = thread(&Mixer::audio_thread_func, this);
954 audio_task_queue_changed.notify_one();
959 void Mixer::transition_clicked(int transition_num)
961 theme->transition_clicked(transition_num, pts());
964 void Mixer::channel_clicked(int preview_num)
966 theme->channel_clicked(preview_num);
969 void Mixer::start_mode_scanning(unsigned card_index)
971 assert(card_index < num_cards);
972 if (is_mode_scanning[card_index]) {
975 is_mode_scanning[card_index] = true;
976 mode_scanlist[card_index].clear();
977 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
978 mode_scanlist[card_index].push_back(mode.first);
980 assert(!mode_scanlist[card_index].empty());
981 mode_scanlist_index[card_index] = 0;
982 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
983 last_mode_scan_change[card_index] = steady_clock::now();
986 Mixer::OutputChannel::~OutputChannel()
988 if (has_current_frame) {
989 parent->release_display_frame(¤t_frame);
991 if (has_ready_frame) {
992 parent->release_display_frame(&ready_frame);
996 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
998 // Store this frame for display. Remove the ready frame if any
999 // (it was seemingly never used).
1001 unique_lock<mutex> lock(frame_mutex);
1002 if (has_ready_frame) {
1003 parent->release_display_frame(&ready_frame);
1005 ready_frame = frame;
1006 has_ready_frame = true;
1009 if (new_frame_ready_callback) {
1010 new_frame_ready_callback();
1013 // Reduce the number of callbacks by filtering duplicates. The reason
1014 // why we bother doing this is that Qt seemingly can get into a state
1015 // where its builds up an essentially unbounded queue of signals,
1016 // consuming more and more memory, and there's no good way of collapsing
1017 // user-defined signals or limiting the length of the queue.
1018 if (transition_names_updated_callback) {
1019 vector<string> transition_names = global_mixer->get_transition_names();
1020 bool changed = false;
1021 if (transition_names.size() != last_transition_names.size()) {
1024 for (unsigned i = 0; i < transition_names.size(); ++i) {
1025 if (transition_names[i] != last_transition_names[i]) {
1032 transition_names_updated_callback(transition_names);
1033 last_transition_names = transition_names;
1036 if (name_updated_callback) {
1037 string name = global_mixer->get_channel_name(channel);
1038 if (name != last_name) {
1039 name_updated_callback(name);
1043 if (color_updated_callback) {
1044 string color = global_mixer->get_channel_color(channel);
1045 if (color != last_color) {
1046 color_updated_callback(color);
1052 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1054 unique_lock<mutex> lock(frame_mutex);
1055 if (!has_current_frame && !has_ready_frame) {
1059 if (has_current_frame && has_ready_frame) {
1060 // We have a new ready frame. Toss the current one.
1061 parent->release_display_frame(¤t_frame);
1062 has_current_frame = false;
1064 if (has_ready_frame) {
1065 assert(!has_current_frame);
1066 current_frame = ready_frame;
1067 ready_frame.ready_fence.reset(); // Drop the refcount.
1068 ready_frame.input_frames.clear(); // Drop the refcounts.
1069 has_current_frame = true;
1070 has_ready_frame = false;
1073 *frame = current_frame;
1077 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1079 new_frame_ready_callback = callback;
1082 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1084 transition_names_updated_callback = callback;
1087 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1089 name_updated_callback = callback;
1092 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1094 color_updated_callback = callback;
1097 mutex RefCountedGLsync::fence_lock;