QGCMAVLinkLogPlayer.cc 25 KB
Newer Older
1 2
#include <QFileDialog>
#include <QMessageBox>
3
#include <QStandardPaths>
4
#include <QtEndian>
5

6
#include "MainWindow.h"
7
#include "SerialLink.h"
8
#include "QGCMAVLinkLogPlayer.h"
9
#include "QGC.h"
10 11 12
#include "ui_QGCMAVLinkLogPlayer.h"

QGCMAVLinkLogPlayer::QGCMAVLinkLogPlayer(MAVLinkProtocol* mavlink, QWidget *parent) :
13
    QWidget(parent),
14 15 16
    playbackStartTime(0),
    logStartTime(0),
    logEndTime(0),
17 18 19 20 21
    accelerationFactor(1.0f),
    mavlink(mavlink),
    logLink(NULL),
    loopCounter(0),
    mavlinkLogFormat(true),
22
    binaryBaudRate(defaultBinaryBaudRate),
lm's avatar
lm committed
23
    isPlaying(false),
24
    currPacketCount(0),
25
    lastLogDirectory(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)),
26
    ui(new Ui::QGCMAVLinkLogPlayer)
27 28
{
    ui->setupUi(this);
29
    ui->horizontalLayout->setAlignment(Qt::AlignTop);
30

31 32 33
    // Connect protocol
    connect(this, SIGNAL(bytesReady(LinkInterface*,QByteArray)), mavlink, SLOT(receiveBytes(LinkInterface*,QByteArray)));

34 35 36
    // Setup timer
    connect(&loopTimer, SIGNAL(timeout()), this, SLOT(logLoop()));

37 38
    // Setup buttons
    connect(ui->selectFileButton, SIGNAL(clicked()), this, SLOT(selectLogFile()));
lm's avatar
lm committed
39
    connect(ui->playButton, SIGNAL(clicked()), this, SLOT(playPauseToggle()));
40
    connect(ui->speedSlider, SIGNAL(valueChanged(int)), this, SLOT(setAccelerationFactorInt(int)));
41 42
    connect(ui->positionSlider, SIGNAL(valueChanged(int)), this, SLOT(jumpToSliderVal(int)));
    connect(ui->positionSlider, SIGNAL(sliderPressed()), this, SLOT(pause()));
43

44 45
    setAccelerationFactorInt(49);
    ui->speedSlider->setValue(49);
46
    updatePositionSliderUi(0.0);
Lorenz Meier's avatar
Lorenz Meier committed
47 48 49 50

    ui->playButton->setEnabled(false);
    ui->speedSlider->setEnabled(false);
    ui->positionSlider->setEnabled(false);
51 52 53
    ui->speedLabel->setEnabled(false);
    ui->logFileNameLabel->setEnabled(false);
    ui->logStatsLabel->setEnabled(false);
Lorenz Meier's avatar
Lorenz Meier committed
54

55 56 57
    // Monitor for when the end of the log file is reached. This is done using signals because the main work is in a timer.
    connect(this, SIGNAL(logFileEndReached()), &loopTimer, SLOT(stop()));

Lorenz Meier's avatar
Lorenz Meier committed
58
    loadSettings();
59 60 61 62
}

QGCMAVLinkLogPlayer::~QGCMAVLinkLogPlayer()
{
Lorenz Meier's avatar
Lorenz Meier committed
63
    storeSettings();
64 65 66
    delete ui;
}

lm's avatar
lm committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
void QGCMAVLinkLogPlayer::playPause(bool enabled)
{
    if (enabled)
    {
        play();
    }
    else
    {
        pause();
    }
}

void QGCMAVLinkLogPlayer::playPauseToggle()
{
    if (isPlaying)
    {
        pause();
    }
    else
    {
        play();
    }
}

