summaryrefslogtreecommitdiffstats
path: root/pica-client/videodevice.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'pica-client/videodevice.cpp')
-rw-r--r--pica-client/videodevice.cpp258
1 files changed, 258 insertions, 0 deletions
diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp
index ab6f08e..2d15d45 100644
--- a/pica-client/videodevice.cpp
+++ b/pica-client/videodevice.cpp
@@ -2224,6 +2224,264 @@ QList<CallCameraSize> VideoDevice::CallCameraSizes(const QList<VideoCaptureForma
// 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
+// wanted size and left to adjust, as buildCaptureAttempts() does too.
+static QSize previewSize(const QList<VideoCaptureFormat> &formats, const QSize &wanted)
+{
+ const qint64 wantedArea = (qint64)wanted.width() * wanted.height();
+ QSize best;
+ QSize smallest;
+
+ for (int i = 0; i < formats.size(); i++)
+ {
+ const QSize size(formats.at(i).width, formats.at(i).height);
+ const qint64 area = (qint64)size.width() * size.height();
+
+ if (size == wanted)
+ return size;
+
+ if (!smallest.isValid() || area < (qint64)smallest.width() * smallest.height())
+ smallest = size;
+
+ if (area <= wantedArea &&
+ (!best.isValid() || area > (qint64)best.width() * best.height()))
+ best = size;
+ }
+
+ if (best.isValid())
+ return best;
+
+ return smallest.isValid() ? smallest : wanted;
+}
+
+void VideoDevice::Preview()
+{
+ /* closed before it got to start */
+ if (sessionClosed())
+ return;
+
+ avdevice_register_all();
+#if LIBAVFORMAT_VERSION_MAJOR < 58
+ av_register_all();
+ avcodec_register_all();
+#endif
+
+ const QByteArray deviceUtf8 = cameraOpenUrl(m_deviceName);
+ const QByteArray driverUtf8 = VideoDevice::PlatformDriverName().toUtf8();
+ const AVInputFormat *ifmt = av_find_input_format(driverUtf8.constData());
+
+ if (!ifmt)
+ {
+ QString msg = QString("Could not find '%1' video input driver").arg(VideoDevice::PlatformDriverName());
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ return;
+ }
+
+ const QList<VideoCaptureFormat> formats = VideoDevice::CaptureFormats(m_deviceName);
+ const QSize size = previewSize(formats, QSize(m_width, m_height));
+
+ // The same order of attempts a call's capture goes through, minus
+ // forwarding a compressed stream, which has no meaning here: every frame is
+ // decoded either way, and MJPEG is still preferred over uncompressed where
+ // only it can carry the rate.
+ const QList<CaptureAttempt> attempts =
+ buildCaptureAttempts(m_deviceName, formats, size.width(), size.height(), m_frameRate,
+ false, QString());
+
+ AVFormatContext *ifmt_ctx = nullptr;
+ int ret = AVERROR(EINVAL);
+
+ for (int a = 0; a < attempts.size() && !sessionClosed(); a++)
+ {
+ const CaptureAttempt &attempt = attempts.at(a);
+
+ ret = openCamera(ifmt, deviceUtf8,
+ attempt.constrainSize ? size.width() : 0,
+ attempt.constrainSize ? size.height() : 0,
+ attempt.constrainRate ? m_frameRate : 0,
+ attempt.inputFormat, &ifmt_ctx);
+
+ if (ret >= 0)
+ break;
+
+ // Another handle is streaming from the camera. No other format or size
+ // will change that, so the remaining attempts would only fail the same
+ // way, one log line each.
+ if (ret == AVERROR(EBUSY))
+ {
+ qWarning() << QString("Camera '%1' preview: the camera is busy - %2")
+ .arg(m_deviceName, ff_errstr(ret));
+
+ if (!sessionClosed())
+ emit cameraBusy();
+ return;
+ }
+
+ qWarning() << QString("Camera '%1' preview: no %2 at %3x%4 - %5 (%6)")
+ .arg(m_deviceName,
+ attempt.inputFormat.isEmpty() ? QStringLiteral("stream") : attempt.inputFormat)
+ .arg(size.width()).arg(size.height())
+ .arg(attempt.reason, ff_errstr(ret));
+ }
+
+ if (ret < 0 || !ifmt_ctx)
+ {
+ if (sessionClosed())
+ return;
+
+ QString msg = QString("Could not open camera '%1': %2").arg(m_deviceName, ff_errstr(ret));
+
+#ifdef Q_OS_WIN
+ // See Capture().
+ msg += tr(" - check that \"Let desktop apps access your camera\" is enabled in the "
+ "Windows camera privacy settings, and that no other application is using it");
+#endif
+
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ return;
+ }
+
+ if ((ret = avformat_find_stream_info(ifmt_ctx, nullptr)) < 0 || ifmt_ctx->nb_streams < 1)
+ {
+ QString msg = QString("Could not determine camera stream parameters: %1").arg(ff_errstr(ret));
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ avformat_close_input(&ifmt_ctx);
+ return;
+ }
+
+ AVStream *in_st = ifmt_ctx->streams[0];
+ 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);
+ avformat_close_input(&ifmt_ctx);
+ return;
+ }
+
+ emit captureStarted(in_st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO
+ ? QString()
+ : QString::fromLatin1(avcodec_get_name(in_st->codecpar->codec_id)),
+ in_st->codecpar->width, in_st->codecpar->height,
+ av_q2d(cameraFrameRate(in_st, m_frameRate)));
+
+ AVPacket *in_pkt = av_packet_alloc();
+ AVFrame *cam_frame = av_frame_alloc();
+ SwsContext *sws = nullptr;
+ // What sws was set up for; rebuilt should the camera's frames change.
+ int sws_width = 0;
+ int sws_height = 0;
+ int sws_format = AV_PIX_FMT_NONE;
+ bool loggedReadError = false;
+
+ if (!in_pkt || !cam_frame)
+ {
+ QString msg = "Could not allocate camera preview buffers";
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ }
+
+ while (in_pkt && cam_frame && !sessionClosed())
+ {
+ ret = av_read_frame(ifmt_ctx, in_pkt);
+ if (ret < 0)
+ {
+ if (ret == AVERROR(EAGAIN))
+ continue;
+ if (!loggedReadError)
+ {
+ qWarning() << QString("Camera read failed: %1").arg(ff_errstr(ret));
+ loggedReadError = true;
+ }
+ break;
+ }
+
+ ret = avcodec_send_packet(dec_ctx, in_pkt);
+ av_packet_unref(in_pkt);
+ if (ret < 0)
+ continue;
+
+ while (avcodec_receive_frame(dec_ctx, cam_frame) == 0)
+ {
+ if (!sws || cam_frame->width != sws_width || cam_frame->height != sws_height ||
+ cam_frame->format != sws_format)
+ {
+ if (sws)
+ sws_freeContext(sws);
+
+ bool srcFullRange = false;
+ const AVPixelFormat srcFormat =
+ swscaleSourceFormat((AVPixelFormat)cam_frame->format, &srcFullRange);
+
+ // AV_PIX_FMT_0RGB32 is laid out exactly as QImage::Format_RGB32,
+ // see decode().
+ sws = sws_getContext(cam_frame->width, cam_frame->height, srcFormat,
+ cam_frame->width, cam_frame->height, AV_PIX_FMT_0RGB32,
+ SWS_BILINEAR, nullptr, nullptr, nullptr);
+
+ if (!sws)
+ {
+ qWarning() << "Could not set up camera preview scaler";
+ av_frame_unref(cam_frame);
+ sws_width = sws_height = 0;
+ continue;
+ }
+
+ // A JPEG frame's full range, which the format name no longer
+ // says - see swscaleSourceFormat(). Without it the picture's
+ // blacks and whites would come out grey, costing a QR code
+ // reader contrast it can use.
+ if (srcFullRange)
+ {
+ const int *coefs = sws_getCoefficients(SWS_CS_DEFAULT);
+
+ sws_setColorspaceDetails(sws, coefs, 1, coefs, 1,
+ 0, 1 << 16, 1 << 16);
+ }
+
+ sws_width = cam_frame->width;
+ sws_height = cam_frame->height;
+ sws_format = cam_frame->format;
+ }
+
+ // A new image per frame, for the same reason decode() makes one:
+ // it goes to another thread without being copied.
+ QImage img(cam_frame->width, cam_frame->height, QImage::Format_RGB32);
+
+ if (!img.isNull())
+ {
+ uint8_t *dst_data[4] = { img.bits(), nullptr, nullptr, nullptr };
+ int dst_linesize[4] = { (int)img.bytesPerLine(), 0, 0, 0 };
+
+ sws_scale(sws, cam_frame->data, cam_frame->linesize, 0, cam_frame->height,
+ dst_data, dst_linesize);
+
+ emit frameReady(img);
+ }
+
+ av_frame_unref(cam_frame);
+ }
+ }
+
+ if (sws)
+ sws_freeContext(sws);
+ av_frame_free(&cam_frame);
+ av_packet_free(&in_pkt);
+ avcodec_free_context(&dec_ctx);
+ avformat_close_input(&ifmt_ctx);
+}
+
static const double kReopenBitrateStep = 0.15;
static const int kReopenIntervalMs = 5000;