Camera.cpp 15 KB
Newer Older
Thiago Santini's avatar
Thiago Santini committed
1
#include "Camera.h"
Thiago Santini's avatar
Thiago Santini committed
2
#include <QFileInfo>
Thiago Santini's avatar
Thiago Santini committed
3

4 5
#include "globals.h"

6 7 8 9
static const int gQCameraInfoMetaTypeId = qRegisterMetaType<QCameraInfo>("QCameraInfo");
static const int gMatMetaTypeId = qRegisterMetaType<cv::Mat>("cv::Mat");
static const int gTimestampMetaTypeId = qRegisterMetaType<Timestamp>("Timestamp");
static const int gQListQCameraViewfinderSettingsId = qRegisterMetaType<QList<QCameraViewfinderSettings>>("QList<QCameraViewfinderSettings>");
Thiago Santini's avatar
Thiago Santini committed
10 11 12

QMutex Camera::setCameraMutex;

13 14 15 16 17 18 19
Camera::Camera(QString id, QObject* parent)
    : QObject(parent)
    , colorCode(CV_8UC3)
    , camera(nullptr)
    , frameGrabber(nullptr)
    , retriesLeft(0)
    , maxRetries(15)
Thiago Santini's avatar
Thiago Santini committed
20 21
{
    this->id = id;
22 23 24 25 26 27 28 29 30
    if (id.contains("eye", Qt::CaseInsensitive))
        colorCode = CV_8UC1;
    ui = new CameraUI();
    ui->moveToThread(QApplication::instance()->thread());
    connect(ui, SIGNAL(setCamera(QCameraInfo)), this, SLOT(setCamera(QCameraInfo)));
    connect(ui, SIGNAL(setViewfinderSettings(QCameraViewfinderSettings)), this, SLOT(setViewfinderSettings(QCameraViewfinderSettings)));
    connect(ui, SIGNAL(setColorCode(int)), this, SLOT(setColorCode(int)));
    connect(ui, SIGNAL(setParameter(QString, float)), this, SLOT(setParameter(QString, float)));
    settings = new QSettings(gCfgDir + "/" + id + " Camera.ini", QSettings::IniFormat);
Thiago Santini's avatar
Thiago Santini committed
31 32 33 34 35 36 37 38 39 40 41 42 43
}

Camera::~Camera()
{
    reset();
    ui->deleteLater();
    if (settings)
        settings->deleteLater();
}

void Camera::reset()
{
    QList<QCameraViewfinderSettings> settingsList;
44
    QMetaObject::invokeMethod(ui, "updateSettings", Q_ARG(QList<QCameraViewfinderSettings>, settingsList), Q_ARG(QCameraViewfinderSettings, currentViewfinderSettings));
Thiago Santini's avatar
Thiago Santini committed
45 46 47
    if (camera) {
        camera->stop();
        camera->unload();
48
        camera->setViewfinder(static_cast<FrameGrabber*>(nullptr));
Thiago Santini's avatar
Thiago Santini committed
49 50 51 52
        // Delete straight away so the destructor from uvcengine service get's
        // called and the device is not busy anymore
        //camera->deleteLater();
        delete camera;
Thiago Santini's avatar
Thiago Santini committed
53
        camera = nullptr;
Thiago Santini's avatar
Thiago Santini committed
54 55 56 57
    }

    if (frameGrabber) {
        frameGrabber->deleteLater();
Thiago Santini's avatar
Thiago Santini committed
58
        frameGrabber = nullptr;
59
    }
Thiago Santini's avatar
Thiago Santini committed
60 61 62 63 64 65 66
}