91 92
void QGCMAVLinkLogPlayer::play()
{
lm's avatar
lm committed
93 94
    if (logFile.isOpen())
    {
95
        // Disable the log file selector button
96
        ui->selectFileButton->setEnabled(false);
97 98 99

        // Make sure we aren't at the end of the file, if we are, reset to the beginning and play from there.
        if (logFile.atEnd())
lm's avatar
lm committed
100
        {
101
            reset();
102
        }
103 104 105 106

        // Always correct the current start time such that the next message will play immediately at playback.
        // We do this by subtracting the current file playback offset  from now()
        playbackStartTime = (quint64)QDateTime::currentMSecsSinceEpoch() - (logCurrentTime - logStartTime) / 1000;
107 108

        // Start timer
lm's avatar
lm committed
109 110
        if (mavlinkLogFormat)
        {
111
            loopTimer.start(1);
lm's avatar
lm committed
112 113 114
        }
        else
        {
115 116 117 118 119 120
            // Read len bytes at a time
            int len = 100;
            // Calculate the number of times to read 100 bytes per second
            // to guarantee the baud rate, then divide 1000 by the number of read
            // operations to obtain the interval in milliseconds
            int interval = 1000 / ((binaryBaudRate / 10) / len);
121
            loopTimer.start(interval / accelerationFactor);
122
        }
lm's avatar
lm committed
123
        isPlaying = true;
124
        ui->playButton->setChecked(true);
125
        ui->playButton->setIcon(QIcon(":files/images/actions/media-playback-pause.svg"));
lm's avatar
lm committed
126 127 128
    }
    else
    {
129 130 131 132 133 134 135 136 137 138 139 140 141
        ui->playButton->setChecked(false);
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setText(tr("No logfile selected"));
        msgBox.setInformativeText(tr("Please select first a MAVLink log file before playing it."));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
    }
}

void QGCMAVLinkLogPlayer::pause()
{
142
    loopTimer.stop();
143
    isPlaying = false;
144
    ui->playButton->setIcon(QIcon(":files/images/actions/media-playback-start.svg"));
145
    ui->playButton->setChecked(false);
146 147 148
    ui->selectFileButton->setEnabled(true);
}

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
void QGCMAVLinkLogPlayer::reset()
{
    pause();
    loopCounter = 0;
    logFile.reset();

    // Now update the position slider to its default location
    updatePositionSliderUi(0.0);

    // And since we haven't starting playback, clear the time of initial playback and the current timestamp.
    playbackStartTime = 0;
    logCurrentTime = logStartTime;
}

bool QGCMAVLinkLogPlayer::jumpToPlaybackLocation(float percentage)
164
{
165
    // Reset only for valid values
166
    if (percentage <= 100.0f && percentage >= 0.0f)
lm's avatar
lm committed
167
    {
168
        bool result = true;
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
        if (mavlinkLogFormat)
        {
            // But if we have a timestamped MAVLink log, then actually aim to hit that percentage in terms of
            // time through the file.
            qint64 newFilePos = (qint64)(percentage * (float)logFile.size());

            // Now seek to the appropriate position, failing gracefully if we can't.
            if (!logFile.seek(newFilePos))
            {
                // Fallback: Start from scratch
                logFile.reset();
                ui->logStatsLabel->setText(tr("Changing packet index failed, back to start."));
                result = false;
            }

            // But we do align to the next MAVLink message for consistency.
            mavlink_message_t dummy;
            logCurrentTime = findNextMavlinkMessage(&dummy);
lm's avatar
lm committed
187

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
            // Now calculate the current file location based on time.
            float newRelativeTime = (float)(logCurrentTime - logStartTime);

            // Calculate the effective baud rate of the file in bytes/s.
            float logDuration = (logEndTime - logStartTime);
            float baudRate = logFile.size() / logDuration / 1e6;

            // And the desired time is:
            float desiredTime = percentage * logDuration;

            // And now jump the necessary number of bytes in the proper direction
            qint64 offset = (newRelativeTime - desiredTime) * baudRate;
            logFile.seek(logFile.pos() + offset);

            // And scan until we reach the start of a MAVLink message. We make sure to record this timestamp for
            // smooth jumping around the file.
            logCurrentTime = findNextMavlinkMessage(&dummy);

            // Now update the UI with our actual final position.
            newRelativeTime = (float)(logCurrentTime - logStartTime);
            percentage = newRelativeTime / logDuration;
            updatePositionSliderUi(percentage);
        }
        else
lm's avatar
lm committed
212
        {
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            // If we're working with a non-timestamped file, we just jump to that percentage of the file,
            // align to the next MAVLink message and roll with it. No reason to do anything more complicated.
            qint64 newFilePos = (qint64)(percentage * (float)logFile.size());

            // Now seek to the appropriate position, failing gracefully if we can't.
            if (!logFile.seek(newFilePos))
            {
                // Fallback: Start from scratch
                logFile.reset();
                ui->logStatsLabel->setText(tr("Changing packet index failed, back to start."));
                result = false;
            }

            // But we do align to the next MAVLink message for consistency.
            mavlink_message_t dummy;
            findNextMavlinkMessage(&dummy);
229 230
        }

231 232
        // Now update the UI. This is necessary because stop() is called when loading a new logfile

233
        return result;
lm's avatar
lm committed
234 235 236
    }
    else
    {
237 238
        return false;
    }
239 240
}

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
void QGCMAVLinkLogPlayer::updatePositionSliderUi(float percent)
{
    ui->positionSlider->blockSignals(true);
    int sliderVal = ui->positionSlider->minimum() + (int)(percent * (float)(ui->positionSlider->maximum() - ui->positionSlider->minimum()));
    ui->positionSlider->setValue(sliderVal);

    // Calculate the runtime in hours:minutes:seconds
    // WARNING: Order matters in this computation
    quint32 seconds = percent * (logEndTime - logStartTime) / 1e6;
    quint32 minutes = seconds / 60;
    quint32 hours = minutes / 60;
    seconds -= 60*minutes;
    minutes -= 60*hours;

    // And show the user the details we found about this file.
    QString timeLabel = tr("%1h:%2m:%3s").arg(hours, 2).arg(minutes, 2).arg(seconds, 2);
    ui->positionSlider->setToolTip(timeLabel);
    ui->positionSlider->blockSignals(false);
}

