GeoTagController.cc 13.6 KB
Newer Older
Don Gagne's avatar
Don Gagne committed
1 2 3 4 5 6 7 8 9 10
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "GeoTagController.h"
Andreas Bircher's avatar
Andreas Bircher committed
11
#include "ExifParser.h"
12 13 14
#include "QGCFileDialog.h"
#include "QGCLoggingCategory.h"
#include <math.h>
Andreas Bircher's avatar
Andreas Bircher committed
15
#include <QtEndian>
16 17
#include <QMessageBox>
#include <QDebug>
Andreas Bircher's avatar
Andreas Bircher committed
18
#include <cfloat>
Don Gagne's avatar
Don Gagne committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

GeoTagController::GeoTagController(void)
    : _progress(0)
    , _inProgress(false)
{
    connect(&_worker, &GeoTagWorker::progressChanged,   this, &GeoTagController::_workerProgressChanged);
    connect(&_worker, &GeoTagWorker::error,             this, &GeoTagController::_workerError);
    connect(&_worker, &GeoTagWorker::started,           this, &GeoTagController::inProgressChanged);
    connect(&_worker, &GeoTagWorker::finished,          this, &GeoTagController::inProgressChanged);
}

GeoTagController::~GeoTagController()
{

}

void GeoTagController::pickLogFile(void)
{
    QString filename = QGCFileDialog::getOpenFileName(NULL, "Select log file load", QString(), "PX4 log file (*.px4log);;All Files (*.*)");
    if (!filename.isEmpty()) {
        _worker.setLogFile(filename);
        emit logFileChanged(filename);
    }
}

void GeoTagController::pickImageDirectory(void)
{
    QString dir = QGCFileDialog::getExistingDirectory(NULL, "Select image directory");
    if (!dir.isEmpty()) {
        _worker.setImageDirectory(dir);
        emit imageDirectoryChanged(dir);
    }
}

53 54 55 56 57 58 59 60 61
void GeoTagController::pickSaveDirectory(void)
{
    QString dir = QGCFileDialog::getExistingDirectory(NULL, "Select save directory");
    if (!dir.isEmpty()) {
        _worker.setSaveDirectory(dir);
        emit saveDirectoryChanged(dir);
    }
}