QCameraViewfinderSettings Camera::getViewfinderSettings(const QCameraInfo cameraInfo)
{
    QCameraViewfinderSettings recommended;

    // Recommend based on known cameras
67
    QString description = cameraInfo.description();
68

69 70
    if (knownSettings.size() == 0)
        buildKnownViewfinderSettings();
71

72 73 74
    if (knownSettings.count(description)) {
        recommended = knownSettings[description];
    } else {
Thiago Santini's avatar
Thiago Santini committed
75 76
        // Unknown; recommend to maximize fps and minimize resolution
        recommended = camera->viewfinderSettings();
77 78 79 80 81 82
        foreach (const QCameraViewfinderSettings& setting, camera->supportedViewfinderSettings()) {
            if (setting.pixelFormat() == QVideoFrame::Format_RGB32
                || setting.pixelFormat() == QVideoFrame::Format_RGB24
                || setting.pixelFormat() == QVideoFrame::Format_YUYV
                || setting.pixelFormat() == QVideoFrame::Format_UYVY
                || setting.pixelFormat() == QVideoFrame::Format_Jpeg) {
Thiago Santini's avatar
Thiago Santini committed
83 84 85

                if (recommended.isNull())
                    recommended = setting;
86 87 88
                else if (setting.maximumFrameRate() >= recommended.maximumFrameRate())
                    if (setting.resolution().width() * setting.resolution().height() < recommended.resolution().width() * recommended.resolution().height())
                        recommended = setting;
Thiago Santini's avatar
Thiago Santini committed
89 90 91 92 93 94
            }
        }
        return recommended;
    }

    // Get the exact setting based on known camera recomendation
95
    foreach (const QCameraViewfinderSettings& setting, camera->supportedViewfinderSettings()) {
Thiago Santini's avatar
Thiago Santini committed
96 97 98 99
        if (recommended.pixelFormat() != setting.pixelFormat())
            continue;
        if (recommended.resolution() != setting.resolution())
            continue;
100
        if (fabs(recommended.maximumFrameRate() - setting.maximumFrameRate()) > 1)
Thiago Santini's avatar
Thiago Santini committed
101 102 103 104 105 106 107 108 109 110 111 112 113
            continue;
        return setting;
    }

    // This shouldn't happen unless the recomendation is wrong
    return camera->viewfinderSettings();
}

void Camera::setViewfinderSettings(QCameraViewfinderSettings settings)
{
    setCamera(currentCameraInfo, settings);
}

114
void Camera::setCamera(const QCameraInfo& cameraInfo)
Thiago Santini's avatar
Thiago Santini committed
115 116 117 118 119
{
    QCameraViewfinderSettings settings;
    setCamera(cameraInfo, settings);
}

120
void Camera::setCamera(const QCameraInfo& cameraInfo, QCameraViewfinderSettings settings)
Thiago Santini's avatar
Thiago Santini committed
121 122 123
{
    QMutexLocker setCameraLocker(&setCameraMutex);

124
    reset();
Thiago Santini's avatar
Thiago Santini committed
125

126 127
    QString msg = "No camera selected";
    QList<QCameraViewfinderSettings> settingsList;
Thiago Santini's avatar
Thiago Santini committed
128 129 130 131 132 133 134 135
    if (cameraInfo.isNull()) {
        currentCameraInfo = QCameraInfo();
        currentViewfinderSettings = QCameraViewfinderSettings();
        emit noCamera(msg);
    } else {

        qInfo() << id << "Opening" << cameraInfo.description();
        camera = new QCamera(cameraInfo.deviceName().toUtf8());
136
        frameGrabber = new FrameGrabber(id, colorCode);
Thiago Santini's avatar
Thiago Santini committed
137 138 139

        camera->load();
        if (camera->state() == QCamera::UnloadedState) {
140 141 142 143
            qInfo() << id << cameraInfo.description() << "failed to load:\n"
                    << camera->errorString();
            reset();
            emit noCamera("Failed to load.");
Thiago Santini's avatar
Thiago Santini committed
144 145 146 147
            return;
        }

        if (settings.isNull())
148
            settings = getViewfinderSettings(cameraInfo);
149

150 151 152 153
        currentCameraInfo = cameraInfo;
        currentViewfinderSettings = settings;
        settingsList = camera->supportedViewfinderSettings();
        QMetaObject::invokeMethod(ui, "updateSettings", Q_ARG(QList<QCameraViewfinderSettings>, settingsList), Q_ARG(QCameraViewfinderSettings, currentViewfinderSettings));
Thiago Santini's avatar
Thiago Santini committed
154 155 156 157 158 159

        camera->setViewfinderSettings(settings);
        camera->setViewfinder(frameGrabber);
        camera->start();

        if (camera->state() != QCamera::ActiveState) {
160 161
            qInfo() << id << cameraInfo.description() << "failed to start (" << settings << ")\n"
                    << camera->errorString();
Thiago Santini's avatar
Thiago Santini committed
162 163 164 165 166
            emit noCamera("Failed to start.");
            return;
        }

        connect(frameGrabber, SIGNAL(newFrame(Timestamp, cv::Mat)),
167
            this, SIGNAL(newFrame(Timestamp, cv::Mat)));
Thiago Santini's avatar
Thiago Santini committed
168
        connect(frameGrabber, SIGNAL(timedout()),
169
            this, SLOT(timedout()));
Thiago Santini's avatar
Thiago Santini committed
170 171 172

        fps = settings.maximumFrameRate();
        msg = currentCameraInfo.description() + " " + toQString(settings);
173
        retriesLeft = maxRetries;
174
    }
175

176 177 178
    loadUserCameraParameters();
    setValuesUI();
    saveCfg();
179
    emit cameraChanged(currentCameraInfo, currentViewfinderSettings);
Thiago Santini's avatar
Thiago Santini committed
180 181 182 183 184 185 186 187 188 189
    qInfo() << id << msg;
}

