]> git.sesse.net Git - nageru/blobdiff - mixer.cpp
Allow adjusting the maximum input queue length by a command-line flag.
[nageru] / mixer.cpp
index 855a73fcaf5969a63a4f27c8f487cf7273b84151..c7a4659c8a66a486a85345310f897cdf49e601c4 100644 (file)
--- a/mixer.cpp
+++ b/mixer.cpp
@@ -10,6 +10,7 @@
 #include <movit/image_format.h>
 #include <movit/init.h>
 #include <movit/resource_pool.h>
+#include <pthread.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -77,25 +78,25 @@ void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced
 
 }  // namespace
 
-void QueueLengthPolicy::update_policy(int queue_length)
+void QueueLengthPolicy::update_policy(unsigned queue_length)
 {
-       if (queue_length < 0) {  // Starvation.
-               if (been_at_safe_point_since_last_starvation && safe_queue_length < 5) {
+       if (queue_length == 0) {  // Starvation.
+               if (been_at_safe_point_since_last_starvation && safe_queue_length < global_flags.max_input_queue_frames) {
                        ++safe_queue_length;
-                       fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frames\n",
+                       fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frame(s)\n",
                                card_index, safe_queue_length);
                }
                frames_with_at_least_one = 0;
                been_at_safe_point_since_last_starvation = false;
                return;
        }
-       if (queue_length > 0) {
-               if (queue_length >= int(safe_queue_length)) {
+       if (queue_length >= 1) {
+               if (queue_length >= safe_queue_length) {
                        been_at_safe_point_since_last_starvation = true;
                }
-               if (++frames_with_at_least_one >= 1000 && safe_queue_length > 0) {
+               if (++frames_with_at_least_one >= 1000 && safe_queue_length > 1) {
                        --safe_queue_length;
-                       fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frames\n",
+                       fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frame(s)\n",
                                card_index, safe_queue_length);
                        frames_with_at_least_one = 0;
                }
@@ -202,7 +203,8 @@ Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
                alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
        }
        if (global_flags.output_card != -1) {
-               set_output_card(global_flags.output_card);
+               desired_output_card_index = global_flags.output_card;
+               set_output_card_internal(global_flags.output_card);
        }
 }
 
@@ -247,7 +249,7 @@ void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool
        if (card->surface == nullptr) {
                card->surface = create_surface_with_same_format(mixer_surface);
        }
-       while (!card->new_frames.empty()) card->new_frames.pop();
+       while (!card->new_frames.empty()) card->new_frames.pop_front();
        card->last_timecode = -1;
        card->capture->configure_card();
 
@@ -259,11 +261,11 @@ void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool
        audio_mixer.trigger_state_changed_callback();
 }
 
-void Mixer::set_output_card(int card_index)
+void Mixer::set_output_card_internal(int card_index)
 {
-       if (card_index == output_card_index) {
-               return;
-       }
+       // We don't really need to take card_mutex, since we're in the mixer
+       // thread and don't mess with any queues (which is the only thing that happens
+       // from other threads), but it's probably the safest in the long run.
        unique_lock<mutex> lock(card_mutex);
        if (output_card_index != -1) {
                // Switch the old card from output to input.
@@ -281,18 +283,23 @@ void Mixer::set_output_card(int card_index)
                old_card->is_fake_capture = false;
                old_card->capture->start_bm_capture();
        }
-
-       CaptureCard *card = &cards[card_index];
-       bmusb::CaptureInterface *capture = card->capture.get();
-       lock.unlock();
-       capture->stop_dequeue_thread();
-       lock.lock();
-       card->parked_capture = move(card->capture);
-       bmusb::CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
-       configure_card(card_index, fake_capture, /*is_fake_capture=*/true, card->output.release());
-       card->queue_length_policy.reset(card_index);
-       card->capture->start_bm_capture();
-       card->output->start_output(bmdModeHD720p5994, pts_int);  // FIXME
+       if (card_index != -1) {
+               CaptureCard *card = &cards[card_index];
+               bmusb::CaptureInterface *capture = card->capture.get();
+               // TODO: DeckLinkCapture::stop_dequeue_thread can actually take
+               // several seconds to complete (blocking on DisableVideoInput);
+               // see if we can maybe do it asynchronously.
+               lock.unlock();
+               capture->stop_dequeue_thread();
+               lock.lock();
+               card->parked_capture = move(card->capture);
+               bmusb::CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
+               configure_card(card_index, fake_capture, /*is_fake_capture=*/true, card->output.release());
+               card->queue_length_policy.reset(card_index);
+               card->capture->start_bm_capture();
+               desired_output_video_mode = output_video_mode = card->output->pick_video_mode(desired_output_video_mode);
+               card->output->start_output(desired_output_video_mode, pts_int);
+       }
        output_card_index = card_index;
 }
 
@@ -377,7 +384,7 @@ void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
                } while (!success);
        }
 