Don Gagne's avatar
Don Gagne committed
62 63 64 65
void GeoTagController::startTagging(void)
{
    _errorMessage.clear();
    emit errorMessageChanged(_errorMessage);
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

    QDir imageDirectory = QDir(_worker.imageDirectory());
    if(!imageDirectory.exists()) {
        _errorMessage = tr("Cannot find the image directory");
        emit errorMessageChanged(_errorMessage);
        return;
    }
    if(_worker.saveDirectory() == "") {
        if(!imageDirectory.mkdir(_worker.imageDirectory() + "/TAGGED")) {
            QMessageBox msgBox(QMessageBox::Question,
                               tr("Images have alreay been tagged."),
                               tr("The images have already been tagged. Do you want to replace the previously tagged images?"),
                               QMessageBox::Cancel);
            msgBox.setWindowModality(Qt::ApplicationModal);
            msgBox.addButton(tr("Replace"), QMessageBox::ActionRole);
            if (msgBox.exec() == QMessageBox::Cancel) {
                _errorMessage = tr("Images have already been tagged");
                emit errorMessageChanged(_errorMessage);
                return;
            }
            QDir oldTaggedFolder = QDir(_worker.imageDirectory() + "/TAGGED");
            oldTaggedFolder.removeRecursively();
            if(!imageDirectory.mkdir(_worker.imageDirectory() + "/TAGGED")) {
                _errorMessage = tr("Couldn't replace the previously tagged images");
                emit errorMessageChanged(_errorMessage);
                return;
            }
        }
    } else {
        QDir saveDirectory = QDir(_worker.saveDirectory());
        if(!saveDirectory.exists()) {
            _errorMessage = tr("Cannot find the save directory");
            emit errorMessageChanged(_errorMessage);
            return;
        }
        saveDirectory.setFilter(QDir::Files | QDir::Readable | QDir::NoSymLinks | QDir::Writable);
        QStringList nameFilters;
        nameFilters << "*.jpg" << "*.JPG";
        saveDirectory.setNameFilters(nameFilters);
        QStringList imageList = saveDirectory.entryList();
        if(!imageList.isEmpty()) {
            QMessageBox msgBox(QMessageBox::Question,
                               tr("Save folder not empty."),
                               tr("The save folder already contains images. Do you want to replace them?"),
                               QMessageBox::Cancel);
            msgBox.setWindowModality(Qt::ApplicationModal);
            msgBox.addButton(tr("Replace"), QMessageBox::ActionRole);
            if (msgBox.exec() == QMessageBox::Cancel) {
                _errorMessage = tr("Save folder not empty");
                emit errorMessageChanged(_errorMessage);
                return;
            }
            foreach(QString dirFile, imageList)
            {
                if(!saveDirectory.remove(dirFile)) {
                    _errorMessage = tr("Couldn't replace the existing images");
                    emit errorMessageChanged(_errorMessage);
                    return;
                }
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    _worker.start();
}

void GeoTagController::_workerProgressChanged(double progress)
{
    _progress = progress;
    emit progressChanged(progress);
}

void GeoTagController::_workerError(QString errorMessage)
{
    _errorMessage = errorMessage;
    emit errorMessageChanged(errorMessage);
}

GeoTagWorker::GeoTagWorker(void)
    : _cancel(false)
145 146 147
    , _logFile("")
    , _imageDirectory("")
    , _saveDirectory("")
Don Gagne's avatar
Don Gagne committed
148 149 150 151 152 153 154
{

}

void GeoTagWorker::run(void)
{
    _cancel = false;
155 156
    emit progressChanged(1);
    double nSteps = 5;
Andreas Bircher's avatar
Andreas Bircher committed
157

158 159
    // Load Images
    _imageList.clear();
Andreas Bircher's avatar
Andreas Bircher committed
160 161 162 163 164 165
    QDir imageDirectory = QDir(_imageDirectory);
    imageDirectory.setFilter(QDir::Files | QDir::Readable | QDir::NoSymLinks | QDir::Writable);
    imageDirectory.setSorting(QDir::Name);
    QStringList nameFilters;
    nameFilters << "*.jpg" << "*.JPG";
    imageDirectory.setNameFilters(nameFilters);
166 167
    _imageList = imageDirectory.entryInfoList();
    if(_imageList.isEmpty()) {
Andreas Bircher's avatar
Andreas Bircher committed
168 169 170
        emit error(tr("The image directory doesn't contain images, make sure your images are of the JPG format"));
        return;
    }
171
    emit progressChanged((100/nSteps));
Andreas Bircher's avatar
Andreas Bircher committed
172

173 174 175 176 177
    // Parse EXIF
    ExifParser exifParser;
    _tagTime.clear();
    for (int i = 0; i < _imageList.size(); ++i) {
        QFile file(_imageList.at(i).absoluteFilePath());
Andreas Bircher's avatar
Andreas Bircher committed
178
        if (!file.open(QIODevice::ReadOnly)) {
179 180
            emit error(tr("Geotagging failed. Couldn't open an image."));
            return;
Andreas Bircher's avatar
Andreas Bircher committed
181
        }
182
        QByteArray imageBuffer = file.readAll();
Andreas Bircher's avatar
Andreas Bircher committed
183 184
        file.close();

185
        _tagTime.append(exifParser.readTime(imageBuffer));
Andreas Bircher's avatar
Andreas Bircher committed
186

187
        emit progressChanged((100/nSteps) + ((100/nSteps) / _imageList.size())*i);
Andreas Bircher's avatar
Andreas Bircher committed
188

189 190 191 192 193
        if (_cancel) {
            qCDebug(GeotaggingLog) << "Tagging cancelled";
            emit error(tr("Tagging cancelled"));
            return;
        }
Andreas Bircher's avatar
Andreas Bircher committed
194 195
    }

196
    // Load PX4 log
Andreas Bircher's avatar
Andreas Bircher committed
197 198 199
    _geoRef.clear();
    _triggerTime.clear();
    if (!parsePX4Log()) {
200 201 202 203 204 205 206 207 208
        if (_cancel) {
            qCDebug(GeotaggingLog) << "Tagging cancelled";
            emit error(tr("Tagging cancelled"));
            return;
        } else {
            qCDebug(GeotaggingLog) << "Log parsing failed";
            emit error(tr("Log parsing failed - tagging cancelled"));
            return;
        }
Andreas Bircher's avatar
Andreas Bircher committed
209
    }
210
    emit progressChanged(3*(100/nSteps));
Andreas Bircher's avatar
Andreas Bircher committed
211

212
    qCDebug(GeotaggingLog) << "Found " << _geoRef.count() << " trigger logs.";
Andreas Bircher's avatar
Andreas Bircher committed
213

214 215 216 217 218
    if (_cancel) {
        qCDebug(GeotaggingLog) << "Tagging cancelled";
        emit error(tr("Tagging cancelled"));
        return;
    }
Andreas Bircher's avatar
Andreas Bircher committed
219

220
    // Filter Trigger
Andreas Bircher's avatar
Andreas Bircher committed
221
    if (!triggerFiltering()) {
222 223
        qCDebug(GeotaggingLog) << "Geotagging failed in trigger filtering";
        emit error(tr("Geotagging failed in trigger filtering"));
Andreas Bircher's avatar
Andreas Bircher committed
224 225
        return;
    }
226
    emit progressChanged(4*(100/nSteps));
Andreas Bircher's avatar
Andreas Bircher committed
227

228 229 230 231 232
    if (_cancel) {
        qCDebug(GeotaggingLog) << "Tagging cancelled";
        emit error(tr("Tagging cancelled"));
        return;
    }
Andreas Bircher's avatar
Andreas Bircher committed
233

234 235 236 237 238 239 240 241 242 243 244
    // Tag images
    int maxIndex = std::min(_imageIndices.count(), _triggerIndices.count());
    maxIndex = std::min(maxIndex, _imageList.count());
    for(int i = 0; i < maxIndex; i++) {
        QFile fileRead(_imageList.at(_imageIndices[i]).absoluteFilePath());
        if (!fileRead.open(QIODevice::ReadOnly)) {
            emit error(tr("Geotagging failed. Couldn't open an image."));
            return;
        }
        QByteArray imageBuffer = fileRead.readAll();
        fileRead.close();
Andreas Bircher's avatar
Andreas Bircher committed
245

246 247 248
        if (!exifParser.write(imageBuffer, _geoRef[_triggerIndices[i]])) {
            emit error(tr("Geotagging failed. Couldn't write to image."));
            return;
Andreas Bircher's avatar
Andreas Bircher committed
249
        } else {
250 251 252 253 254 255 256 257 258
            QFile fileWrite;
            if(_saveDirectory == "") {
                fileWrite.setFileName(_imageDirectory + "/TAGGED/" + _imageList.at(_imageIndices[i]).fileName());
            } else {
                fileWrite.setFileName(_saveDirectory + "/" + _imageList.at(_imageIndices[i]).fileName());
            }
            if (!fileWrite.open(QFile::WriteOnly)) {
                emit error(tr("Geotagging failed. Couldn't write to an image."));
                return;
Andreas Bircher's avatar
Andreas Bircher committed
259
            }
260 261
            fileWrite.write(imageBuffer);
            fileWrite.close();
Andreas Bircher's avatar
Andreas Bircher committed
262
        }
263
        emit progressChanged(4*(100/nSteps) + ((100/nSteps) / maxIndex)*i);
Andreas Bircher's avatar
Andreas Bircher committed
264

Don Gagne's avatar
Don Gagne committed
265
        if (_cancel) {
266
            qCDebug(GeotaggingLog) << "Tagging cancelled";
Don Gagne's avatar
Don Gagne committed
267 268 269 270 271
            emit error(tr("Tagging cancelled"));
            return;
        }
    }

272 273 274 275 276 277
    if (_cancel) {
        qCDebug(GeotaggingLog) << "Tagging cancelled";
        emit error(tr("Tagging cancelled"));
        return;
    }

Don Gagne's avatar
Don Gagne committed
278 279
    emit progressChanged(100);
}
Andreas Bircher's avatar
Andreas Bircher committed
280 281 282 283

bool GeoTagWorker::parsePX4Log()
{
    // general message header
284
    char header[] = {(char)0xA3, (char)0x95, (char)0x00};
285 286 287
    // header for GPOS message header
    char gposHeaderHeader[] = {(char)0xA3, (char)0x95, (char)0x80, (char)0x10, (char)0x00};
    int gposHeaderOffset;
Andreas Bircher's avatar
Andreas Bircher committed
288
    // header for GPOS message
289
    char gposHeader[] = {(char)0xA3, (char)0x95, (char)0x10, (char)0x00};
Andreas Bircher's avatar
Andreas Bircher committed
290 291
    int gposOffsets[3] = {3, 7, 11};
    int gposLengths[3] = {4, 4, 4};
292 293 294
    // header for trigger message header
    char triggerHeaderHeader[] = {(char)0xA3, (char)0x95, (char)0x80, (char)0x37, (char)0x00};
    int triggerHeaderOffset;
Andreas Bircher's avatar
Andreas Bircher committed
295
    // header for trigger message
296
    char triggerHeader[] = {(char)0xA3, (char)0x95, (char)0x37, (char)0x00};
Andreas Bircher's avatar
Andreas Bircher committed
297 298
    int triggerOffsets[2] = {3, 11};
    int triggerLengths[2] = {8, 4};
299

Andreas Bircher's avatar
Andreas Bircher committed
300 301 302
    // load log
    QFile file(_logFile);
    if (!file.open(QIODevice::ReadOnly)) {
303
        qCDebug(GeotaggingLog) << "Could not open log file " << _logFile;
Andreas Bircher's avatar
Andreas Bircher committed
304 305 306 307 308
        return false;
    }
    QByteArray log = file.readAll();
    file.close();

309 310 311 312 313 314
    // extract header information: message lengths
    uint8_t* iptr = reinterpret_cast<uint8_t*>(log.mid(log.indexOf(gposHeaderHeader) + 4, 1).data());
    gposHeaderOffset = static_cast<int>(qFromLittleEndian(*iptr));
    iptr = reinterpret_cast<uint8_t*>(log.mid(log.indexOf(triggerHeaderHeader) + 4, 1).data());
    triggerHeaderOffset = static_cast<int>(qFromLittleEndian(*iptr));

Andreas Bircher's avatar
Andreas Bircher committed
315 316 317 318 319
    // extract trigger data
    int index = 1;
    int sequence = -1;
    QGeoCoordinate lastCoordinate;
    while(index < log.count() - 1) {
320 321 322 323 324 325

        if (_cancel) {
            return false;
        }

        // first extract trigger
326
        index = log.indexOf(triggerHeader, index + 1);
Andreas Bircher's avatar
Andreas Bircher committed
327
        // check for whether last entry has been passed
328
        if (index < 0) {
Andreas Bircher's avatar
Andreas Bircher committed
329 330
            break;
        }
331 332 333 334 335 336 337

        if (log.indexOf(header, index + 1) != index + triggerHeaderOffset) {
            continue;
        }
        uint64_t* time = reinterpret_cast<uint64_t*>(log.mid(index + triggerOffsets[0], triggerLengths[0]).data());
        double timeDouble = static_cast<double>(qFromLittleEndian(*time)) / 1.0e6;
        uint32_t* seq = reinterpret_cast<uint32_t*>(log.mid(index + triggerOffsets[1], triggerLengths[1]).data());
338
        int seqInt = static_cast<int>(qFromLittleEndian(*seq));
339 340
        if (sequence >= seqInt || sequence + 20 < seqInt) { // assume that logging has not skipped more than 20 triggers. this prevents wrong header detection
            continue;
341
        }
342 343
        _triggerTime.append(timeDouble);
        sequence = seqInt;
344 345 346 347 348 349 350 351 352 353 354 355 356 357

        // second extract position
        bool lookForGpos = true;
        while (lookForGpos) {

            if (_cancel) {
                return false;
            }

            int gposIndex = log.indexOf(gposHeader, index + 1);
            if (gposIndex < 0) {
                _geoRef.append(lastCoordinate);
                break;
            }
Andreas Bircher's avatar
Andreas Bircher committed
358
            index = gposIndex;
359 360
            // verify that at an offset of gposHeaderOffset the next log message starts
            if (gposIndex + gposHeaderOffset == log.indexOf(header, gposIndex + 1)) {
361 362 363 364 365 366 367 368 369 370 371
                int32_t* lat = reinterpret_cast<int32_t*>(log.mid(gposIndex + gposOffsets[0], gposLengths[0]).data());
                double latitude = static_cast<double>(qFromLittleEndian(*lat))/1.0e7;
                lastCoordinate.setLatitude(latitude);
                int32_t* lon = reinterpret_cast<int32_t*>(log.mid(gposIndex + gposOffsets[1], gposLengths[1]).data());
                double longitude = static_cast<double>(qFromLittleEndian(*lon))/1.0e7;
                longitude = fmod(180.0 + longitude, 360.0) - 180.0;
                lastCoordinate.setLongitude(longitude);
                float* alt = reinterpret_cast<float*>(log.mid(gposIndex + gposOffsets[2], gposLengths[2]).data());
                lastCoordinate.setAltitude(qFromLittleEndian(*alt));
                _geoRef.append(lastCoordinate);
                break;
Andreas Bircher's avatar
Andreas Bircher committed
372 373 374 375 376 377 378 379
            }
        }
    }
    return true;
}

bool GeoTagWorker::triggerFiltering()
{
380 381 382 383
    _imageIndices.clear();
    _triggerIndices.clear();
    for(int i = 0; i < _tagTime.count() && i < _triggerTime.count(); i++) {
        _imageIndices.append(i);
Andreas Bircher's avatar
Andreas Bircher committed
384 385
        _triggerIndices.append(i);
    }
386

Andreas Bircher's avatar
Andreas Bircher committed
387 388
    return true;
}