void Camera::setColorCode(int code)
{
    colorCode = code;
    QMetaObject::invokeMethod(frameGrabber, "setColorCode", Q_ARG(int, colorCode));
    saveCfg();
}

190 191
void Camera::setParameter(QString what, float value)
{
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    if (!camera)
        return;

    QCameraImageProcessing* ip = camera->imageProcessing();
    QCameraExposure* exp = camera->exposure();

    QString parameter = what;

    if (ip->isAvailable()) {
        if (parameter == "brightness")
            ip->setBrightness(value);
        if (parameter == "contrast")
            ip->setContrast(value);
        if (parameter == "white_balance")
            ip->setManualWhiteBalance(value);
        if (parameter == "saturation")
            ip->setSaturation(value);
        if (parameter == "sharpening_level")
            ip->setSharpeningLevel(value);
    }

    if (exp->isAvailable()) {
        if (parameter == "exposure_time")
            exp->setManualAperture(value);
        if (parameter == "exposure_mode") {
            switch ((int)value) {
            case 1:
                exp->setExposureMode(QCameraExposure::ExposureManual);
                break;
            case 2:
                exp->setExposureMode(QCameraExposure::ExposureAuto);
                break;
            }
        }
    }

    saveCameraParameter(parameter, value);
Thiago Santini's avatar
Thiago Santini committed
229 230 231 232
}

void Camera::setValuesUI()
{
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    if (!camera)
        return;

    QCameraImageProcessing* ip = camera->imageProcessing();
    QCameraExposure* exp = camera->exposure();

    if (ip->isAvailable()) {
        ui->setValue(ui->findChild<QDoubleSpinBox*>("brightness"), ip->brightness());
        ui->setValue(ui->findChild<QDoubleSpinBox*>("contrast"), ip->contrast());
        ui->setValue(ui->findChild<QDoubleSpinBox*>("white_balance"), ip->manualWhiteBalance());
        ui->setValue(ui->findChild<QDoubleSpinBox*>("saturation"), ip->saturation());
        ui->setValue(ui->findChild<QDoubleSpinBox*>("sharpening_level"), ip->sharpeningLevel());
    }

    if (exp->isAvailable()) {
        ui->setValue(ui->findChild<QDoubleSpinBox*>("exposure_time"), exp->aperture());
        switch ((int)exp->exposureMode()) {
        case QCameraExposure::ExposureManual:
            ui->setValue(ui->findChild<QComboBox*>("exposure_mode"), 1);
            break;
        case QCameraExposure::ExposureAuto:
            ui->setValue(ui->findChild<QComboBox*>("exposure_mode"), 2);
            break;
        }
    }
258 259
}