Lorenz Meier's avatar
Lorenz Meier committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
void QGCMAVLinkLogPlayer::loadSettings()
{
    QSettings settings;
    settings.beginGroup("QGC_MAVLINKLOGPLAYER");
    lastLogDirectory = settings.value("LAST_LOG_DIRECTORY", lastLogDirectory).toString();
    settings.endGroup();
}

void QGCMAVLinkLogPlayer::storeSettings()
{
    QSettings settings;
    settings.beginGroup("QGC_MAVLINKLOGPLAYER");
    settings.setValue("LAST_LOG_DIRECTORY", lastLogDirectory);
    settings.endGroup();
    settings.sync();
}

/**
 * @brief Select a log file
 * @param startDirectory Directory where the file dialog will be opened
 * @return filename of the logFile
 */
bool QGCMAVLinkLogPlayer::selectLogFile()
{
285
    // Prompt the user for a new file using the last directory they searched.
Lorenz Meier's avatar
Lorenz Meier committed
286 287 288
    return selectLogFile(lastLogDirectory);
}

289
/**
Lorenz Meier's avatar
Lorenz Meier committed
290
 * @brief Select a log file
291 292 293 294
 * @param startDirectory Directory where the file dialog will be opened
 * @return filename of the logFile
 */
bool QGCMAVLinkLogPlayer::selectLogFile(const QString startDirectory)
295
{
296
    QString fileName = QFileDialog::getOpenFileName(this, tr("Specify MAVLink log file name to replay"), startDirectory, tr("MAVLink or Binary Logfile (*.mavlink *.bin *.log)"));
297

298 299 300 301 302 303
    if (fileName == "")
    {
        return false;
    }
    else
    {
Lorenz Meier's avatar
Lorenz Meier committed
304
        lastLogDirectory = fileName;
305 306
        return loadLogFile(fileName);
    }
307 308
}

309 310 311 312 313 314 315 316
/**
 * @param factor 0: 0.01X, 50: 1.0X, 100: 100.0X
 */
