diff options
Diffstat (limited to 'pica-client/videodevice.cpp')
| -rw-r--r-- | pica-client/videodevice.cpp | 673 |
1 files changed, 562 insertions, 111 deletions
diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp index f7d080c..ab6f08e 100644 --- a/pica-client/videodevice.cpp +++ b/pica-client/videodevice.cpp @@ -25,6 +25,7 @@ #include <QFile> #include <QDebug> #include <QMutexLocker> +#include <QElapsedTimer> #include <QMap> #include <QPair> #include <cstring> @@ -731,7 +732,8 @@ VideoDevice::VideoDevice(QObject *parent) : QObject(parent), m_width(kDefaultCaptureWidth), m_height(kDefaultCaptureHeight), m_maxWidth(0), m_maxHeight(0), m_frameRate(kDefaultCaptureFrameRate), m_bitrate(kDefaultVideoBitrateKbps * 1000), - m_preferCompressed(false), + m_preferCompressed(false), m_preset(CallQualityCustom), m_planned(false), + m_fragmentsSent(0), m_acceleration(0), m_useVaapiRender(false), m_reconfigure(0), m_pendingWidth(0), m_pendingHeight(0), m_pendingAcceleration(0), m_pendingUseVaapiRender(false), @@ -799,6 +801,10 @@ void VideoDevice::configureCapture(QString deviceName, int width, int height, in m_bitrate = bitrate > 0 ? bitrate : kDefaultVideoBitrateKbps * 1000; m_preferCompressed = preferCompressed; m_acceleration = acceleration; + m_preset = CallQualityCustom; + + // Reports about the previous call's video say nothing about this one. + takeReports(); } void VideoDevice::limitCaptureSize(int width, int height) @@ -807,6 +813,36 @@ void VideoDevice::limitCaptureSize(int width, int height) m_maxHeight = qMax(0, height); } +void VideoDevice::setQualityPreset(int preset) +{ + m_preset = preset; +} + +void VideoDevice::reportReception(const CallReceptionReport &report) +{ + QMutexLocker locker(&m_reportMutex); + + // A capture loop that is not taking them - another preset, or no camera - + // would otherwise collect them for the whole call. + if (m_reports.size() < 16) + m_reports.append(report); +} + +QList<CallReceptionReport> VideoDevice::takeReports() +{ + QMutexLocker locker(&m_reportMutex); + QList<CallReceptionReport> reports = m_reports; + + m_reports.clear(); + return reports; +} + +void VideoDevice::probeHardwareEncoders() +{ + ProbeHardwareEncoders(); + emit hardwareEncodersProbed(); +} + void VideoDevice::configurePlayback(QString codec, int width, int height, int acceleration, bool useVaapiRender, QByteArray caller_id, QByteArray callee_id) @@ -1271,6 +1307,39 @@ void VideoDevice::Capture() const QList<VideoCaptureFormat> formats = VideoDevice::CaptureFormats(m_deviceName); + // A preset decides everything configureCapture() was given about the + // picture, out of what this camera, the peer and the GPU allow. Within + // the peer's limit already, so the step down below leaves it as it is. + m_planned = m_preset != CallQualityCustom; + m_fragmentsSent = 0; + takeReports(); + + if (m_planned) + { + m_plan = callPlanVideo((CallQualityPreset)m_preset, CallCameraSizes(formats), + QSize(m_maxWidth, m_maxHeight), ProbeHardwareEncoders()); + + m_codec = m_plan.codec; + m_acceleration = m_plan.acceleration; + m_width = m_plan.captureSize.width(); + m_height = m_plan.captureSize.height(); + m_frameRate = m_plan.frameRate; + m_bitrate = m_plan.bitrateKbps * 1000; + m_preferCompressed = false; + + qDebug() << QString("Call quality preset %1: %2 %3, camera at %4x%5 @%6, encoding %7x%8 at %9 kbit/s%10") + .arg(m_preset) + .arg(m_plan.codec, + m_plan.acceleration ? QStringLiteral("on the GPU") : QStringLiteral("on the CPU")) + .arg(m_width).arg(m_height).arg(m_frameRate) + .arg(m_plan.encodeSize.width()).arg(m_plan.encodeSize.height()) + .arg(m_plan.bitrateKbps) + .arg(m_plan.adaptive() + ? QString(", adapting up to %1x%2 at %3 kbit/s") + .arg(m_width).arg(m_height).arg(m_plan.maxBitrateKbps) + : QString()); + } + // Brought down to what the peer wants to receive before anything is asked // of the camera, so that the size below is the one every attempt is made // at and the one the encoder is opened for. @@ -1415,6 +1484,7 @@ void VideoDevice::emitFragments(const unsigned char *data, int size) emit packetReady(QByteArray((const char *)data + offset, chunk), isLast); offset += chunk; + m_fragmentsSent++; } } @@ -1650,50 +1720,56 @@ static AVCodecContext *openMediaFoundationEncoder(const AVCodec *enc, int width, } #endif -void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) +// An opened video encoder, as openVideoEncoder() hands it back. +struct VideoEncoderSession { - const AVRational frameRate = cameraFrameRate(in_st, m_frameRate); + AVCodecContext *ctx; + // The surface pool it draws from, for an encoder that takes GPU surfaces. + AVBufferRef *hwFrames; + bool hardware; + // FFmpeg encoder name, e.g. "h264_vaapi" or "libx264". + QString name; +}; - // Which encoder produces the configured codec. Looked up once: the GPU - // attempt and the software fallback below are two encoders for the same - // codec, so the peer is told the same thing either way. - const int encIdx = videoEncoderIndex(m_codec); +static void closeVideoEncoder(VideoEncoderSession *s) +{ + if (s->ctx) + avcodec_free_context(&s->ctx); + if (s->hwFrames) + av_buffer_unref(&s->hwFrames); - // Two seconds between keyframes. A receiver that joins late or loses a - // 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); + s->ctx = nullptr; + s->hwFrames = nullptr; +} +// Opens an encoder for the codec at kVideoEncoders[encIdx]: through the GPU +// paths acceleration asks for, in the order VAAPI, Direct3D 12, Media +// Foundation, and in software when none of them opens and allowSoftware is +// set. Anything that goes wrong on the way to a GPU encoder - no such encoder +// built into FFmpeg, no usable device, no surface pool, the encoder refusing +// to open - is logged and only moves on to the next. +// +// False with *error set when nothing opened. +static bool openVideoEncoder(int encIdx, int acceleration, int width, int height, + AVRational frameRate, int64_t bitrate, int gopSize, + bool allowSoftware, VideoEncoderSession *out, QString *error) +{ int ret; - - // The camera hands us either raw frames or a compressed stream that is - // not being forwarded as-is; either way it goes through a decoder here to - // get raw pictures for the encoder. - const AVCodec *cam_dec = avcodec_find_decoder(in_st->codecpar->codec_id); - AVCodecContext *dec_ctx = cam_dec ? avcodec_alloc_context3(cam_dec) : nullptr; - if (!cam_dec || !dec_ctx || - avcodec_parameters_to_context(dec_ctx, in_st->codecpar) < 0 || - avcodec_open2(dec_ctx, cam_dec, nullptr) < 0) - { - QString msg = "Could not open camera format decoder"; - qWarning() << msg; - emit errorOccurred(msg); - if (dec_ctx) avcodec_free_context(&dec_ctx); - return; - } - - // The GPU encoder is tried first when asked for, and anything that goes - // wrong on the way - no such encoder built into FFmpeg, no usable device, - // no surface pool, the encoder refusing to open - just leaves hardware - // false and takes the software path below. bool hardware = false; const AVCodec *enc = nullptr; AVCodecContext *enc_ctx = nullptr; AVBufferRef *hw_frames_ref = nullptr; + out->ctx = nullptr; + out->hwFrames = nullptr; + out->hardware = false; + out->name.clear(); + + Q_UNUSED(ret); + Q_UNUSED(acceleration); + #ifdef HAVE_VAAPI - if ((m_acceleration & VideoAccelerationVaapi) && VaapiContext::isAvailable()) + if ((acceleration & VideoAccelerationVaapi) && VaapiContext::isAvailable()) { enc = avcodec_find_encoder_by_name(kVideoEncoders[encIdx].vaapiEncoder); AVBufferRef *hw_device_ref = enc ? VaapiContext::deviceRef() : nullptr; @@ -1701,7 +1777,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) if (hw_device_ref) { enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_VAAPI, - m_width, m_height, frameRate, m_bitrate, gopSize, + width, height, frameRate, bitrate, gopSize, nullptr, &hw_frames_ref); // Newer Intel GPUs (iHD driver, Gen11+) expose only the low-power @@ -1711,7 +1787,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) AVDictionary *opts = nullptr; av_dict_set(&opts, "low_power", "1", 0); enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_VAAPI, - m_width, m_height, frameRate, m_bitrate, gopSize, + width, height, frameRate, bitrate, gopSize, &opts, &hw_frames_ref); av_dict_free(&opts); } @@ -1742,10 +1818,10 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // that somehow has both - libva has a Windows port of its own - still // gets a hardware encoder if only one of the two comes up. // - // The device is created per capture session and dropped with it, unlike - // the VAAPI one: nothing else in the client holds a D3D12 device - the - // decoder makes its own, and rendering does not go through one. - if (!hardware && (m_acceleration & VideoAccelerationD3d12va)) + // The device is created per encoder and dropped with it, unlike the VAAPI + // one: nothing else in the client holds a D3D12 device - the decoder makes + // its own, and rendering does not go through one. + if (!hardware && (acceleration & VideoAccelerationD3d12va)) { const char *encoderName = kVideoEncoders[encIdx].d3d12vaEncoder; @@ -1779,7 +1855,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) av_dict_set(&options, "rc_mode", kRateControls[r], 0); enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_D3D12, - m_width, m_height, frameRate, m_bitrate, gopSize, + width, height, frameRate, bitrate, gopSize, &options, &hw_frames_ref); av_dict_free(&options); } @@ -1799,7 +1875,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) av_dict_set(&options, "rc_mode", "CQP", 0); AVCodecContext *probe = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_D3D12, - m_width, m_height, frameRate, m_bitrate, + width, height, frameRate, bitrate, gopSize, &options, &probe_frames_ref); av_dict_free(&options); @@ -1850,7 +1926,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // encoder the GPU vendor's driver has registered with Windows, so it also // covers GPUs, drivers and versions of Windows that predate D3D12 video // encoding. - if (!hardware && (m_acceleration & VideoAccelerationMediaFoundation)) + if (!hardware && (acceleration & VideoAccelerationMediaFoundation)) { const char *encoderName = kVideoEncoders[encIdx].mediaFoundationEncoder; @@ -1858,8 +1934,8 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) if (enc) { - enc_ctx = openMediaFoundationEncoder(enc, m_width, m_height, frameRate, - m_bitrate, gopSize); + enc_ctx = openMediaFoundationEncoder(enc, width, height, frameRate, + bitrate, gopSize); hardware = enc_ctx != nullptr; } else if (encoderName) @@ -1878,55 +1954,331 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) } #endif - // Named rather than taken from enc->name because the VAAPI branch above - // may have left a different encoder in enc; filled in below for the - // software path, which is the only one the private options apply to. - QString swEncoderName; + if (hardware) + { + out->ctx = enc_ctx; + out->hwFrames = hw_frames_ref; + out->hardware = true; + out->name = QLatin1String(enc->name); + return true; + } - if (!hardware) + if (!allowSoftware) { - enc = avcodec_find_encoder_by_name(kVideoEncoders[encIdx].swEncoder); - if (!enc) - enc = avcodec_find_encoder(kVideoEncoders[encIdx].id); - enc_ctx = enc ? avcodec_alloc_context3(enc) : nullptr; - if (!enc || !enc_ctx) - { - QString msg = QString("No %1 encoder available").arg(QLatin1String(kVideoEncoders[encIdx].codec)); - qWarning() << msg; - emit errorOccurred(msg); - if (enc_ctx) avcodec_free_context(&enc_ctx); - avcodec_free_context(&dec_ctx); - return; - } + *error = QString("No hardware %1 encoder opened").arg(QLatin1String(kVideoEncoders[encIdx].codec)); + return false; + } + + enc = avcodec_find_encoder_by_name(kVideoEncoders[encIdx].swEncoder); + if (!enc) + enc = avcodec_find_encoder(kVideoEncoders[encIdx].id); + enc_ctx = enc ? avcodec_alloc_context3(enc) : nullptr; + if (!enc || !enc_ctx) + { + *error = QString("No %1 encoder available").arg(QLatin1String(kVideoEncoders[encIdx].codec)); + if (enc_ctx) avcodec_free_context(&enc_ctx); + return false; + } - swEncoderName = QLatin1String(enc->name); + const QString swEncoderName = QLatin1String(enc->name); + + 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->framerate = frameRate; + enc_ctx->bit_rate = bitrate; + enc_ctx->gop_size = gopSize; + // B-frames reorder output, which would cost latency in a live call. + enc_ctx->max_b_frames = 0; + + // Note the absence of AV_CODEC_FLAG_GLOBAL_HEADER: we want the parameter + // sets repeated in-band with every keyframe, since the receiving side has + // no out-of-band way to learn them and may start decoding mid-stream. + applyLiveEncoderOptions(enc_ctx, swEncoderName, kSliceMaxSize); + + if ((ret = avcodec_open2(enc_ctx, enc, nullptr)) < 0) + { + *error = QString("Could not open the %1 encoder: %2").arg(swEncoderName, ff_errstr(ret)); + avcodec_free_context(&enc_ctx); + return false; + } + + out->ctx = enc_ctx; + out->name = swEncoderName; + return true; +} + +// The frame the camera's pictures are scaled into for an encoder. With an +// encoder that draws on a surface pool this is only a staging buffer in system +// memory - NV12, which is what the GPU encoders take - that gets uploaded to a +// GPU surface before encoding; the encoder itself consumes surfaces and never +// sees this frame. Every other encoder, Media Foundation's included, takes it +// as it is. +static AVFrame *allocEncoderFrame(const AVCodecContext *enc_ctx) +{ + AVFrame *frame = av_frame_alloc(); + + if (!frame) + return nullptr; + + frame->format = enc_ctx->hw_frames_ctx ? AV_PIX_FMT_NV12 : enc_ctx->pix_fmt; + frame->width = enc_ctx->width; + frame->height = enc_ctx->height; + + if (av_frame_get_buffer(frame, 0) < 0) + av_frame_free(&frame); + + return frame; +} + +// Whether an opened encoder turns a frame into a packet: an encoder that +// opens is not always one that works - a driver can accept the settings and +// then fail on the first surface. +static bool encoderWorks(AVCodecContext *enc_ctx) +{ + AVFrame *frame = allocEncoderFrame(enc_ctx); + AVFrame *hw_frame = nullptr; + AVPacket *pkt = av_packet_alloc(); + bool works = false; + + if (!frame || !pkt) + goto out; + + { + ptrdiff_t linesizes[4]; + + for (int i = 0; i < 4; i++) + linesizes[i] = frame->linesize[i]; + + av_image_fill_black(frame->data, linesizes, (AVPixelFormat)frame->format, + AVCOL_RANGE_MPEG, frame->width, frame->height); + } + + frame->pts = 0; + + if (enc_ctx->hw_frames_ctx) + { + hw_frame = av_frame_alloc(); + + if (!hw_frame || + av_hwframe_get_buffer(enc_ctx->hw_frames_ctx, hw_frame, 0) < 0 || + av_hwframe_transfer_data(hw_frame, frame, 0) < 0) + goto out; + + hw_frame->pts = 0; + } + + if (avcodec_send_frame(enc_ctx, hw_frame ? hw_frame : frame) < 0 || + avcodec_send_frame(enc_ctx, nullptr) < 0) + goto out; + + while (avcodec_receive_packet(enc_ctx, pkt) == 0) + { + if (pkt->size > 0) + works = true; + + av_packet_unref(pkt); + } + +out: + av_packet_free(&pkt); + av_frame_free(&hw_frame); + av_frame_free(&frame); + + return works; +} + +static QMutex s_probeMutex; +static bool s_probed = false; +static QList<CallHardwareEncoder> s_hardwareEncoders; + +QList<CallHardwareEncoder> VideoDevice::ProbeHardwareEncoders() +{ + 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 + + // In the order openVideoEncoder() tries them. + static const VideoAcceleration kAccelerations[] = + { + VideoAccelerationVaapi, VideoAccelerationD3d12va, VideoAccelerationMediaFoundation + }; - enc_ctx->width = m_width; - enc_ctx->height = m_height; - enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P; - enc_ctx->time_base = av_inv_q(frameRate); - enc_ctx->framerate = frameRate; - enc_ctx->bit_rate = m_bitrate; - enc_ctx->gop_size = gopSize; - // B-frames reorder output, which would cost latency in a live call. - enc_ctx->max_b_frames = 0; + // A common call size and rate: a GPU that cannot encode this is no use + // for a call either. + const AVRational frameRate = { 30, 1 }; - // Note the absence of AV_CODEC_FLAG_GLOBAL_HEADER: we want the parameter - // sets repeated in-band with every keyframe, since the receiving side has - // no out-of-band way to learn them and may start decoding mid-stream. - applyLiveEncoderOptions(enc_ctx, swEncoderName, kSliceMaxSize); + qDebug() << "Finding out which hardware video encoders work - failures below are expected"; - if ((ret = avcodec_open2(enc_ctx, enc, nullptr)) < 0) + for (unsigned int c = 0; c < sizeof(kVideoEncoders) / sizeof(kVideoEncoders[0]); c++) + { + for (unsigned int a = 0; a < sizeof(kAccelerations) / sizeof(kAccelerations[0]); a++) { - QString msg = QString("Could not open the %1 encoder: %2").arg(swEncoderName, ff_errstr(ret)); - qWarning() << msg; - emit errorOccurred(msg); - avcodec_free_context(&enc_ctx); - avcodec_free_context(&dec_ctx); - return; + const char *name = nullptr; + + if (kAccelerations[a] == VideoAccelerationVaapi) + { +#ifdef HAVE_VAAPI + name = kVideoEncoders[c].vaapiEncoder; +#endif + } + else if (kAccelerations[a] == VideoAccelerationD3d12va) + { +#ifdef HAVE_D3D12VA + name = kVideoEncoders[c].d3d12vaEncoder; +#endif + } + else + { +#ifdef Q_OS_WIN + name = kVideoEncoders[c].mediaFoundationEncoder; +#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; + + if (!openVideoEncoder((int)c, kAccelerations[a], 1280, 720, frameRate, 2000000, 60, + false, &es, &error)) + continue; + + if (encoderWorks(es.ctx)) + { + CallHardwareEncoder e; + + 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); + } + + closeVideoEncoder(&es); } } + QStringList names; + + for (int i = 0; i < s_hardwareEncoders.size(); i++) + names << s_hardwareEncoders.at(i).encoder; + + qDebug() << "Hardware video encoders that work here:" + << (names.isEmpty() ? QStringLiteral("none") : names.join(QLatin1String(", "))); + + s_probed = true; + + return s_hardwareEncoders; +} + +bool VideoDevice::HardwareEncodersProbed(QList<CallHardwareEncoder> *encoders) +{ + // Not waiting is the point: a probe that is running holds the lock. + if (!s_probeMutex.tryLock()) + return false; + + const bool probed = s_probed; + + if (probed && encoders) + *encoders = s_hardwareEncoders; + + s_probeMutex.unlock(); + + return probed; +} + +QList<CallCameraSize> VideoDevice::CallCameraSizes(const QList<VideoCaptureFormat> &formats) +{ + QList<CallCameraSize> sizes; + + for (int i = 0; i < formats.size(); i++) + { + CallCameraSize s; + + s.size = QSize(formats.at(i).width, formats.at(i).height); + s.frameRates = formats.at(i).frameRates; + sizes << s; + } + + 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. +static const double kReopenBitrateStep = 0.15; +static const int kReopenIntervalMs = 5000; + +void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) +{ + const AVRational frameRate = cameraFrameRate(in_st, m_frameRate); + + // Which encoder produces the configured codec. Looked up once: the GPU + // attempt and the software fallback below are two encoders for the same + // codec, so the peer is told the same thing either way. + const int encIdx = videoEncoderIndex(m_codec); + + // Two seconds between keyframes. A receiver that joins late or loses a + // 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); + + // What gets encoded: the camera's picture as it is, or for a preset that + // sends less than the camera captures, scaled down. + QSize encodeSize(m_width, m_height); + + if (m_planned && m_plan.encodeSize.isValid()) + encodeSize = m_plan.encodeSize; + + int ret; + + // The camera hands us either raw frames or a compressed stream that is + // not being forwarded as-is; either way it goes through a decoder here to + // get raw pictures for the encoder. + const AVCodec *cam_dec = avcodec_find_decoder(in_st->codecpar->codec_id); + AVCodecContext *dec_ctx = cam_dec ? avcodec_alloc_context3(cam_dec) : nullptr; + if (!cam_dec || !dec_ctx || + avcodec_parameters_to_context(dec_ctx, in_st->codecpar) < 0 || + avcodec_open2(dec_ctx, cam_dec, nullptr) < 0) + { + QString msg = "Could not open camera format decoder"; + qWarning() << msg; + emit errorOccurred(msg); + if (dec_ctx) avcodec_free_context(&dec_ctx); + return; + } + + VideoEncoderSession encoder; + QString encoderError; + + if (!openVideoEncoder(encIdx, m_acceleration, encodeSize.width(), encodeSize.height(), + frameRate, m_bitrate, gopSize, true, &encoder, &encoderError)) + { + qWarning() << encoderError; + emit errorOccurred(encoderError); + avcodec_free_context(&dec_ctx); + return; + } + // Which format the camera is actually delivering, reported alongside the // encoder because the two together explain the frame rate: an uncompressed // camera stream is what caps the rate on a USB 2.0 bus, and seeing @@ -1939,10 +2291,8 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // Named from the encoder that was actually opened rather than written out // per API: "h264_vaapi" and "hevc_d3d12va" say both which codec and which // accelerator settled it, and cannot drift from what is running. - emit accelerationInUse(hardware - ? QString("GPU encoding (%1) from %2") - .arg(QLatin1String(enc->name), source) - : QString("CPU encoding (%1) from %2").arg(swEncoderName, source)); + emit accelerationInUse(QString(encoder.hardware ? "GPU encoding (%1) from %2" : "CPU encoding (%1) from %2") + .arg(encoder.name, source)); // Everything the camera sends is scaled to the encoder's size and re-encoded, // so this is what the peer will receive regardless of what the camera @@ -1954,36 +2304,34 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // The rate is the camera's, not the encoder's: the encoder is configured // from it (see frameRate above) and encodes every frame it is given, so // what the camera delivers is what goes out. - emit captureStarted(QLatin1String(avcodec_get_name(enc_ctx->codec_id)), - enc_ctx->width, enc_ctx->height, av_q2d(frameRate)); + const QString codecName = QLatin1String(avcodec_get_name(encoder.ctx->codec_id)); - // What the camera's frames are scaled into. With an encoder that draws on - // a surface pool this is only a staging buffer in system memory - NV12, - // which is what the GPU encoders take - that gets uploaded to a GPU - // surface below; the encoder itself consumes surfaces and never sees this - // frame. Every other encoder, Media Foundation's included, takes it as it - // is. - AVPixelFormat sw_pix_fmt = enc_ctx->hw_frames_ctx ? AV_PIX_FMT_NV12 : enc_ctx->pix_fmt; + emit captureStarted(codecName, encoder.ctx->width, encoder.ctx->height, av_q2d(frameRate)); - AVFrame *enc_frame = av_frame_alloc(); - if (enc_frame) - { - enc_frame->format = sw_pix_fmt; - enc_frame->width = enc_ctx->width; - enc_frame->height = enc_ctx->height; - } - if (!enc_frame || av_frame_get_buffer(enc_frame, 0) < 0) + AVFrame *enc_frame = allocEncoderFrame(encoder.ctx); + if (!enc_frame) { QString msg = "Could not allocate encoder frame"; qWarning() << msg; emit errorOccurred(msg); - if (enc_frame) av_frame_free(&enc_frame); - if (hw_frames_ref) av_buffer_unref(&hw_frames_ref); - avcodec_free_context(&enc_ctx); + closeVideoEncoder(&encoder); avcodec_free_context(&dec_ctx); return; } + // CallQualityAdaptive: the peer's reports decide the bitrate and size from + // here on, see CallRateController. + const bool adaptive = m_planned && m_plan.adaptive(); + CallRateController rate; + QElapsedTimer clock; + int64_t currentBitrate = m_bitrate; + qint64 lastReopen = 0; + + clock.start(); + + if (adaptive) + rate.start(m_plan, 0); + SwsContext *sws = nullptr; AVPacket *in_pkt = av_packet_alloc(); AVFrame *cam_frame = av_frame_alloc(); @@ -2015,6 +2363,110 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) while (avcodec_receive_frame(dec_ctx, cam_frame) == 0) { + // Between frames, so that a new encoder starts with a whole one. + if (adaptive) + { + const QList<CallReceptionReport> reports = takeReports(); + + for (int i = 0; i < reports.size(); i++) + { + if (rate.update(reports.at(i), m_fragmentsSent, clock.elapsed())) + qDebug() << QString("Adaptive call quality: %1x%2 at %3 kbit/s - %4") + .arg(rate.size().width()).arg(rate.size().height()) + .arg(rate.bitrateKbps()).arg(rate.reason()); + + m_fragmentsSent = 0; + } + + const QSize wantedSize = rate.size(); + const int64_t wantedBitrate = (int64_t)rate.bitrateKbps() * 1000; + bool reopen = wantedSize != encodeSize; + + if (!reopen && wantedBitrate != currentBitrate) + { + const double ratio = (double)wantedBitrate / currentBitrate; + + if (encoder.name == QLatin1String("libx264")) + { + // FFmpeg's libx264 wrapper compares this with what + // the encoder runs at before every frame, and hands a + // change to x264_encoder_reconfig(): no new encoder, + // no keyframe. + encoder.ctx->bit_rate = wantedBitrate; + currentBitrate = wantedBitrate; + } + else if (ratio <= 1.0 - kReopenBitrateStep || + (ratio >= 1.0 + kReopenBitrateStep && clock.elapsed() - lastReopen >= kReopenIntervalMs)) + { + reopen = true; + } + } + + // 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; + + 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 (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) + { + while (avcodec_receive_packet(encoder.ctx, out_pkt) == 0) + { + 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; + + // The scaler targets the encoder's size and format. + if (sws) + { + sws_freeContext(sws); + sws = nullptr; + } + + if (wantedSize != encodeSize) + { + encodeSize = wantedSize; + emit streamChanged(codecName, encodeSize.width(), encodeSize.height()); + } + } + else + { + 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; + // Built lazily: the camera's actual frame format and size are // only known once a frame has been decoded, and may differ from // what was requested. @@ -2025,7 +2477,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) swscaleSourceFormat((AVPixelFormat)cam_frame->format, &srcFullRange); sws = sws_getContext(cam_frame->width, cam_frame->height, srcFormat, - enc_ctx->width, enc_ctx->height, sw_pix_fmt, + enc_ctx->width, enc_ctx->height, (AVPixelFormat)enc_frame->format, SWS_BILINEAR, nullptr, nullptr, nullptr); if (!sws) { @@ -2133,8 +2585,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) av_frame_free(&cam_frame); av_frame_free(&enc_frame); if (sws) sws_freeContext(sws); - if (hw_frames_ref) av_buffer_unref(&hw_frames_ref); - avcodec_free_context(&enc_ctx); + closeVideoEncoder(&encoder); avcodec_free_context(&dec_ctx); } |
