diff options
Diffstat (limited to 'pica-client/videodevice.cpp')
| -rw-r--r-- | pica-client/videodevice.cpp | 387 |
1 files changed, 269 insertions, 118 deletions
diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp index 2d15d45..0fcb01c 100644 --- a/pica-client/videodevice.cpp +++ b/pica-client/videodevice.cpp @@ -167,6 +167,23 @@ static const struct }; #endif +// What the frames given to an encoder are timestamped in: the 90 kHz clock of +// RTP video. Fine enough that a frame's timestamp says when the camera took it, +// which is what libvpx budgets its bits by - see encoderFollowsTimestamps(). +static const AVRational kEncoderTimeBase = { 1, 90000 }; + +// Whether an encoder takes the time between frames from their timestamps, as +// opposed to from the framerate it was opened with. libvpx does. x264 can, but +// not with tune=zerolatency, which turns its variable frame rate input off - +// turning it back on holds every frame back until the next one arrives, to +// learn its duration. Every hardware encoder FFmpeg has and libx265 go by the +// framerate as well. Those are reopened at the rate the camera delivers +// instead, see runTranscodeLoop(). +static bool encoderFollowsTimestamps(const QString &encoderName) +{ + return encoderName == QLatin1String("libvpx-vp9"); +} + static int videoEncoderIndex(const QString &codec) { for (unsigned int i = 0; i < sizeof(kVideoEncoders) / sizeof(kVideoEncoders[0]); i++) @@ -802,6 +819,7 @@ void VideoDevice::configureCapture(QString deviceName, int width, int height, in m_preferCompressed = preferCompressed; m_acceleration = acceleration; m_preset = CallQualityCustom; + m_hardwareEncoders.clear(); // Reports about the previous call's video say nothing about this one. takeReports(); @@ -813,9 +831,22 @@ void VideoDevice::limitCaptureSize(int width, int height) m_maxHeight = qMax(0, height); } -void VideoDevice::setQualityPreset(int preset) +void VideoDevice::setQualityPreset(int preset, QStringList hardwareEncoders) { + const QList<CallHardwareEncoder> builtIn = HardwareEncodersBuiltIn(); + m_preset = preset; + m_hardwareEncoders.clear(); + + // In the order given, which is the order of preference. + for (int n = 0; n < hardwareEncoders.size(); n++) + { + for (int i = 0; i < builtIn.size(); i++) + { + if (builtIn.at(i).encoder == hardwareEncoders.at(n)) + m_hardwareEncoders << builtIn.at(i); + } + } } void VideoDevice::reportReception(const CallReceptionReport &report) @@ -837,9 +868,18 @@ QList<CallReceptionReport> VideoDevice::takeReports() return reports; } -void VideoDevice::probeHardwareEncoders() +void VideoDevice::probeHardwareEncoders(QStringList encoders) { - ProbeHardwareEncoders(); + for (int i = 0; i < encoders.size(); i++) + { + const bool works = ProbeHardwareEncoder(encoders.at(i)); + + qDebug() << QString("Hardware encoder %1: %2").arg(encoders.at(i), + works ? QStringLiteral("works") + : QStringLiteral("does not work")); + emit hardwareEncoderProbed(encoders.at(i), works); + } + emit hardwareEncodersProbed(); } @@ -1317,7 +1357,7 @@ void VideoDevice::Capture() if (m_planned) { m_plan = callPlanVideo((CallQualityPreset)m_preset, CallCameraSizes(formats), - QSize(m_maxWidth, m_maxHeight), ProbeHardwareEncoders()); + QSize(m_maxWidth, m_maxHeight), m_hardwareEncoders); m_codec = m_plan.codec; m_acceleration = m_plan.acceleration; @@ -1636,7 +1676,7 @@ static AVCodecContext *openHwEncoder(const AVCodec *enc, AVBufferRef *hw_device_ enc_ctx->width = width; enc_ctx->height = height; enc_ctx->pix_fmt = hw_pix_fmt; - enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->time_base = kEncoderTimeBase; enc_ctx->framerate = frameRate; enc_ctx->bit_rate = bitrate; enc_ctx->gop_size = gopSize; @@ -1684,7 +1724,7 @@ static AVCodecContext *openMediaFoundationEncoder(const AVCodec *enc, int width, // What the hardware encoders take natively; YUV420P would be converted // inside the encoder instead of by the scaler we run anyway. enc_ctx->pix_fmt = AV_PIX_FMT_NV12; - enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->time_base = kEncoderTimeBase; enc_ctx->framerate = frameRate; enc_ctx->bit_rate = bitrate; enc_ctx->gop_size = gopSize; @@ -1985,7 +2025,7 @@ static bool openVideoEncoder(int encIdx, int acceleration, int width, int height enc_ctx->width = width; enc_ctx->height = height; enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P; - enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->time_base = kEncoderTimeBase; enc_ctx->framerate = frameRate; enc_ctx->bit_rate = bitrate; enc_ctx->gop_size = gopSize; @@ -2089,22 +2129,8 @@ out: return works; } -static QMutex s_probeMutex; -static bool s_probed = false; -static QList<CallHardwareEncoder> s_hardwareEncoders; - -QList<CallHardwareEncoder> VideoDevice::ProbeHardwareEncoders() +QList<CallHardwareEncoder> VideoDevice::HardwareEncodersBuiltIn() { - QMutexLocker locker(&s_probeMutex); - - if (s_probed) - return s_hardwareEncoders; - -#ifdef Q_OS_WIN - // Media Foundation will not work otherwise, see ComMultithreadedScope. - ComMultithreadedScope comApartment; -#endif - #if LIBAVFORMAT_VERSION_MAJOR < 58 avcodec_register_all(); #endif @@ -2115,11 +2141,7 @@ QList<CallHardwareEncoder> VideoDevice::ProbeHardwareEncoders() VideoAccelerationVaapi, VideoAccelerationD3d12va, VideoAccelerationMediaFoundation }; - // A common call size and rate: a GPU that cannot encode this is no use - // for a call either. - const AVRational frameRate = { 30, 1 }; - - qDebug() << "Finding out which hardware video encoders work - failures below are expected"; + QList<CallHardwareEncoder> encoders; for (unsigned int c = 0; c < sizeof(kVideoEncoders) / sizeof(kVideoEncoders[0]); c++) { @@ -2146,62 +2168,84 @@ QList<CallHardwareEncoder> VideoDevice::ProbeHardwareEncoders() #endif } - // Not even built in: nothing to try, and nothing worth a warning. if (!name || !avcodec_find_encoder_by_name(name)) continue; - VideoEncoderSession es; - QString error; + CallHardwareEncoder e; - if (!openVideoEncoder((int)c, kAccelerations[a], 1280, 720, frameRate, 2000000, 60, - false, &es, &error)) - continue; + e.codec = QLatin1String(kVideoEncoders[c].codec); + e.acceleration = kAccelerations[a]; + e.encoder = QLatin1String(name); + encoders << e; + } + } - if (encoderWorks(es.ctx)) - { - CallHardwareEncoder e; + return encoders; +} - e.codec = QLatin1String(kVideoEncoders[c].codec); - e.acceleration = kAccelerations[a]; - e.encoder = es.name; - s_hardwareEncoders << e; - } - else - { - qWarning() << QString("The %1 encoder opened but did not encode a frame").arg(es.name); - } +bool VideoDevice::ProbeHardwareEncoder(const QString &encoder) +{ +#ifdef Q_OS_WIN + // Media Foundation will not work otherwise, see ComMultithreadedScope. + ComMultithreadedScope comApartment; +#endif - closeVideoEncoder(&es); + const QList<CallHardwareEncoder> builtIn = HardwareEncodersBuiltIn(); + + for (int i = 0; i < builtIn.size(); i++) + { + if (builtIn.at(i).encoder != encoder) + continue; + + // A common call size and rate: a GPU that cannot encode this is no + // use for a call either. + const AVRational frameRate = { 30, 1 }; + VideoEncoderSession es; + QString error; + + if (!openVideoEncoder(videoEncoderIndex(builtIn.at(i).codec), builtIn.at(i).acceleration, + 1280, 720, frameRate, 2000000, 60, false, &es, &error)) + { + qWarning() << QString("Probing %1: %2").arg(encoder, error); + return false; } - } - QStringList names; + const bool works = encoderWorks(es.ctx); - for (int i = 0; i < s_hardwareEncoders.size(); i++) - names << s_hardwareEncoders.at(i).encoder; + if (!works) + qWarning() << QString("Probing %1: opened, but did not encode a frame").arg(encoder); - qDebug() << "Hardware video encoders that work here:" - << (names.isEmpty() ? QStringLiteral("none") : names.join(QLatin1String(", "))); + closeVideoEncoder(&es); - s_probed = true; + return works; + } - return s_hardwareEncoders; + qWarning() << QString("Probing %1: not in this build").arg(encoder); + return false; } -bool VideoDevice::HardwareEncodersProbed(QList<CallHardwareEncoder> *encoders) +QList<CallHardwareEncoder> VideoDevice::PresetHardwareEncoders(int encodingAcceleration) { - // Not waiting is the point: a probe that is running holds the lock. - if (!s_probeMutex.tryLock()) - return false; + const QList<CallHardwareEncoder> builtIn = HardwareEncodersBuiltIn(); + QStringList working; + + for (int i = 0; i < builtIn.size(); i++) + { + if (CallSettings::loadHardwareEncoderProbe(builtIn.at(i).encoder) == HardwareEncoderWorks) + working << builtIn.at(i).encoder; + } - const bool probed = s_probed; + return callUsableHardwareEncoders(builtIn, working, encodingAcceleration); +} - if (probed && encoders) - *encoders = s_hardwareEncoders; +QStringList VideoDevice::HardwareEncoderNames(const QList<CallHardwareEncoder> &encoders) +{ + QStringList names; - s_probeMutex.unlock(); + for (int i = 0; i < encoders.size(); i++) + names << encoders.at(i).encoder; - return probed; + return names; } QList<CallCameraSize> VideoDevice::CallCameraSizes(const QList<VideoCaptureFormat> &formats) @@ -2220,10 +2264,6 @@ QList<CallCameraSize> VideoDevice::CallCameraSizes(const QList<VideoCaptureForma return sizes; } -// CallQualityAdaptive: how much a bitrate change has to amount to before an -// encoder that cannot take one while running is reopened for it - each reopen -// starts with a keyframe - and how far apart reopens for increases are kept. -// Decreases are not held back: they are what stops the loss. // The size Preview() asks the camera for: the wanted one if the camera lists // it, otherwise the largest it lists that is no bigger, or failing that the // smallest it has. A camera that could not be enumerated is asked for the @@ -2482,9 +2522,60 @@ void VideoDevice::Preview() avformat_close_input(&ifmt_ctx); } +// CallQualityAdaptive: how much a bitrate change has to amount to before an +// encoder that cannot take one while running is reopened for it - each reopen +// starts with a keyframe - and how far apart reopens for increases are kept. +// Decreases are not held back: they are what stops the loss. static const double kReopenBitrateStep = 0.15; static const int kReopenIntervalMs = 5000; +// An encoder that goes by the framerate it was opened with is reopened at the +// rate the camera actually delivers once that is this far off, measured over +// kFrameRateWindowUs, and no more often than every kFrameRateReopenIntervalMs: +// a camera in a dim room halves its rate to expose longer, and a hardware +// encoder still budgeting for the full rate would send half the bitrate. +static const double kFrameRateReopenStep = 0.2; +static const int64_t kFrameRateWindowUs = 3000000; +static const int kFrameRateReopenIntervalMs = 10000; + +// When each picture was taken, in microseconds from the first: the camera's +// own timestamps where it gives them, our clock where it does not or where +// they jump - backwards, or by more than a second, as a camera stamping from +// the wall clock does when the clock is set. +class CaptureClock +{ +public: + CaptureClock() : m_started(false), m_lastCamera(AV_NOPTS_VALUE), m_lastWall(0), m_now(0) {} + + int64_t next(int64_t cameraTimestamp, AVRational cameraTimeBase, int64_t wallUs) + { + if (m_started) + { + int64_t delta = -1; + + if (cameraTimestamp != AV_NOPTS_VALUE && m_lastCamera != AV_NOPTS_VALUE) + delta = av_rescale_q(cameraTimestamp - m_lastCamera, cameraTimeBase, AVRational{ 1, 1000000 }); + + if (delta <= 0 || delta > 1000000) + delta = wallUs - m_lastWall; + + m_now += qMax<int64_t>(delta, 0); + } + + m_started = true; + m_lastCamera = cameraTimestamp; + m_lastWall = wallUs; + + return m_now; + } + +private: + bool m_started; + int64_t m_lastCamera; + int64_t m_lastWall; + int64_t m_now; +}; + void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) { const AVRational frameRate = cameraFrameRate(in_st, m_frameRate); @@ -2498,7 +2589,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // packet waits this long for a picture, so it is a latency figure as much // as a bandwidth one - hence deriving it from the real rate rather than // from a fixed frame count. - const int gopSize = qMax(1, (int)av_q2d(frameRate) * 2); + auto gopSizeFor = [](AVRational rate) { return qMax(1, (int)(av_q2d(rate) * 2)); }; // What gets encoded: the camera's picture as it is, or for a preset that // sends less than the camera captures, scaled down. @@ -2529,7 +2620,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) QString encoderError; if (!openVideoEncoder(encIdx, m_acceleration, encodeSize.width(), encodeSize.height(), - frameRate, m_bitrate, gopSize, true, &encoder, &encoderError)) + frameRate, m_bitrate, gopSizeFor(frameRate), true, &encoder, &encoderError)) { qWarning() << encoderError; emit errorOccurred(encoderError); @@ -2585,6 +2676,16 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) int64_t currentBitrate = m_bitrate; qint64 lastReopen = 0; + // The rate the encoder was opened for, and what the camera delivers: + // frames counted since rateWindowStart, in captureClock's time. The first + // window is not gone by: a camera takes a moment to settle into its rate. + AVRational encoderRate = frameRate; + CaptureClock captureClock; + int64_t rateWindowStart = -1; + int rateWindowFrames = 0; + bool rateSettled = false; + int64_t lastPts = AV_NOPTS_VALUE; + clock.start(); if (adaptive) @@ -2594,7 +2695,6 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) AVPacket *in_pkt = av_packet_alloc(); AVFrame *cam_frame = av_frame_alloc(); AVPacket *out_pkt = av_packet_alloc(); - int64_t pts = 0; bool loggedReadError = false; bool loggedScaleError = false; bool loggedEncodeError = false; @@ -2621,6 +2721,42 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) while (avcodec_receive_frame(dec_ctx, cam_frame) == 0) { + const int64_t captureUs = captureClock.next(cam_frame->best_effort_timestamp, in_st->time_base, + clock.nsecsElapsed() / 1000); + + // What the encoder is to be reopened with, if anything changes. + QSize wantedSize = encodeSize; + int64_t wantedBitrate = currentBitrate; + AVRational wantedRate = encoderRate; + bool reopen = false; + + if (rateWindowStart < 0) + rateWindowStart = captureUs; + else + rateWindowFrames++; + + if (rateWindowFrames > 0 && captureUs - rateWindowStart >= kFrameRateWindowUs) + { + const double measured = rateWindowFrames * 1000000.0 / (captureUs - rateWindowStart); + + rateWindowStart = captureUs; + rateWindowFrames = 0; + + if (rateSettled && !encoderFollowsTimestamps(encoder.name) && + qAbs(measured / av_q2d(encoderRate) - 1.0) > kFrameRateReopenStep && + (lastReopen == 0 || clock.elapsed() - lastReopen >= kFrameRateReopenIntervalMs)) + { + wantedRate = AVRational{ qMax(1, qRound(measured)), 1 }; + reopen = av_cmp_q(wantedRate, encoderRate) != 0; + + if (reopen) + qDebug() << QString("The camera delivers %1 fps, reopening %2 for that instead of %3") + .arg(measured, 0, 'f', 1).arg(encoder.name).arg(av_q2d(encoderRate)); + } + + rateSettled = true; + } + // Between frames, so that a new encoder starts with a whole one. if (adaptive) { @@ -2636,11 +2772,13 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) m_fragmentsSent = 0; } - const QSize wantedSize = rate.size(); - const int64_t wantedBitrate = (int64_t)rate.bitrateKbps() * 1000; - bool reopen = wantedSize != encodeSize; + wantedSize = rate.size(); + wantedBitrate = (int64_t)rate.bitrateKbps() * 1000; - if (!reopen && wantedBitrate != currentBitrate) + if (wantedSize != encodeSize) + reopen = true; + + if (wantedBitrate != currentBitrate) { const double ratio = (double)wantedBitrate / currentBitrate; @@ -2659,68 +2797,69 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) reopen = true; } } + } - // A failed reopen is not retried for every frame. - if (reopen && lastReopen != 0 && clock.elapsed() - lastReopen < 1000) - reopen = false; + // A failed reopen is not retried for every frame. + if (reopen && lastReopen != 0 && clock.elapsed() - lastReopen < 1000) + reopen = false; - if (reopen) - { - VideoEncoderSession next; - QString error; + if (reopen) + { + VideoEncoderSession next; + QString error; - lastReopen = clock.elapsed(); + lastReopen = clock.elapsed(); - if (openVideoEncoder(encIdx, m_acceleration, wantedSize.width(), wantedSize.height(), - frameRate, wantedBitrate, gopSize, true, &next, &error)) - { - AVFrame *next_frame = allocEncoderFrame(next.ctx); + if (openVideoEncoder(encIdx, m_acceleration, wantedSize.width(), wantedSize.height(), + wantedRate, wantedBitrate, gopSizeFor(wantedRate), true, &next, &error)) + { + AVFrame *next_frame = allocEncoderFrame(next.ctx); - if (next_frame) + if (next_frame) + { + // What the old encoder still holds goes out first; a + // low latency one holds nothing. + if (avcodec_send_frame(encoder.ctx, nullptr) == 0) { - // What the old encoder still holds goes out - // first; a low latency one holds nothing. - if (avcodec_send_frame(encoder.ctx, nullptr) == 0) + while (avcodec_receive_packet(encoder.ctx, out_pkt) == 0) { - while (avcodec_receive_packet(encoder.ctx, out_pkt) == 0) - { - emitFragments(out_pkt->data, out_pkt->size); - av_packet_unref(out_pkt); - } + emitFragments(out_pkt->data, out_pkt->size); + av_packet_unref(out_pkt); } + } - closeVideoEncoder(&encoder); - av_frame_free(&enc_frame); - - encoder = next; - enc_frame = next_frame; - currentBitrate = wantedBitrate; + closeVideoEncoder(&encoder); + av_frame_free(&enc_frame); - // The scaler targets the encoder's size and format. - if (sws) - { - sws_freeContext(sws); - sws = nullptr; - } + encoder = next; + enc_frame = next_frame; + currentBitrate = wantedBitrate; + encoderRate = wantedRate; - if (wantedSize != encodeSize) - { - encodeSize = wantedSize; - emit streamChanged(codecName, encodeSize.width(), encodeSize.height()); - } + // The scaler targets the encoder's size and format. + if (sws) + { + sws_freeContext(sws); + sws = nullptr; } - else + + if (wantedSize != encodeSize) { - closeVideoEncoder(&next); - qWarning() << "Could not allocate encoder frame, keeping the encoder as it is"; + encodeSize = wantedSize; + emit streamChanged(codecName, encodeSize.width(), encodeSize.height()); } } else { - qWarning() << QString("Could not reopen the video encoder (%1), keeping it as it is") - .arg(error); + closeVideoEncoder(&next); + qWarning() << "Could not allocate encoder frame, keeping the encoder as it is"; } } + else + { + qWarning() << QString("Could not reopen the video encoder (%1), keeping it as it is") + .arg(error); + } } AVCodecContext *enc_ctx = encoder.ctx; @@ -2771,7 +2910,19 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) enc_frame->data, enc_frame->linesize); av_frame_unref(cam_frame); - enc_frame->pts = pts++; + // When the camera took the picture rather than a frame count: a + // camera that delivers fewer frames than it said it would would + // otherwise have each one budgeted for the time of a frame it + // skipped, by the encoders that go by timestamps - see + // encoderFollowsTimestamps(). A new encoder could start over, but + // carrying on from where the last one was is no harm. + int64_t pts = av_rescale_q(captureUs, AVRational{ 1, 1000000 }, enc_ctx->time_base); + + if (lastPts != AV_NOPTS_VALUE && pts <= lastPts) + pts = lastPts + 1; + + lastPts = pts; + enc_frame->pts = pts; // What actually goes to the encoder: the staging frame itself, or // a GPU surface holding a copy of it for an encoder that draws on |
