]> git.sesse.net Git - nageru/blobdiff - mixer.cpp
Release Nageru 1.7.2.
[nageru] / mixer.cpp
index f45880d321be6d2a1c17c5a61b7ba0babc28e846..7a3f437d6ec745048c57be3283005cbf94597937 100644 (file)
--- a/mixer.cpp
+++ b/mixer.cpp
@@ -33,6 +33,9 @@
 #include "basic_stats.h"
 #include "bmusb/bmusb.h"
 #include "bmusb/fake_capture.h"
+#ifdef HAVE_CEF
+#include "cef_capture.h"
+#endif
 #include "chroma_subsampler.h"
 #include "context.h"
 #include "decklink_capture.h"
 #include "v210_converter.h"
 #include "video_encoder.h"
 
+#undef Status
+#include <google/protobuf/util/json_util.h>
+#include "json.pb.h"
+
 class IDeckLink;
 class QOpenGLContext;
 
@@ -150,6 +157,8 @@ void ensure_texture_resolution(PBOFrameAllocator::Userdata *userdata, unsigned f
                        }
                        check_error();
                        break;
+               default:
+                       assert(false);
                }
                userdata->last_width[field] = width;
                userdata->last_height[field] = height;
@@ -239,7 +248,7 @@ double JitterHistory::estimate_max_jitter() const
        if (percentile <= 0.5) {
                return *next(orders.begin(), elem_idx) * multiplier;
        } else {
-               return *prev(orders.end(), elem_idx + 1) * multiplier;
+               return *prev(orders.end(), orders.size() - elem_idx) * multiplier;
        }
 }
 
@@ -295,8 +304,7 @@ Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
          num_cards(num_cards),
          mixer_surface(create_surface(format)),
          h264_encoder_surface(create_surface(format)),
-         decklink_output_surface(create_surface(format)),
-         audio_mixer(num_cards)
+         decklink_output_surface(create_surface(format))
 {
        memcpy(ycbcr_interpretation, global_flags.ycbcr_interpretation, sizeof(ycbcr_interpretation));
        CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
@@ -352,6 +360,17 @@ Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
        // Must be instantiated after VideoEncoder has initialized global_flags.use_zerocopy.
        theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get(), num_cards));
 
+       // Must be instantiated after the theme, as the theme decides the number of FFmpeg inputs.
+       std::vector<FFmpegCapture *> video_inputs = theme->get_video_inputs();
+       audio_mixer.reset(new AudioMixer(num_cards, video_inputs.size()));
+
+       httpd.add_endpoint("/channels", bind(&Mixer::get_channels_json, this), HTTPD::ALLOW_ALL_ORIGINS);
+       for (int channel_idx = 2; channel_idx < theme->get_num_channels(); ++channel_idx) {
+               char url[256];
+               snprintf(url, sizeof(url), "/channels/%d/color", channel_idx);
+               httpd.add_endpoint(url, bind(&Mixer::get_channel_color_http, this, unsigned(channel_idx)), HTTPD::ALLOW_ALL_ORIGINS);
+       }
+
        // Start listening for clients only once VideoEncoder has written its header, if any.
        httpd.start(global_flags.http_port);
 
@@ -405,7 +424,6 @@ Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
 
        // Initialize all video inputs the theme asked for. Note that these are
        // all put _after_ the regular cards, which stop at <num_cards> - 1.