Thiago Santini's avatar
Thiago Santini committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
void Camera::showOptions()
{
    QMetaObject::invokeMethod(ui, "update", Q_ARG(QCameraInfo, currentCameraInfo), Q_ARG(int, colorCode));
    QMetaObject::invokeMethod(ui, "show");
}

void Camera::saveCfg()
{
    settings->sync();
    settings->setValue("description", iniStr(currentCameraInfo.description()));
    settings->setValue("deviceName", iniStr(currentCameraInfo.deviceName()));
    settings->setValue("width", currentViewfinderSettings.resolution().width());
    settings->setValue("height", currentViewfinderSettings.resolution().height());
    settings->setValue("fps", currentViewfinderSettings.maximumFrameRate());
    settings->setValue("format", currentViewfinderSettings.pixelFormat());
    settings->setValue("wPxRatio", currentViewfinderSettings.pixelAspectRatio().width());
    settings->setValue("hPxRatio", currentViewfinderSettings.pixelAspectRatio().height());
    settings->setValue("colorCode", colorCode);
}

void Camera::loadCfg()
{
    settings->sync();
    QString description;
    set(settings, "description", description);
    QString deviceName;
    set(settings, "deviceName", deviceName);

    QCameraInfo info;
    QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
290
    for (int i = 0; i < cameras.size(); i++) {
Thiago Santini's avatar
Thiago Santini committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        if (iniStr(cameras[i].description()) == description && iniStr(cameras[i].deviceName()) == deviceName)
            info = cameras[i];
    }

    QCameraViewfinderSettings viewFinderSetting;

    double fps = 30;
    set(settings, "fps", fps);
    viewFinderSetting.setMaximumFrameRate(fps);
    viewFinderSetting.setMinimumFrameRate(fps);

    double width = 640;
    double height = 480;
    set(settings, "width", width);
    set(settings, "height", height);
306
    viewFinderSetting.setResolution(width, height);
Thiago Santini's avatar
Thiago Santini committed
307 308 309 310 311

    double wPxRatio = 1;
    double hPxRatio = 1;
    set(settings, "wPxRatio", wPxRatio);
    set(settings, "hPxRatio", hPxRatio);
312
    viewFinderSetting.setPixelAspectRatio(wPxRatio, hPxRatio);
Thiago Santini's avatar
Thiago Santini committed
313 314 315

    QVideoFrame::PixelFormat format = QVideoFrame::Format_BGR24;
    set(settings, "format", format);
316
    viewFinderSetting.setPixelFormat(format);
Thiago Santini's avatar
Thiago Santini committed
317 318 319

    set(settings, "colorCode", colorCode);

320
    setCamera(info, viewFinderSetting);
321

322 323
    if (info.isNull()) // failed to load something, search for default cameras
        searchDefaultCamera();
Thiago Santini's avatar
Thiago Santini committed
324 325 326 327 328
}

void Camera::timedout()
{
    qWarning() << id << "timedout; reopening...";
329
    retriesLeft--; // initialize the countdown
330 331
    reset();
    retry();
332
}
Thiago Santini's avatar
Thiago Santini committed
333

334 335
void Camera::retry()
{
Thiago Santini's avatar
Thiago Santini committed
336 337 338 339 340 341
    QCameraInfo cameraInfo = currentCameraInfo;
    QCameraViewfinderSettings viewfinderSettings = currentViewfinderSettings;

    currentCameraInfo = QCameraInfo();
    currentViewfinderSettings = QCameraViewfinderSettings();

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    if (retriesLeft < maxRetries && retriesLeft >= 0) {
        if (isAvailable(cameraInfo))
            setCamera(cameraInfo, viewfinderSettings);
        if (!currentCameraInfo.isNull())
            return;
        currentCameraInfo = cameraInfo;
        currentViewfinderSettings = viewfinderSettings;
        retriesLeft--;
        QTimer::singleShot(1000, this, SLOT(retry()));
    }

    QString msg = QString("%1: ").arg(cameraInfo.deviceName());
    if (retriesLeft < 0)
        msg.append("lost.");
    else
        msg.append(QString("reopening (%1/%2) ...").arg(maxRetries - retriesLeft).arg(maxRetries));
    emit noCamera(msg);
Thiago Santini's avatar
Thiago Santini committed
359
}
360 361 362