-       audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length);
+       audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length, audio_frame.received_timestamp);
 
        // Done with the audio, so release it.
        if (audio_frame.owner) {
@@ -406,7 +413,7 @@ void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
                        new_frame.length = frame_length;
                        new_frame.interlaced = false;
                        new_frame.dropped_frames = dropped_frames;
-                       card->new_frames.push(move(new_frame));
+                       card->new_frames.push_back(move(new_frame));
                        card->new_frames_changed.notify_all();
                }
                return;
@@ -545,7 +552,7 @@ void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
                        new_frame.upload_func = upload_func;
                        new_frame.dropped_frames = dropped_frames;
                        new_frame.received_timestamp = video_frame.received_timestamp;  // Ignore the audio timestamp.
-                       card->new_frames.push(move(new_frame));
+                       card->new_frames.push_back(move(new_frame));
                        card->new_frames_changed.notify_all();
                }
        }
@@ -564,6 +571,8 @@ void Mixer::bm_hotplug_remove(unsigned card_index)
 
 void Mixer::thread_func()
 {
+       pthread_setname_np(pthread_self(), "Mixer_OpenGL");
+
        eglBindAPI(EGL_OPENGL_API);
        QOpenGLContext *context = create_context(mixer_surface);
        if (!make_current(context, mixer_surface)) {
@@ -586,6 +595,17 @@ void Mixer::thread_func()
        int stats_dropped_frames = 0;
 
        while (!should_quit) {
+               if (desired_output_card_index != output_card_index) {
+                       set_output_card_internal(desired_output_card_index);
+               }
+               if (output_card_index != -1 &&
+                   desired_output_video_mode != output_video_mode) {
+                       DeckLinkOutput *output = cards[output_card_index].output.get();
+                       output->end_output();
+                       desired_output_video_mode = output_video_mode = output->pick_video_mode(desired_output_video_mode);
+                       output->start_output(desired_output_video_mode, pts_int);
+               }
+
                CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
                bool has_new_frame[MAX_VIDEO_CARDS] = { false };
 
@@ -601,7 +621,7 @@ void Mixer::thread_func()
                }
 
                OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
-               schedule_audio_resampling_tasks(output_frame_info.dropped_frames, output_frame_info.num_samples, output_frame_info.frame_duration);
+               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);
                stats_dropped_frames += output_frame_info.dropped_frames;
 
                handle_hotplugged_cards();
@@ -719,6 +739,47 @@ bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card
        return (card_index == master_card_index);
 }
 
+void Mixer::trim_queue(CaptureCard *card, unsigned card_index)
+{
+       // Count the number of frames in the queue, including any frames
+       // we dropped. It's hard to know exactly how we should deal with
+       // dropped (corrupted) input frames; they don't help our goal of
+       // avoiding starvation, but they still add to the problem of latency.
+       // Since dropped frames is going to mean a bump in the signal anyway,
+       // we err on the side of having more stable latency instead.
+       unsigned queue_length = 0;
+       for (const CaptureCard::NewFrame &frame : card->new_frames) {
+               queue_length += frame.dropped_frames + 1;
+       }
+       card->queue_length_policy.update_policy(queue_length);
+
+       // If needed, drop frames until the queue is below the safe limit.
+       // We prefer to drop from the head, because all else being equal,
+       // we'd like more recent frames (less latency).
+       unsigned dropped_frames = 0;
+       while (queue_length > card->queue_length_policy.get_safe_queue_length()) {
+               assert(!card->new_frames.empty());
+               assert(queue_length > card->new_frames.front().dropped_frames);
+               queue_length -= card->new_frames.front().dropped_frames;
+
+               if (queue_length <= card->queue_length_policy.get_safe_queue_length()) {
+                       // No need to drop anything.
+                       break;
+               }
+
+               card->new_frames.pop_front();
+               card->new_frames_changed.notify_all();
+               --queue_length;
+               ++dropped_frames;
+       }
+
+       if (dropped_frames > 0) {
+               fprintf(stderr, "Card %u dropped %u frame(s) to keep latency down.\n",
+                       card_index, dropped_frames);
+       }
+}
+
+
 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])
 {
        OutputFrameInfo output_frame_info;
@@ -726,11 +787,12 @@ start:
        unique_lock<mutex> lock(card_mutex, defer_lock);
        if (master_card_is_output) {
                // Clocked to the output, so wait for it to be ready for the next frame.
-               cards[master_card_index].output->wait_for_frame(pts_int, &output_frame_info.dropped_frames, &output_frame_info.frame_duration);
+               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);
                lock.lock();
        } else {
                // Wait for the master card to have a new frame.
                // TODO: Add a timeout.
+               output_frame_info.is_preroll = false;
                lock.lock();
                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(); });
        }