-       std::vector<FFmpegCapture *> video_inputs = theme->get_video_inputs();
        for (unsigned video_card_index = 0; video_card_index < video_inputs.size(); ++card_index, ++video_card_index) {
                if (card_index >= MAX_VIDEO_CARDS) {
                        fprintf(stderr, "ERROR: Not enough card slots available for the videos the theme requested.\n");
@@ -416,10 +434,24 @@ Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
        }
        num_video_inputs = video_inputs.size();
 
+#ifdef HAVE_CEF
+       // Same, for HTML inputs.
+       std::vector<CEFCapture *> html_inputs = theme->get_html_inputs();
+       for (unsigned html_card_index = 0; html_card_index < html_inputs.size(); ++card_index, ++html_card_index) {
+               if (card_index >= MAX_VIDEO_CARDS) {
+                       fprintf(stderr, "ERROR: Not enough card slots available for the HTML inputs the theme requested.\n");
+                       exit(1);
+               }
+               configure_card(card_index, html_inputs[html_card_index], CardType::CEF_INPUT, /*output=*/nullptr);
+               html_inputs[html_card_index]->set_card_index(card_index);
+       }
+       num_html_inputs = html_inputs.size();
+#endif
+
        BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
        BMUSBCapture::start_bm_thread();
 
-       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs; ++card_index) {
+       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs + num_html_inputs; ++card_index) {
                cards[card_index].queue_length_policy.reset(card_index);
        }
 