void Camera::searchDefaultCamera()
{
363
    /* TODO:
Thiago Santini's avatar
Thiago Santini committed
364
	 * 1) consider searching for the cameras periodically -- e.g., if the user
365 366 367 368 369
	 * plugs the eye tracker *after* we are running, nothing will happen.
	 *
	 * 2) extend this so the user can add his own default cameras
	 */

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    QStringList ets;
    if (id.contains("eye", Qt::CaseInsensitive)) {
        if (id.contains("right", Qt::CaseInsensitive)) {
            ets.push_back("Pupil Cam. ID0");
            ets.push_back("RYS THREE");
        }
        if (id.contains("left", Qt::CaseInsensitive)) {
            ets.push_back("Pupil Cam. ID1");
            ets.push_back("RYS TWO");
        }
    }
    if (id.contains("field", Qt::CaseInsensitive)) {
        ets.push_back("Pupil Cam. ID2");
        ets.push_back("RYS ONE");
    }
385

386 387 388 389 390 391 392 393 394 395 396
    for (auto et : ets) {
        QRegularExpression re(et);
        QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
        for (int i = 0; i < cameras.size(); i++) {
            if (re.match(cameras[i].deviceName()).hasMatch()) {
                setCamera(cameras[i]);
                if (!currentCameraInfo.isNull())
                    return;
            }
        }
    }
397
}
Thiago Santini's avatar
Thiago Santini committed
398 399 400

void Camera::loadUserCameraParameters()
{
401 402 403 404 405 406 407 408 409 410 411
    QFileInfo cameraSettingsFile(makeSettingsFileName());
    if (!cameraSettingsFile.exists())
        return;
    QSettings settings(cameraSettingsFile.absoluteFilePath(), QSettings::IniFormat);
    loadAndSet(settings, "brightness");
    loadAndSet(settings, "contrast");
    loadAndSet(settings, "white_balance");
    loadAndSet(settings, "saturation");
    loadAndSet(settings, "sharpening_level");
    loadAndSet(settings, "exposure_time");
    loadAndSet(settings, "exposure_mode");
Thiago Santini's avatar
Thiago Santini committed
412
}
413 414 415

void Camera::buildKnownViewfinderSettings()
{
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    auto set = [this](const QString& cid, const float& fps, const QSize& resolution, const QVideoFrame::PixelFormat& format) {
        assert(this->knownSettings.count(cid) == 0);
        QCameraViewfinderSettings setting;
        setting.setMaximumFrameRate(fps);
        setting.setMinimumFrameRate(fps);
        setting.setResolution(resolution);
        setting.setPixelFormat(format);
        this->knownSettings[cid] = std::move(setting);
    };

    // Pupil eye V1
    set("Pupil Cam1 ID0", 60, { 640, 480 }, QVideoFrame::Format_Jpeg);
    set("Pupil Cam1 ID1", 60, { 640, 480 }, QVideoFrame::Format_Jpeg);

    // Pupil eye v2
431 432
    set("Pupil Cam2 ID0", 90, { 192, 192 }, QVideoFrame::Format_Jpeg);
    set("Pupil Cam2 ID1", 90, { 192, 192 }, QVideoFrame::Format_Jpeg);
433 434 435 436 437 438 439 440 441 442 443

    // Pupil field
    set("Pupil Cam1 ID2", 30, { 1280, 720 }, QVideoFrame::Format_Jpeg);

    // Tuebingen v1
    set("RYS ONE", 60, { 640, 480 }, QVideoFrame::Format_Jpeg);
    set("RYS TWO", 60, { 320, 240 }, QVideoFrame::Format_Jpeg);
    set("RYS THREE", 60, { 320, 240 }, QVideoFrame::Format_Jpeg);

    // Generic
    set("HD Webcam C525", 30, { 640, 480 }, QVideoFrame::Format_Jpeg);
444
}