@@ -745,30 +807,27 @@ start:
                goto start;
        }
 
+       if (!master_card_is_output) {
+               output_frame_info.frame_timestamp =
+                       cards[master_card_index].new_frames.front().received_timestamp;
+       }
+
        for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
                CaptureCard *card = &cards[card_index];
-               if (card->new_frames.empty()) {
-                       assert(!input_card_is_master_clock(card_index, master_card_index));
-                       card->queue_length_policy.update_policy(-1);
-                       continue;
-               }
-               new_frames[card_index] = move(card->new_frames.front());
-               has_new_frame[card_index] = true;
-               card->new_frames.pop();
-               card->new_frames_changed.notify_all();
-
                if (input_card_is_master_clock(card_index, master_card_index)) {
                        // We don't use the queue length policy for the master card,
                        // but we will if it stops being the master. Thus, clear out
                        // the policy in case we switch in the future.
                        card->queue_length_policy.reset(card_index);
+                       assert(!card->new_frames.empty());
                } else {
-                       // If we have excess frames compared to the policy for this card,
-                       // drop frames from the head.
-                       card->queue_length_policy.update_policy(card->new_frames.size());
-                       while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
-                               card->new_frames.pop();
-                       }
+                       trim_queue(card, card_index);
+               }
+               if (!card->new_frames.empty()) {
+                       new_frames[card_index] = move(card->new_frames.front());
+                       has_new_frame[card_index] = true;
+                       card->new_frames.pop_front();
+                       card->new_frames_changed.notify_all();
                }
        }
 
@@ -834,7 +893,7 @@ void Mixer::handle_hotplugged_cards()
 }
 
 
-void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame)
+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)
 {
        // Resample the audio as needed, including from previously dropped frames.
        assert(num_cards > 0);
@@ -855,8 +914,8 @@ void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_sam
                        // since dropped frames are expected to be rare, and it might be
                        // better to just wait until we have a slightly more normal situation).
                        unique_lock<mutex> lock(audio_mutex);
-                       bool adjust_rate = !dropped_frame;
-                       audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate});
+                       bool adjust_rate = !dropped_frame && !is_preroll;
+                       audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
                        audio_task_queue_changed.notify_one();
                }
                if (dropped_frame) {
@@ -931,6 +990,8 @@ void Mixer::render_one_frame(int64_t duration)
 
 void Mixer::audio_thread_func()
 {
+       pthread_setname_np(pthread_self(), "Mixer_Audio");
+
        while (!should_quit) {
                AudioTask task;
 
@@ -947,7 +1008,7 @@ void Mixer::audio_thread_func()
                ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
                        task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
                vector<float> samples_out = audio_mixer.get_output(
-                       double(task.pts_int) / TIMEBASE,
+                       task.frame_timestamp,
                        task.num_samples,
                        rate_adjustment_policy);
 
@@ -1014,6 +1075,13 @@ void Mixer::start_mode_scanning(unsigned card_index)
        last_mode_scan_change[card_index] = steady_clock::now();
 }
 
+map<uint32_t, bmusb::VideoMode> Mixer::get_available_output_video_modes() const
+{
+       assert(desired_output_card_index != -1);
+       unique_lock<mutex> lock(card_mutex);
+       return cards[desired_output_card_index].output->get_available_video_modes();
+}
+
 Mixer::OutputChannel::~OutputChannel()
 {
        if (has_current_frame) {