void QGCMAVLinkLogPlayer::setAccelerationFactorInt(int factor)
{
    float f = factor+1.0f;
    f -= 50.0f;

lm's avatar
lm committed
317 318
    if (f < 0.0f)
    {
319
        accelerationFactor = 1.0f / (-f/2.0f);
lm's avatar
lm committed
320 321 322
    }
    else
    {
323 324 325
        accelerationFactor = 1+(f/2.0f);
    }

326
    // Update timer interval
lm's avatar
lm committed
327 328
    if (!mavlinkLogFormat)
    {
329 330 331 332 333 334 335
        // Read len bytes at a time
        int len = 100;
        // Calculate the number of times to read 100 bytes per second
        // to guarantee the baud rate, then divide 1000 by the number of read
        // operations to obtain the interval in milliseconds
        int interval = 1000 / ((binaryBaudRate / 10) / len);
        loopTimer.stop();
336
        loopTimer.start(interval / accelerationFactor);
337 338
    }

339
    ui->speedLabel->setText(tr("Speed: %1X").arg(accelerationFactor, 5, 'f', 2, '0'));
340 341
}

342
bool QGCMAVLinkLogPlayer::loadLogFile(const QString& file)
343
{
Lorenz Meier's avatar
Lorenz Meier committed
344 345 346 347
    // Enable controls
    ui->playButton->setEnabled(true);
    ui->speedSlider->setEnabled(true);
    ui->positionSlider->setEnabled(true);
348 349 350
    ui->speedLabel->setEnabled(true);
    ui->logFileNameLabel->setEnabled(true);
    ui->logStatsLabel->setEnabled(true);
Lorenz Meier's avatar
Lorenz Meier committed
351

352
    // Disable logging while replaying a log file.
lm's avatar
lm committed
353 354
    if (mavlink->loggingEnabled())
    {
lm's avatar
lm committed
355 356 357 358
        mavlink->enableLogging(false);
        MainWindow::instance()->showInfoMessage(tr("MAVLink Logging Stopped during Replay"), tr("MAVLink logging has been stopped during the log replay. To re-enable logging, use the link properties in the communication menu."));
    }

359 360 361 362
    // Make sure to stop the logging process and reset everything.
    reset();

    // And that the old file is closed nicely.
lm's avatar
lm committed
363 364
    if (logFile.isOpen())
    {
365 366
        logFile.close();
    }
367

368 369
    // Now load the new file.
    logFile.setFileName(file);
lm's avatar
lm committed
370 371
    if (!logFile.open(QFile::ReadOnly))
    {
372
        MainWindow::instance()->showCriticalMessage(tr("The selected logfile is unreadable"), tr("Please make sure that the file %1 is readable or select a different file").arg(file));
373
        logFile.setFileName("");
374
        return false;
lm's avatar
lm committed
375 376 377
    }
    else
    {
378 379
        QFileInfo logFileInfo(file);
        logFile.reset();
380 381 382 383 384 385 386 387 388 389 390 391
        ui->logFileNameLabel->setText(tr("Logfile: %1").arg(logFileInfo.fileName()));

        // If there's an existing MAVLinkSimulationLink() being used for an old file,
        // we replace it.
        if (logLink)
        {
            logLink->disconnect();
            LinkManager::instance()->removeLink(logLink);
            delete logLink;
        }
        logLink = new MAVLinkSimulationLink("");

392

393 394 395
        // Select if binary or MAVLink log format is used
        mavlinkLogFormat = file.endsWith(".mavlink");

lm's avatar
lm committed
396 397
        if (mavlinkLogFormat)
        {
398 399
            // Get the first timestamp from the logfile
            // This should be a big-endian uint64.
400
            QByteArray timestamp = logFile.read(timeLen);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
            quint64 starttime = parseTimestamp(timestamp);

            // Now find the last timestamp by scanning for the last MAVLink packet and
            // find the timestamp before it. To do this we start searchin a little before
            // the end of the file, specifically the maximum MAVLink packet size + the
            // timestamp size. This guarantees that we will hit a MAVLink packet before
            // the end of the file. Unfortunately, it basically guarantees that we will
            // hit more than one. This is why we have to search for a bit.
            qint64 fileLoc = logFile.size() - MAVLINK_MAX_PACKET_LEN - timeLen;
            logFile.seek(fileLoc);
            quint64 endtime = starttime; // Set a sane default for the endtime
            mavlink_message_t msg;
            quint64 newTimestamp;
            while ((newTimestamp = findNextMavlinkMessage(&msg)) > endtime) {
                endtime = newTimestamp;
            }

            if (endtime == starttime) {
                MainWindow::instance()->showCriticalMessage(tr("The selected logfile cannot be processed"), tr("No valid timestamps were found at the end of the logfile.").arg(file));
                logFile.setFileName("");
                ui->logFileNameLabel->setText(tr("No logfile selected"));
                return false;
            }
424

425 426 427 428
            // Remember the start and end time so we can move around this logfile with the slider.
            logEndTime = endtime;
            logStartTime = starttime;
            logCurrentTime = logStartTime;
429

430
            // Reset our log file so when we go to read it for the first time, we start at the beginning.
431
            logFile.reset();
432

433
            // Calculate the runtime in hours:minutes:seconds
434
            // WARNING: Order matters in this computation
435 436 437
            quint32 seconds = (endtime - starttime)/1000000;
            quint32 minutes = seconds / 60;
            quint32 hours = minutes / 60;
438 439
            seconds -= 60*minutes;
            minutes -= 60*hours;
440

441
            // And show the user the details we found about this file.
442
            QString timelabel = tr("%1h:%2m:%3s").arg(hours, 2).arg(minutes, 2).arg(seconds, 2);
443 444
            currPacketCount = logFileInfo.size()/(32 + MAVLINK_NUM_NON_PAYLOAD_BYTES + sizeof(quint64)); // Count packets by assuming an average payload size of 32 bytes
            ui->logStatsLabel->setText(tr("%2 MB, ~%3 packets, %4").arg(logFileInfo.size()/1000000.0f, 0, 'f', 2).arg(currPacketCount).arg(timelabel));
lm's avatar
lm committed
445 446 447
        }
        else
        {
448 449 450
            // Load in binary mode. In this mode, files should be have a filename postfix
            // of the baud rate they were recorded at, like `test_run_115200.bin`. Then on
            // playback, the datarate is equal to set to this value.
451

452
            // Set baud rate if any present. Otherwise we default to 57600.
453
            QStringList parts = logFileInfo.baseName().split("_");
454
            binaryBaudRate = defaultBinaryBaudRate;
lm's avatar
lm committed
455 456
            if (parts.count() > 1)
            {
457 458 459
                bool ok;
                int rate = parts.last().toInt(&ok);
                // 9600 baud to 100 MBit
lm's avatar
lm committed
460 461
                if (ok && (rate > 9600 && rate < 100000000))
                {
462 463 464 465 466 467 468 469 470 471 472 473
                    // Accept this as valid baudrate
                    binaryBaudRate = rate;
                }
            }

            int seconds = logFileInfo.size() / (binaryBaudRate / 10);
            int minutes = seconds / 60;
            int hours = minutes / 60;
            seconds -= 60*minutes;
            minutes -= 60*hours;

            QString timelabel = tr("%1h:%2m:%3s").arg(hours, 2).arg(minutes, 2).arg(seconds, 2);
474
            ui->logStatsLabel->setText(tr("%2 MB, %4 at %5 KB/s").arg(logFileInfo.size()/1000000.0f, 0, 'f', 2).arg(timelabel).arg(binaryBaudRate/10.0f/1024.0f, 0, 'f', 2));
475
        }
476

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
        // Check if a serial link is connected

        bool linkWarning = false;
        foreach (LinkInterface* link, LinkManager::instance()->getLinks())
        {
            SerialLink* s = dynamic_cast<SerialLink*>(link);

            if (s && s->isConnected())
                linkWarning = true;
        }

        if (linkWarning)
            MainWindow::instance()->showInfoMessage(tr("Active MAVLink links found"), tr("Currently other links are connected. It is recommended to disconnect any active link before replaying a log."));

        play();

493
        return true;
494
    }
495 496
}

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
quint64 QGCMAVLinkLogPlayer::parseTimestamp(const QByteArray &data)
{
    // Retrieve the timestamp from the ByteArray assuming a proper BigEndian quint64 timestamp in microseconds.
    quint64 timestamp = qFromBigEndian(*((quint64*)(data.constData())));

    // And get the current time in microseconds
    quint64 currentTimestamp = ((quint64)QDateTime::currentMSecsSinceEpoch()) * 1000;

    // Now if the parsed timestamp is in the future, it must be an old file where the timestamp was stored as
    // little endian, so switch it.
    if (timestamp > currentTimestamp) {
        timestamp = qbswap(timestamp);
    }

    return timestamp;
}