@@ -467,9 +499,10 @@ Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
 
 Mixer::~Mixer()
 {
+       httpd.stop();
        BMUSBCapture::stop_bm_thread();
 
-       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs; ++card_index) {
+       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs + num_html_inputs; ++card_index) {
                {
                        unique_lock<mutex> lock(card_mutex);
                        cards[card_index].should_quit = true;  // Unblock thread.
@@ -495,6 +528,8 @@ void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, CardT
        }
        card->capture.reset(capture);
        card->is_fake_capture = (card_type == CardType::FAKE_CAPTURE);
+       card->is_cef_capture = (card_type == CardType::CEF_INPUT);
+       card->may_have_dropped_last_frame = false;
        card->type = card_type;
        if (card->output.get() != output) {
                card->output.reset(output);
@@ -503,6 +538,8 @@ void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, CardT
        PixelFormat pixel_format;
        if (card_type == CardType::FFMPEG_INPUT) {
                pixel_format = capture->get_current_pixel_format();
+       } else if (card_type == CardType::CEF_INPUT) {
+               pixel_format = PixelFormat_8BitBGRA;
        } else if (global_flags.ten_bit_input) {
                pixel_format = PixelFormat_10BitYCbCr;
        } else {
@@ -524,10 +561,15 @@ void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, CardT
 
        // NOTE: start_bm_capture() happens in thread_func().
 
-       DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
-       audio_mixer.reset_resampler(device);
-       audio_mixer.set_display_name(device, card->capture->get_description());
-       audio_mixer.trigger_state_changed_callback();
+       DeviceSpec device;
+       if (card_type == CardType::FFMPEG_INPUT) {
+               device = DeviceSpec{InputSourceType::FFMPEG_VIDEO_INPUT, card_index - num_cards};
+       } else {
+               device = DeviceSpec{InputSourceType::CAPTURE_CARD, card_index};
+       }
+       audio_mixer->reset_resampler(device);
+       audio_mixer->set_display_name(device, card->capture->get_description());
+       audio_mixer->trigger_state_changed_callback();
 
        // Unregister old metrics, if any.
        if (!card->labels.empty()) {
@@ -567,6 +609,9 @@ void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, CardT
        case CardType::FFMPEG_INPUT:
                labels.emplace_back("cardtype", "ffmpeg");
                break;
+       case CardType::CEF_INPUT:
+               labels.emplace_back("cardtype", "cef");
+               break;
        default:
                assert(false);
        }
@@ -651,7 +696,12 @@ void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
                      FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
                     FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
 {
-       DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
+       DeviceSpec device;
+       if (card_index >= num_cards) {
+               device = DeviceSpec{InputSourceType::FFMPEG_VIDEO_INPUT, card_index - num_cards};
+       } else {
+               device = DeviceSpec{InputSourceType::CAPTURE_CARD, card_index};
+       }
        CaptureCard *card = &cards[card_index];
 
        ++card->metric_input_received_frames;
@@ -686,9 +736,9 @@ void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
        assert(frame_length > 0);
 
        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;
-       if (num_samples > OUTPUT_FREQUENCY / 10) {
-               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",
-                       card_index, int(audio_frame.len), int(audio_offset),
+       if (num_samples > OUTPUT_FREQUENCY / 10 && card->type != CardType::FFMPEG_INPUT) {
+               printf("%s: Dropping frame with implausible audio length (len=%d, offset=%d) [timecode=0x%04x video_len=%d video_offset=%d video_format=%x)\n",
+                       spec_to_string(device).c_str(), int(audio_frame.len), int(audio_offset),
                        timecode, int(video_frame.len), int(video_offset), video_format.id);
                if (video_frame.owner) {
                        video_frame.owner->release_frame(video_frame);
@@ -709,25 +759,25 @@ void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
        const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
 
        if (dropped_frames > MAX_FPS * 2) {
-               fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
-                       card_index, card->last_timecode, timecode);
-               audio_mixer.reset_resampler(device);
+               fprintf(stderr, "%s lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
+                       spec_to_string(device).c_str(), card->last_timecode, timecode);
+               audio_mixer->reset_resampler(device);
                dropped_frames = 0;
                ++card->metric_input_resets;
        } else if (dropped_frames > 0) {
                // Insert silence as needed.
-               fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
-                       card_index, dropped_frames, timecode);
+               fprintf(stderr, "%s dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
+                       spec_to_string(device).c_str(), dropped_frames, timecode);
                card->metric_input_dropped_frames_error += dropped_frames;
 
                bool success;
                do {
-                       success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
+                       success = audio_mixer->add_silence(device, silence_samples, dropped_frames, frame_length);
                } while (!success);
        }
 
        if (num_samples > 0) {
-               audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length, audio_frame.received_timestamp);
+               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.
@@ -762,8 +812,8 @@ void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
        if (video_frame.len - video_offset == 0 ||
            video_frame.len - video_offset != expected_length) {
                if (video_frame.len != 0) {
-                       printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
-                               card_index, video_frame.len - video_offset, expected_length);
+                       printf("%s: Dropping video frame with wrong length (%ld; expected %ld)\n",
+                               spec_to_string(device).c_str(), video_frame.len - video_offset, expected_length);
                }
                if (video_frame.owner) {
                        video_frame.owner->release_frame(video_frame);
@@ -907,6 +957,7 @@ void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
                        new_frame.received_timestamp = video_frame.received_timestamp;  // Ignore the audio timestamp.
                        card->new_frames.push_back(move(new_frame));
                        card->jitter_history.frame_arrived(video_frame.received_timestamp, frame_length, dropped_frames);
+                       card->may_have_dropped_last_frame = false;
                }
                card->new_frames_changed.notify_all();
        }
@@ -936,13 +987,13 @@ void Mixer::thread_func()
 
        // Start the actual capture. (We don't want to do it before we're actually ready
        // to process output frames.)
-       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs; ++card_index) {
+       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs + num_html_inputs; ++card_index) {
                if (int(card_index) != output_card_index) {
                        cards[card_index].capture->start_bm_capture();
                }
        }
 
-       BasicStats basic_stats(/*verbose=*/true);
+       BasicStats basic_stats(/*verbose=*/true, /*use_opengl=*/true);
        int stats_dropped_frames = 0;
 
        while (!should_quit) {
@@ -968,7 +1019,7 @@ void Mixer::thread_func()
                } else {
                        master_card_is_output = false;
                        master_card_index = theme->map_signal(master_clock_channel);
-                       assert(master_card_index < num_cards);
+                       assert(master_card_index < num_cards + num_video_inputs);
                }
 
                OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
@@ -977,7 +1028,7 @@ void Mixer::thread_func()
 
                handle_hotplugged_cards();
 
-               for (unsigned card_index = 0; card_index < num_cards + num_video_inputs; ++card_index) {
+               for (unsigned card_index = 0; card_index < num_cards + num_video_inputs + num_html_inputs; ++card_index) {
                        if (card_index == master_card_index || !has_new_frame[card_index]) {
                                continue;
                        }
@@ -998,7 +1049,7 @@ void Mixer::thread_func()
                        continue;
                }
 
-               for (unsigned card_index = 0; card_index < num_cards + num_video_inputs; ++card_index) {
+               for (unsigned card_index = 0; card_index < num_cards + num_video_inputs + num_html_inputs; ++card_index) {
                        if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
                                continue;
 
@@ -1016,7 +1067,11 @@ void Mixer::thread_func()
 
                int64_t frame_duration = output_frame_info.frame_duration;
                render_one_frame(frame_duration);
-               ++frame_num;
+               {
+                       lock_guard<mutex> lock(frame_num_mutex);
+                       ++frame_num;
+               }
+               frame_num_updated.notify_all();
                pts_int += frame_duration;
 
                basic_stats.update(frame_num, stats_dropped_frames);
@@ -1083,6 +1138,10 @@ void Mixer::trim_queue(CaptureCard *card, size_t safe_queue_length)
                card->new_frames_changed.notify_all();
                --queue_length;
                ++dropped_frames;
+
+               if (queue_length == 0 && card->is_cef_capture) {
+                       card->may_have_dropped_last_frame = true;
+               }
        }
 
        card->metric_input_dropped_frames_jitter += dropped_frames;
@@ -1096,6 +1155,24 @@ void Mixer::trim_queue(CaptureCard *card, size_t safe_queue_length)
 #endif
 }
 
+pair<string, string> Mixer::get_channels_json()
+{
+       Channels ret;
+       for (int channel_idx = 2; channel_idx < theme->get_num_channels(); ++channel_idx) {
+               Channel *channel = ret.add_channel();
+               channel->set_index(channel_idx);
+               channel->set_name(theme->get_channel_name(channel_idx));
+               channel->set_color(theme->get_channel_color(channel_idx));
+       }
+       string contents;
+       google::protobuf::util::MessageToJsonString(ret, &contents);  // Ignore any errors.
+       return make_pair(contents, "text/json");
+}
+
+pair<string, string> Mixer::get_channel_color_http(unsigned channel_idx)
+{
+       return make_pair(theme->get_channel_color(channel_idx), "text/plain");
+}
 
 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])
 {
@@ -1125,10 +1202,20 @@ start:
                goto start;
        }
 
-       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs; ++card_index) {
+       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs + num_html_inputs; ++card_index) {
                CaptureCard *card = &cards[card_index];
                if (card->new_frames.empty()) {  // Starvation.
                        ++card->metric_input_duped_frames;
+#ifdef HAVE_CEF
+                       if (card->is_cef_capture && card->may_have_dropped_last_frame) {
+                               // Unlike other sources, CEF is not guaranteed to send us a steady
+                               // stream of frames, so we'll have to ask it to repaint the frame
+                               // we dropped. (may_have_dropped_last_frame is set whenever we
+                               // trim the queue completely away, and cleared when we actually
+                               // get a new frame.)
+                               ((CEFCapture *)card->capture.get())->request_new_frame();
+                       }
+#endif
                } else {
                        new_frames[card_index] = move(card->new_frames.front());
                        has_new_frame[card_index] = true;
@@ -1147,7 +1234,7 @@ start:
                output_jitter_history.frame_arrived(output_frame_info.frame_timestamp, output_frame_info.frame_duration, output_frame_info.dropped_frames);
        }
 
-       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs; ++card_index) {
+       for (unsigned card_index = 0; card_index < num_cards + num_video_inputs + num_html_inputs; ++card_index) {
                CaptureCard *card = &cards[card_index];
                if (has_new_frame[card_index] &&
                    !input_card_is_master_clock(card_index, master_card_index) &&
@@ -1280,12 +1367,6 @@ void Mixer::render_one_frame(int64_t duration)
        theme_main_chain.setup_chain();
        //theme_main_chain.chain->enable_phase_timing(true);
 
-       // The theme can't (or at least shouldn't!) call connect_signal() on
-       // each FFmpeg input, so we'll do it here.
-       for (const pair<LiveInputWrapper *, FFmpegCapture *> &conn : theme->get_signal_connections()) {
-               conn.first->connect_signal_raw(conn.second->get_card_index(), input_state);
-       }
-
        // If HDMI/SDI output is active and the user has requested auto mode,
        // its mode overrides the existing Y'CbCr setting for the chain.
        YCbCrLumaCoefficients ycbcr_output_coefficients;
@@ -1390,18 +1471,18 @@ void Mixer::render_one_frame(int64_t duration)
        live_frame.ready_fence = fence;
        live_frame.input_frames = {};
        live_frame.temp_textures = { y_display_tex, cbcr_display_tex };
-       output_channel[OUTPUT_LIVE].output_frame(live_frame);
+       output_channel[OUTPUT_LIVE].output_frame(move(live_frame));
 
        // Set up preview and any additional channels.
        for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
                DisplayFrame display_frame;
                Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state);  // FIXME: dimensions
-               display_frame.chain = chain.chain;
-               display_frame.setup_chain = chain.setup_chain;
+               display_frame.chain = move(chain.chain);
+               display_frame.setup_chain = move(chain.setup_chain);
                display_frame.ready_fence = fence;
-               display_frame.input_frames = chain.input_frames;
+               display_frame.input_frames = move(chain.input_frames);
                display_frame.temp_textures = {};
-               output_channel[i].output_frame(display_frame);
+               output_channel[i].output_frame(move(display_frame));
        }
 }
 
@@ -1424,7 +1505,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(
+               vector<float> samples_out = audio_mixer->get_output(
                        task.frame_timestamp,
                        task.num_samples,
                        rate_adjustment_policy);
@@ -1511,6 +1592,25 @@ map<uint32_t, VideoMode> Mixer::get_available_output_video_modes() const
        return cards[desired_output_card_index].output->get_available_video_modes();
 }
 
+string Mixer::get_ffmpeg_filename(unsigned card_index) const
+{
+       assert(card_index >= num_cards && card_index < num_cards + num_video_inputs);
+       return ((FFmpegCapture *)(cards[card_index].capture.get()))->get_filename();
+}
+
+void Mixer::set_ffmpeg_filename(unsigned card_index, const string &filename) {
+       assert(card_index >= num_cards && card_index < num_cards + num_video_inputs);
+       ((FFmpegCapture *)(cards[card_index].capture.get()))->change_filename(filename);
+}
+
+void Mixer::wait_for_next_frame()
+{
+       unique_lock<mutex> lock(frame_num_mutex);
+       unsigned old_frame_num = frame_num;
+       frame_num_updated.wait_for(lock, seconds(1),  // Timeout is just in case.
+               [old_frame_num, this]{ return this->frame_num > old_frame_num; });
+}
+
 Mixer::OutputChannel::~OutputChannel()
 {
        if (has_current_frame) {
@@ -1521,7 +1621,7 @@ Mixer::OutputChannel::~OutputChannel()
        }
 }
 
-void Mixer::OutputChannel::output_frame(DisplayFrame frame)
+void Mixer::OutputChannel::output_frame(DisplayFrame &&frame)
 {
        // Store this frame for display. Remove the ready frame if any
        // (it was seemingly never used).
@@ -1530,7 +1630,7 @@ void Mixer::OutputChannel::output_frame(DisplayFrame frame)
                if (has_ready_frame) {
                        parent->release_display_frame(&ready_frame);
                }
-               ready_frame = frame;
+               ready_frame = move(frame);
                has_ready_frame = true;
 
                // Call the callbacks under the mutex (they should be short),
@@ -1593,7 +1693,7 @@ bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
        }
        if (has_ready_frame) {
                assert(!has_current_frame);
-               current_frame = ready_frame;
+               current_frame = move(ready_frame);
                ready_frame.ready_fence.reset();  // Drop the refcount.
                ready_frame.input_frames.clear();  // Drop the refcounts.
                has_current_frame = true;