514
/**
515 516
 * Jumps to the current percentage of the position slider. When this is called, the LogPlayer should already
 * have been paused, so it just jumps to the proper location in the file and resumes playing.
517 518
 */
void QGCMAVLinkLogPlayer::jumpToSliderVal(int slidervalue)
519
{
520 521 522 523 524 525 526 527 528 529 530 531
    // Determine what percentage through the file we should be (time or packet number depending).
    float newLocation = slidervalue / (float)(ui->positionSlider->maximum() - ui->positionSlider->minimum());

    // And clamp our calculated values to the valid range of [0,100]
    if (newLocation > 100.0f)
    {
        newLocation = 100.0f;
    }
    if (newLocation < 0.0f)
    {
        newLocation = 0.0f;
    }
532

533 534
    // Do only valid jumps
    if (jumpToPlaybackLocation(newLocation))
lm's avatar
lm committed
535 536 537
    {
        if (mavlinkLogFormat)
        {
538 539 540 541 542 543 544 545 546 547 548 549
            // Grab the total seconds of this file (1e6 is due to microsecond -> second conversion)
            int seconds = newLocation * (logEndTime - logStartTime) / 1e6;
            int minutes = seconds / 60;
            int hours = minutes / 60;
            seconds -= 60*minutes;
            minutes -= 60*hours;

            ui->logStatsLabel->setText(tr("Jumped to time %1h:%2m:%3s").arg(hours, 2).arg(minutes, 2).arg(seconds, 2));
        }
        else
        {
            ui->logStatsLabel->setText(tr("Jumped to %1").arg(newLocation));
550
        }
551 552 553 554 555 556

        play();
    }
    else
    {
        reset();
557
    }
558
}
559

560 561 562 563 564 565 566 567
/**
 * This function is the "mainloop" of the log player, reading one line
 * and adjusting the mainloop timer to read the next line in time.
 * It might not perfectly match the timing of the log file,
 * but it will never induce a static drift into the log file replay.
 * For scientific logging, the use of onboard timestamps and the log
 * functionality of the line chart plot is recommended.
 */
568
void QGCMAVLinkLogPlayer::logLoop()
569
{
570 571
    // If we have a file with timestamps, try and pace this out following the time differences
    // between the timestamps and the current playback speed.
lm's avatar
lm committed
572 573
    if (mavlinkLogFormat)
    {
574
        // Now parse MAVLink messages, grabbing their timestamps as we go. We stop once we
Bryant Mairs's avatar
Bryant Mairs committed
575 576 577 578
        // have at least 3ms until the next one. 

        // We track what the next execution time should be in milliseconds, which we use to set
        // the next timer interrupt.
579
        int nextExecutionTime = 0;
Bryant Mairs's avatar
Bryant Mairs committed
580 581 582 583

        // We use the `findNextMavlinkMessage()` function to scan ahead for MAVLink messages. This
        // is necessary because we don't know how big each MAVLink message is until we finish parsing
        // one, and since we only output arrays of bytes, we need to know the size of that array.
584
        mavlink_message_t msg;
Bryant Mairs's avatar
Bryant Mairs committed
585 586
        findNextMavlinkMessage(&msg);

587
        while (nextExecutionTime < 3) {
588

589 590
            // Now we're sitting at the start of a MAVLink message, so read it all into a byte array for feeding to our parser.
            QByteArray message = logFile.read(msg.len + MAVLINK_NUM_NON_PAYLOAD_BYTES);
591

592 593
            // Emit this message to our MAVLink parser.
            emit bytesReady(logLink, message);
594

595 596
            // If we've reached the end of the of the file, make sure we handle that well
            if (logFile.atEnd())
lm's avatar
lm committed
597
            {
598 599 600 601 602 603 604 605 606
                // For some reason calling pause() here doesn't work, so we update the UI manually here.
                isPlaying = false;
                ui->playButton->setIcon(QIcon(":files/images/actions/media-playback-start.svg"));
                ui->playButton->setChecked(false);
                ui->selectFileButton->setEnabled(true);

                // Note that we explicitly set the slider to 100%, as it may not hit that by itself depending on log file size.
                updatePositionSliderUi(100.0f);
                emit logFileEndReached();
607 608
                return;
            }
609

610 611
            // Run our parser to find the next timestamp and leave us at the start of the next MAVLink message.
            logCurrentTime = findNextMavlinkMessage(&msg);
612

613 614 615 616 617 618
            // Calculate how long we should wait in real time until parsing this message.
            // We pace ourselves relative to the start time of playback to fix any drift (initially set in play())
            qint64 timediff = (logCurrentTime - logStartTime) / accelerationFactor;
            quint64 desiredPacedTime = playbackStartTime + ((quint64)timediff) / 1000;
            quint64 currentTime = (quint64)QDateTime::currentMSecsSinceEpoch();
            nextExecutionTime = desiredPacedTime - currentTime;
619
        }
620

621 622
        // And schedule the next execution of this function.
        loopTimer.start(nextExecutionTime);
lm's avatar
lm committed
623 624 625
    }
    else
    {
626 627 628 629 630 631 632 633
        // Binary format - read at fixed rate
        const int len = 100;
        QByteArray chunk = logFile.read(len);

        // Emit this packet
        emit bytesReady(logLink, chunk);

        // Check if reached end of file before reading next timestamp
lm's avatar
lm committed
634 635
        if (chunk.length() < len || logFile.atEnd())
        {
636 637 638 639 640 641 642 643
            // Reached end of file
            reset();

            QString status = tr("Reached end of binary log file.");
            ui->logStatsLabel->setText(status);
            MainWindow::instance()->showStatusMessage(status);
            return;
        }
644
    }
645

646 647 648
    // Update the UI every 2^5=32 times, or when there isn't much data to be played back.
    // Reduces flickering and minimizes CPU load.
    if ((loopCounter & 0x1F) == 0 || currPacketCount < 2000)
lm's avatar
lm committed
649
    {
650
        QFileInfo logFileInfo(logFile);
651
        updatePositionSliderUi(logFile.pos() / static_cast<float>(logFileInfo.size()));
652
    }
653
    loopCounter++;
654
}
655

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
/**
 * This function parses out the next MAVLink message and its corresponding timestamp.
 *
 * It makes no assumptions about where in the file we currently are. It leaves the file right
 * at the beginning of the successfully parsed message. Note that this function will not attempt to
 * correct for any MAVLink parsing failures, so it always returns the next successfully-parsed
 * message.
 *
 * @param msg[output] Where the final parsed message output will go.
 * @return A Unix timestamp in microseconds UTC or 0 if parsing failed
 */
quint64 QGCMAVLinkLogPlayer::findNextMavlinkMessage(mavlink_message_t *msg)
{
    char nextByte;
    mavlink_status_t comm;
    while (logFile.getChar(&nextByte)) { // Loop over every byte
        bool messageFound = mavlink_parse_char(logLink->getId(), nextByte, msg, &comm);

        // If we've found a message, jump back to the start of the message, grab the timestamp,
        // and go back to the end of this file.
        if (messageFound) {
            logFile.seek(logFile.pos() - (msg->len + MAVLINK_NUM_NON_PAYLOAD_BYTES + timeLen));
            QByteArray rawTime = logFile.read(timeLen);
            return parseTimestamp(rawTime);
        }
    }

    // Otherwise, if we never find a message, return a failure code of 0.
    return 0;
}

687 688 689
void QGCMAVLinkLogPlayer::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
lm's avatar
lm committed
690 691
    switch (e->type())
    {
692 693 694 695 696 697 698
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
699 700 701 702 703 704 705 706 707 708

/**
 * Implement paintEvent() so that stylesheets work for our custom widget.
 */
void QGCMAVLinkLogPlayer::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
709
}