Updated changelog.
[LameXP.git] / src / Dialog_Processing.cpp
blob06a71f39fdab084aad50c0a4a4701ee12a787673
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2023 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU GENERAL PUBLIC LICENSE as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version; always including the non-optional
9 // LAMEXP GNU GENERAL PUBLIC LICENSE ADDENDUM. See "License.txt" file!
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Dialog_Processing.h"
25 //UIC includes
26 #include "UIC_ProcessingDialog.h"
28 //Internal
29 #include "Global.h"
30 #include "Model_FileList.h"
31 #include "Model_Progress.h"
32 #include "Model_Settings.h"
33 #include "Model_FileExts.h"
34 #include "Thread_Process.h"
35 #include "Thread_CPUObserver.h"
36 #include "Thread_RAMObserver.h"
37 #include "Thread_DiskObserver.h"
38 #include "Dialog_LogView.h"
39 #include "Registry_Decoder.h"
40 #include "Registry_Encoder.h"
41 #include "Filter_Downmix.h"
42 #include "Filter_Normalize.h"
43 #include "Filter_Resample.h"
44 #include "Filter_ToneAdjust.h"
46 //MUtils
47 #include <MUtils/Global.h>
48 #include <MUtils/OSSupport.h>
49 #include <MUtils/GUI.h>
50 #include <MUtils/CPUFeatures.h>
51 #include <MUtils/Sound.h>
52 #include <MUtils/Taskbar7.h>
54 //Qt
55 #include <QApplication>
56 #include <QRect>
57 #include <QDesktopWidget>
58 #include <QMovie>
59 #include <QMessageBox>
60 #include <QTimer>
61 #include <QCloseEvent>
62 #include <QDesktopServices>
63 #include <QUrl>
64 #include <QUuid>
65 #include <QFileInfo>
66 #include <QDir>
67 #include <QMenu>
68 #include <QSystemTrayIcon>
69 #include <QProcess>
70 #include <QProgressDialog>
71 #include <QResizeEvent>
72 #include <QTime>
73 #include <QElapsedTimer>
74 #include <QThreadPool>
76 #include <math.h>
77 #include <float.h>
78 #include <stdint.h>
80 //Maximum number of parallel instances
81 #define MAX_INSTANCES 64U
83 ////////////////////////////////////////////////////////////
85 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
86 { \
87 QPalette palette = WIDGET->palette(); \
88 palette.setColor(QPalette::Background, COLOR); \
89 WIDGET->setPalette(palette); \
90 } \
91 while(0)
93 #define SET_PROGRESS_TEXT(TXT) do \
94 { \
95 ui->label_progress->setText(TXT); \
96 if(!m_systemTray.isNull()) \
97 { \
98 if(!m_systemTray->isVisible()) m_systemTray->setVisible(true); \
99 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
102 while(0)
104 #define SET_PROGRESS_MESG(TITLE, MESSAGE, TYPE, ICON) do \
106 if (!m_systemTray.isNull()) \
108 m_systemTray->showMessage(TITLE, MESSAGE, TYPE); \
109 m_systemTray->setIcon(ICON); \
112 while(0)
114 #define SET_FONT_BOLD(WIDGET,BOLD) do \
116 QFont _font = WIDGET->font(); \
117 _font.setBold(BOLD); WIDGET->setFont(_font); \
119 while(0)
121 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
123 QPalette _palette = WIDGET->palette(); \
124 _palette.setColor(QPalette::WindowText, (COLOR)); \
125 _palette.setColor(QPalette::Text, (COLOR)); \
126 WIDGET->setPalette(_palette); \
128 while(0)
130 #define UPDATE_MIN_WIDTH(WIDGET) do \
132 if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
134 while(0)
136 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
138 if(m_settings->soundsEnabled()) MUtils::Sound::play_sound((NAME), (ASYNC)); \
140 while(0)
142 #define IS_VBR(RC_MODE) ((RC_MODE) == SettingsModel::VBRMode)
144 ////////////////////////////////////////////////////////////
146 //Dummy class for UserData
147 class IntUserData : public QObjectUserData
149 public:
150 IntUserData(int value) : m_value(value) {/*NOP*/}
151 int value(void) { return m_value; }
152 void setValue(int value) { m_value = value; }
153 private:
154 int m_value;
157 ////////////////////////////////////////////////////////////
158 // Constructor
159 ////////////////////////////////////////////////////////////
161 ProcessingDialog::ProcessingDialog(FileListModel *const fileListModel, const AudioFileModel_MetaInfo *const metaInfo, const SettingsModel *const settings, QWidget *const parent)
163 QDialog(parent),
164 ui(new Ui::ProcessingDialog),
165 m_systemTray((!settings->disableTrayIcon()) ? new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this) : NULL),
166 m_taskbar(new MUtils::Taskbar7(this)),
167 m_settings(settings),
168 m_metaInfo(metaInfo),
169 m_shutdownFlag(SHUTDOWN_FLAG_NONE),
170 m_progressViewFilter(-1),
171 m_initThreads(0),
172 m_defaultColor(new QColor()),
173 m_tempFolder(settings->customTempPathEnabled() ? settings->customTempPath() : MUtils::temp_folder()),
174 m_firstShow(true)
176 //Init the dialog, from the .ui file
177 ui->setupUi(this);
178 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
179 setMinimumSize(this->size());
181 //Update the window icon
182 MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
184 //Update header icon
185 ui->label_headerIcon->setPixmap(lamexp_app_icon().pixmap(ui->label_headerIcon->size()));
187 //Setup version info
188 ui->label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
189 ui->label_versionInfo->installEventFilter(this);
191 //Register meta type
192 qRegisterMetaType<QUuid>("QUuid");
194 //Adjust size to DPI settings and re-center
195 MUtils::GUI::scale_widget(this);
197 //Enable buttons
198 connect(ui->button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
200 //Init progress indicator
201 m_progressIndicator.reset(new QMovie(":/images/Working.gif"));
202 m_progressIndicator->setCacheMode(QMovie::CacheAll);
203 ui->label_headerWorking->setMovie(m_progressIndicator.data());
204 ui->progressBar->setValue(0);
206 //Load overlay icons
207 m_iconRunning.reset(new QIcon(":/icons/control_play_blue.png"));
208 m_iconError.reset (new QIcon(":/icons/error.png"));
209 m_iconWarning.reset(new QIcon(":/icons/exclamation.png"));
210 m_iconSuccess.reset(new QIcon(":/icons/accept.png"));
212 //Init progress model
213 m_progressModel.reset(new ProgressModel());
214 ui->view_log->setModel(m_progressModel.data());
215 ui->view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
216 ui->view_log->verticalHeader()->hide();
217 ui->view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
218 ui->view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
219 ui->view_log->viewport()->installEventFilter(this);
220 connect(m_progressModel.data(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
221 connect(m_progressModel.data(), SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(progressModelChanged()));
222 connect(m_progressModel.data(), SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
223 connect(m_progressModel.data(), SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
224 connect(ui->view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
225 connect(ui->view_log->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
227 //Create context menu
228 m_contextMenu.reset(new QMenu());
229 QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
230 QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
231 m_contextMenu->addSeparator();
233 //Create "filter" context menu
234 m_progressViewFilterGroup.reset(new QActionGroup(this));
235 QAction *contextMenuFilterAction[5] = {NULL, NULL, NULL, NULL, NULL};
236 if(QMenu *filterMenu = m_contextMenu->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
238 contextMenuFilterAction[0] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobRunning), tr("Show Running Only"));
239 contextMenuFilterAction[1] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobComplete), tr("Show Succeeded Only"));
240 contextMenuFilterAction[2] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobFailed), tr("Show Failed Only"));
241 contextMenuFilterAction[3] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobSkipped), tr("Show Skipped Only"));
242 contextMenuFilterAction[4] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
243 if(QAction *act = contextMenuFilterAction[0]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobRunning); }
244 if(QAction *act = contextMenuFilterAction[1]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobComplete); }
245 if(QAction *act = contextMenuFilterAction[2]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobFailed); }
246 if(QAction *act = contextMenuFilterAction[3]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobSkipped); }
247 if(QAction *act = contextMenuFilterAction[4]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(-1); act->setChecked(true); }
250 //Create info label
251 m_filterInfoLabel.reset(new QLabel(ui->view_log));
252 m_filterInfoLabel->setFrameShape(QFrame::NoFrame);
253 m_filterInfoLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
254 m_filterInfoLabel->setUserData(0, new IntUserData(-1));
255 SET_FONT_BOLD(m_filterInfoLabel, true);
256 SET_TEXT_COLOR(m_filterInfoLabel, Qt::darkGray);
257 m_filterInfoLabel->setContextMenuPolicy(Qt::CustomContextMenu);
258 connect(m_filterInfoLabel.data(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
259 m_filterInfoLabel->hide();
261 m_filterInfoLabelIcon .reset(new QLabel(ui->view_log));
262 m_filterInfoLabelIcon->setFrameShape(QFrame::NoFrame);
263 m_filterInfoLabelIcon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
264 m_filterInfoLabelIcon->setContextMenuPolicy(Qt::CustomContextMenu);
265 const QIcon &ico = m_progressModel->getIcon(ProgressModel::JobState(-1));
266 m_filterInfoLabelIcon->setPixmap(ico.pixmap(16, 16));
267 connect(m_filterInfoLabelIcon.data(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
268 m_filterInfoLabelIcon->hide();
270 //Connect context menu
271 ui->view_log->setContextMenuPolicy(Qt::CustomContextMenu);
272 connect(ui->view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
273 connect(contextMenuDetailsAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
274 connect(contextMenuShowFileAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
275 for(size_t i = 0; i < 5; i++)
277 if(contextMenuFilterAction[i]) connect(contextMenuFilterAction[i], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
279 SET_FONT_BOLD(contextMenuDetailsAction, true);
281 //Setup file extensions
282 if(!m_settings->renameFiles_fileExtension().isEmpty())
284 m_fileExts.reset(new FileExtsModel());
285 m_fileExts->importItems(m_settings->renameFiles_fileExtension());
288 //Enque jobs
289 if(fileListModel)
291 for(int i = 0; i < fileListModel->rowCount(); i++)
293 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
297 //Translate
298 ui->label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
300 //Enable system tray icon, if enabled
301 if (!m_systemTray.isNull())
303 connect(m_systemTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
306 //Init other vars
307 m_runningThreads = 0;
308 m_currentFile = 0;
309 m_allJobs.clear();
310 m_succeededJobs.clear();
311 m_failedJobs.clear();
312 m_skippedJobs.clear();
313 m_userAborted = false;
314 m_forcedAbort = false;
317 ////////////////////////////////////////////////////////////
318 // Destructor
319 ////////////////////////////////////////////////////////////
321 ProcessingDialog::~ProcessingDialog(void)
323 ui->view_log->setModel(NULL);
325 if(!m_progressIndicator.isNull())
327 m_progressIndicator->stop();
330 if(!m_diskObserver.isNull())
332 m_diskObserver->stop();
333 if(!m_diskObserver->wait(15000))
335 m_diskObserver->terminate();
336 m_diskObserver->wait();
340 if(!m_cpuObserver.isNull())
342 m_cpuObserver->stop();
343 if(!m_cpuObserver->wait(15000))
345 m_cpuObserver->terminate();
346 m_cpuObserver->wait();
350 if(!m_ramObserver.isNull())
352 m_ramObserver->stop();
353 if(!m_ramObserver->wait(15000))
355 m_ramObserver->terminate();
356 m_ramObserver->wait();
360 if(!m_threadPool.isNull())
362 if(!m_threadPool->waitForDone(100))
364 emit abortRunningTasks();
365 m_threadPool->waitForDone();
369 m_taskbar->setOverlayIcon(NULL);
370 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
372 MUTILS_DELETE(ui);
375 ////////////////////////////////////////////////////////////
376 // EVENTS
377 ////////////////////////////////////////////////////////////
379 void ProcessingDialog::showEvent(QShowEvent *event)
381 QDialog::showEvent(event);
383 if(m_firstShow)
385 static const char *NA = " N/A";
387 MUtils::GUI::enable_close_button(this, false);
388 ui->button_closeDialog->setEnabled(false);
389 ui->button_AbortProcess->setEnabled(false);
391 ui->label_cpu->setText(NA);
392 ui->label_disk->setText(NA);
393 ui->label_ram->setText(NA);
395 QTimer::singleShot(100, this, SLOT(prepareEncoding()));
396 m_firstShow = false;
399 //Force update geometry
400 resizeEvent(NULL);
403 void ProcessingDialog::closeEvent(QCloseEvent *event)
405 if(!ui->button_closeDialog->isEnabled())
407 event->ignore();
409 else
411 if (!m_systemTray.isNull())
413 m_systemTray->setVisible(false);
418 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
420 if(obj == ui->label_versionInfo)
422 if(event->type() == QEvent::Enter)
424 QPalette palette = ui->label_versionInfo->palette();
425 *m_defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
426 palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
427 ui->label_versionInfo->setPalette(palette);
429 else if(event->type() == QEvent::Leave)
431 QPalette palette = ui->label_versionInfo->palette();
432 palette.setColor(QPalette::Normal, QPalette::WindowText, *m_defaultColor);
433 ui->label_versionInfo->setPalette(palette);
435 else if(event->type() == QEvent::MouseButtonPress)
437 QUrl url(lamexp_website_url());
438 QDesktopServices::openUrl(url);
442 return false;
445 bool ProcessingDialog::event(QEvent *e)
447 switch(static_cast<qint32>(e->type()))
449 case MUtils::GUI::USER_EVENT_QUERYENDSESSION:
450 qWarning("System is shutting down, preparing to abort...");
451 if(!m_userAborted) abortEncoding(true);
452 return true;
453 case MUtils::GUI::USER_EVENT_ENDSESSION:
454 qWarning("System is shutting down, encoding will be aborted now...");
455 if(isVisible())
457 while(!close())
459 if(!m_userAborted) abortEncoding(true);
460 qApp->processEvents(QEventLoop::WaitForMoreEvents | QEventLoop::ExcludeUserInputEvents);
463 m_pendingJobs.clear();
464 return true;
465 default:
466 return QDialog::event(e);
471 * Window was resized
473 void ProcessingDialog::resizeEvent(QResizeEvent *event)
475 if(event) QDialog::resizeEvent(event);
477 if(QWidget *port = ui->view_log->viewport())
479 QRect geom = port->geometry();
480 m_filterInfoLabel->setGeometry(geom.left() + 16, geom.top() + 16, geom.width() - 32, 48);
481 m_filterInfoLabelIcon->setGeometry(geom.left() + 16, geom.top() + 64, geom.width() - 32, geom.height() - 80);
485 ////////////////////////////////////////////////////////////
486 // SLOTS
487 ////////////////////////////////////////////////////////////
489 void ProcessingDialog::prepareEncoding(void)
491 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
492 QTimer::singleShot(100, this, SLOT(initEncoding()));
495 void ProcessingDialog::initEncoding(void)
497 qDebug("Initializing encoding process...");
499 m_runningThreads = 0;
500 m_currentFile = 0;
501 m_allJobs.clear();
502 m_succeededJobs.clear();
503 m_failedJobs.clear();
504 m_skippedJobs.clear();
505 m_userAborted = m_forcedAbort = false;
506 m_playList.clear();
507 m_progressIndicator->start();
509 MUtils::OS::change_process_priority(1);
510 DecoderRegistry::configureDecoders(m_settings);
512 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor(Qt::white));
514 ui->button_closeDialog->setEnabled(false);
515 ui->button_AbortProcess->setEnabled(true);
516 ui->progressBar->setRange(0, m_pendingJobs.count());
517 ui->checkBox_shutdownComputer->setEnabled(true);
518 ui->checkBox_shutdownComputer->setChecked(false);
520 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
521 m_taskbar->setTaskbarProgress(0, m_pendingJobs.count());
522 m_taskbar->setOverlayIcon(m_iconRunning.data());
524 if(!m_diskObserver)
526 m_diskObserver.reset(new DiskObserverThread(m_tempFolder));
527 connect(m_diskObserver.data(), SIGNAL(messageLogged(QString,int)), m_progressModel.data(), SLOT(addSystemMessage(QString,int)), Qt::QueuedConnection);
528 connect(m_diskObserver.data(), SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
529 m_diskObserver->start();
531 if(!m_cpuObserver)
533 m_cpuObserver.reset(new CPUObserverThread());
534 connect(m_cpuObserver.data(), SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
535 m_cpuObserver->start();
537 if(!m_ramObserver)
539 m_ramObserver.reset(new RAMObserverThread());
540 connect(m_ramObserver.data(), SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
541 m_ramObserver->start();
544 if(m_threadPool.isNull())
546 m_threadPool.reset(createThreadPool());
547 if (m_threadPool->maxThreadCount() > 1)
549 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(m_threadPool->maxThreadCount())));
553 m_initThreads = m_threadPool->maxThreadCount();
554 QTimer::singleShot(100, this, SLOT(initNextJob()));
556 m_totalTime.reset(new QElapsedTimer());
557 m_totalTime->start();
560 void ProcessingDialog::initNextJob(void)
562 if((m_initThreads > 0) && (!m_userAborted))
564 startNextJob();
565 if(--m_initThreads > 0)
567 QTimer::singleShot(50, this, SLOT(initNextJob()));
572 void ProcessingDialog::startNextJob(void)
574 if(m_pendingJobs.isEmpty())
576 qWarning("No more files left, unable to start another job!");
577 return;
580 m_currentFile++;
581 m_runningThreads++;
583 //Fetch next file
584 AudioFileModel currentFile = m_pendingJobs.takeFirst();
585 updateMetaInfo(currentFile);
587 //Create encoder instance
588 AbstractEncoder *encoder = EncoderRegistry::createInstance(m_settings->compressionEncoder(), m_settings);
590 //Create processing thread
591 QScopedPointer<ProcessThread> thread(new ProcessThread
593 currentFile,
594 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
595 m_tempFolder,
596 encoder,
597 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
600 //Add audio filters
601 if(m_settings->forceStereoDownmix())
603 thread->addFilter(new DownmixFilter());
605 if(m_settings->samplingRate() > 0)
607 const int targetRate = SettingsModel::samplingRates[qBound(1, m_settings->samplingRate(), 6)];
608 if((targetRate != static_cast<int>(currentFile.techInfo().audioSamplerate())) || (currentFile.techInfo().audioSamplerate() == 0))
610 if (encoder->toEncoderInfo()->isResamplingSupported())
612 encoder->setSamplingRate(targetRate);
614 else
616 thread->addFilter(new ResampleFilter(targetRate));
620 if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
622 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
624 if(m_settings->normalizationFilterEnabled())
626 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterDynamic(), m_settings->normalizationFilterCoupled(), m_settings->normalizationFilterSize()));
628 if(m_settings->renameFiles_renameEnabled() && (!m_settings->renameFiles_renamePattern().simplified().isEmpty()))
630 thread->setRenamePattern(m_settings->renameFiles_renamePattern());
632 if(m_settings->renameFiles_regExpEnabled() && (!m_settings->renameFiles_regExpSearch().trimmed().isEmpty()) && (!m_settings->renameFiles_regExpReplace().simplified().isEmpty()))
634 thread->setRenameRegExp(m_settings->renameFiles_regExpSearch(), m_settings->renameFiles_regExpReplace());
636 if(!m_fileExts.isNull())
638 thread->setRenameFileExt(m_fileExts->apply(QString::fromUtf8(EncoderRegistry::getEncoderInfo(m_settings->compressionEncoder())->extension())));
640 if(m_settings->overwriteMode() != SettingsModel::Overwrite_KeepBoth)
642 thread->setOverwriteMode((m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile), (m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces));
644 if (m_settings->keepOriginalDataTime())
646 thread->setKeepDateTime(m_settings->keepOriginalDataTime());
649 //Save job UUID
650 m_allJobs.append(thread->getId());
652 //Connect thread signals
653 connect(thread.data(), SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
654 connect(thread.data(), SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel.data(), SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
655 connect(thread.data(), SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel.data(), SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
656 connect(thread.data(), SIGNAL(processStateFinished(QUuid,QString,int)), this, SLOT(processFinished(QUuid,QString,int)), Qt::QueuedConnection);
657 connect(thread.data(), SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel.data(), SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
658 connect(this, SIGNAL(abortRunningTasks()), thread.data(), SLOT(abort()), Qt::DirectConnection);
660 //Initialize thread object
661 if(!thread->init())
663 qFatal("Fatal Error: Thread initialization has failed!");
666 //Give it a go!
667 if(!thread->start(m_threadPool.data()))
669 qWarning("Job failed to start or the file was skipped!");
670 return;
673 thread.take(); //will be auto-deleted by QThreadPool!
676 void ProcessingDialog::abortEncoding(bool force)
678 m_userAborted = true;
679 if(force) m_forcedAbort = true;
680 ui->button_AbortProcess->setEnabled(false);
681 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
682 emit abortRunningTasks();
685 void ProcessingDialog::doneEncoding(void)
687 m_runningThreads--;
688 ui->progressBar->setValue(ui->progressBar->value() + 1);
690 if(!m_userAborted)
692 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui->progressBar->value()).arg(QString::number(ui->progressBar->maximum())));
693 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
696 if((!m_pendingJobs.isEmpty()) && (!m_userAborted))
698 QTimer::singleShot(25, this, SLOT(startNextJob()));
699 qDebug("%d files left, starting next job...", m_pendingJobs.count());
700 return;
703 if(m_runningThreads > 0)
705 qDebug("No files left, but still have %u running jobs.", m_runningThreads);
706 return;
709 QApplication::setOverrideCursor(Qt::WaitCursor);
710 qDebug("Running jobs: %u", m_runningThreads);
712 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
714 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
715 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
716 writePlayList();
719 if(m_userAborted)
721 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFFFE0"));
722 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
723 m_taskbar->setOverlayIcon(m_iconError.data());
724 SET_PROGRESS_TEXT((m_succeededJobs.count() > 0) ? tr("Process was aborted by the user after %n file(s)!", "", m_succeededJobs.count()) : tr("Process was aborted prematurely by the user!"));
725 SET_PROGRESS_MESG(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning, QIcon(":/icons/cd_delete.png"));
726 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
727 if(!m_forcedAbort) PLAY_SOUND_OPTIONAL("aborted", false);
729 else
731 if((!m_totalTime.isNull()) && m_totalTime->isValid())
733 m_progressModel->addSystemMessage(tr("Process finished after %1.").arg(time2text(m_totalTime->elapsed())), ProgressModel::SysMsg_Performance);
734 m_totalTime->invalidate();
737 if(m_failedJobs.count() > 0)
739 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFF0F0"));
740 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
741 m_taskbar->setOverlayIcon(m_iconWarning.data());
742 if(m_skippedJobs.count() > 0)
744 SET_PROGRESS_TEXT(tr("Error: %1 of %n file(s) failed (%2). Double-click failed items for detailed information!", "", m_failedJobs.count() + m_succeededJobs.count() + m_skippedJobs.count()).arg(QString::number(m_failedJobs.count()), tr("%n file(s) skipped", "", m_skippedJobs.count())));
746 else
748 SET_PROGRESS_TEXT(tr("Error: %1 of %n file(s) failed. Double-click failed items for detailed information!", "", m_failedJobs.count() + m_succeededJobs.count()).arg(QString::number(m_failedJobs.count())));
750 SET_PROGRESS_MESG(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical, QIcon(":/icons/cd_delete.png"));
751 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
752 PLAY_SOUND_OPTIONAL("error", false);
754 else
756 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#F0FFF0"));
757 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
758 m_taskbar->setOverlayIcon(m_iconSuccess.data());
759 if(m_skippedJobs.count() > 0)
761 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs.count()));
763 else
765 SET_PROGRESS_TEXT(tr("All files completed successfully."));
767 SET_PROGRESS_MESG(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information, QIcon(":/icons/cd_add.png"));
768 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
769 PLAY_SOUND_OPTIONAL("success", false);
773 MUtils::GUI::enable_close_button(this, true);
774 ui->button_closeDialog->setEnabled(true);
775 ui->button_AbortProcess->setEnabled(false);
776 ui->checkBox_shutdownComputer->setEnabled(false);
778 m_progressModel->restoreHiddenItems();
779 ui->view_log->scrollToBottom();
780 m_progressIndicator->stop();
781 ui->progressBar->setValue(ui->progressBar->maximum());
782 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
784 QApplication::restoreOverrideCursor();
786 if(!m_userAborted && ui->checkBox_shutdownComputer->isChecked())
788 if(shutdownComputer())
790 m_shutdownFlag = m_settings->hibernateComputer() ? SHUTDOWN_FLAG_HIBERNATE : SHUTDOWN_FLAG_POWER_OFF;
791 accept();
796 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, int success)
798 if(success > 0)
800 m_playList.insert(jobId, outFileName);
801 m_succeededJobs.append(jobId);
803 else if(success < 0)
805 m_playList.insert(jobId, outFileName);
806 m_skippedJobs.append(jobId);
808 else
810 m_failedJobs.append(jobId);
813 //Update filter as soon as a job finished!
814 if(m_progressViewFilter >= 0)
816 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
820 void ProcessingDialog::progressModelChanged(void)
822 //Update filter as soon as the model changes!
823 if(m_progressViewFilter >= 0)
825 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
828 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
831 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
833 if(m_runningThreads == 0)
835 const QStringList &logFile = m_progressModel->getLogFile(index);
837 if(!logFile.isEmpty())
839 LogViewDialog *logView = new LogViewDialog(this);
840 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
841 logView->exec(logFile);
842 MUTILS_DELETE(logView);
844 else
846 QMessageBox::information(this, windowTitle(), m_progressModel->data(m_progressModel->index(index.row(), 0)).toString());
849 else
851 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
855 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int /*oldSize*/, int /*newSize*/)
857 if(logicalIndex == 1)
859 if(QHeaderView *hdr = ui->view_log->horizontalHeader())
861 hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
866 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
868 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
869 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
871 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
873 m_contextMenu->popup(sender->mapToGlobal(pos));
877 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
879 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
880 logViewDoubleClicked(index.isValid() ? index : ui->view_log->currentIndex());
883 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
885 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
886 const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : ui->view_log->currentIndex());
887 QString filePath = m_playList.value(jobId, QString());
889 if(filePath.isEmpty())
891 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
892 return;
895 if(QFileInfo(filePath).exists())
897 const QString systemRootPath = MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSROOT);
898 if(!systemRootPath.isEmpty())
900 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
901 if(explorer.exists() && explorer.isFile())
903 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
904 return;
907 else
909 qWarning("SystemRoot directory could not be detected!");
912 else
914 qWarning("File not found: %s", filePath.toLatin1().constData());
915 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
919 void ProcessingDialog::contextMenuFilterActionTriggered(void)
921 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
923 if(action->data().type() == QVariant::Int)
925 m_progressViewFilter = action->data().toInt();
926 progressViewFilterChanged();
927 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
928 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
929 action->setChecked(true);
935 * Filter progress items
937 void ProcessingDialog::progressViewFilterChanged(void)
939 bool matchFound = false;
941 for(int i = 0; i < ui->view_log->model()->rowCount(); i++)
943 QModelIndex index = (m_progressViewFilter >= 0) ? m_progressModel->index(i, 0) : QModelIndex();
944 const bool bHide = index.isValid() ? (m_progressModel->getJobState(index) != m_progressViewFilter) : false;
945 ui->view_log->setRowHidden(i, bHide); matchFound = matchFound || (!bHide);
948 if((m_progressViewFilter >= 0) && (!matchFound))
950 if(m_filterInfoLabel->isHidden() || (dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->value() != m_progressViewFilter))
952 dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->setValue(m_progressViewFilter);
953 m_filterInfoLabel->setText(QString("<p>&raquo; %1 &laquo;</p>").arg(tr("None of the items matches the current filtering rules")));
954 m_filterInfoLabel->show();
955 m_filterInfoLabelIcon->setPixmap(m_progressModel->getIcon(static_cast<ProgressModel::JobState>(m_progressViewFilter)).pixmap(16, 16, QIcon::Disabled));
956 m_filterInfoLabelIcon->show();
957 resizeEvent(NULL);
960 else if(!m_filterInfoLabel->isHidden())
962 m_filterInfoLabel->hide();
963 m_filterInfoLabelIcon->hide();
967 ////////////////////////////////////////////////////////////
968 // Private Functions
969 ////////////////////////////////////////////////////////////
971 QThreadPool *ProcessingDialog::createThreadPool(void)
973 quint32 maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
974 if (maximumInstances < 1U)
976 const MUtils::CPUFetaures::cpu_info_t cpuFeatures = MUtils::CPUFetaures::detect();
977 const quint32 nProcessors = qBound(1U, cpuFeatures.count, MAX_INSTANCES);
978 maximumInstances = isFastSeekingDevice(m_tempFolder) ? nProcessors : cores2instances(nProcessors);
980 QThreadPool *const threadPool = new QThreadPool();
981 threadPool->setMaxThreadCount(qBound(1U, maximumInstances, static_cast<unsigned int>(m_pendingJobs.count())));
982 return threadPool;
985 void ProcessingDialog::writePlayList(void)
987 if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
989 qWarning("WritePlayList: Nothing to do!");
990 return;
993 //Init local variables
994 QStringList list;
995 QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
996 QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
997 QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
998 bool usePrefix[3] = {true, true, true};
999 bool useUtf8 = false;
1000 int counter = 1;
1002 //Generate playlist name
1003 QString playListName = (m_metaInfo->album().isEmpty() ? "Playlist" : m_metaInfo->album());
1004 if(!m_metaInfo->artist().isEmpty())
1006 playListName = QString("%1 - %2").arg(m_metaInfo->artist(), playListName);
1009 //Clean playlist name
1010 playListName = MUtils::clean_file_name(playListName, true);
1012 //Create list of audio files
1013 for(int i = 0; i < m_allJobs.count(); i++)
1015 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
1016 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
1019 //Use prefix?
1020 for(int i = 0; i < list.count(); i++)
1022 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
1023 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
1024 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
1026 if(usePrefix[0] || usePrefix[1] || usePrefix[2])
1028 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
1031 //Do we need an UTF-8 playlist?
1032 for(int i = 0; i < list.count(); i++)
1034 if(wcscmp(MUTILS_WCHR(QString::fromLatin1(list.at(i).toLatin1().constData())), MUTILS_WCHR(list.at(i))))
1036 useUtf8 = true;
1037 break;
1041 //Generate playlist output file
1042 QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
1043 while(QFileInfo(playListFile).exists())
1045 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
1048 //Now write playlist to output file
1049 QFile playList(playListFile);
1050 if(playList.open(QIODevice::WriteOnly))
1052 if(useUtf8)
1054 playList.write("\xef\xbb\xbf");
1056 playList.write("#EXTM3U\r\n");
1057 while(!list.isEmpty())
1059 playList.write(useUtf8 ? MUTILS_UTF8(list.takeFirst()) : list.takeFirst().toLatin1().constData());
1060 playList.write("\r\n");
1062 playList.close();
1064 else
1066 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
1070 void ProcessingDialog::updateMetaInfo(AudioFileModel &audioFile)
1072 if(!m_settings->writeMetaTags())
1074 audioFile.metaInfo().reset();
1075 return;
1078 audioFile.metaInfo().update(*m_metaInfo, true);
1080 if(audioFile.metaInfo().position() == UINT_MAX)
1082 audioFile.metaInfo().setPosition(m_currentFile);
1086 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
1088 if(reason == QSystemTrayIcon::DoubleClick)
1090 MUtils::GUI::bring_to_front(this);
1094 void ProcessingDialog::cpuUsageHasChanged(const double val)
1097 ui->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1098 UPDATE_MIN_WIDTH(ui->label_cpu);
1101 void ProcessingDialog::ramUsageHasChanged(const double val)
1104 ui->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1105 UPDATE_MIN_WIDTH(ui->label_ram);
1108 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
1110 int postfix = 0;
1111 const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1112 double space = static_cast<double>(val);
1114 while((space >= 1000.0) && (postfix < 5))
1116 space = space / 1024.0;
1117 postfix++;
1120 ui->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
1121 UPDATE_MIN_WIDTH(ui->label_disk);
1124 bool ProcessingDialog::shutdownComputer(void)
1126 const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
1127 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
1128 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1130 qWarning("Initiating shutdown sequence!");
1132 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
1133 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
1134 cancelButton->setIcon(QIcon(":/icons/power_on.png"));
1135 progressDialog.setModal(true);
1136 progressDialog.setAutoClose(false);
1137 progressDialog.setAutoReset(false);
1138 progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
1139 progressDialog.setCancelButton(cancelButton);
1140 progressDialog.show();
1142 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1144 QApplication::setOverrideCursor(Qt::WaitCursor);
1145 PLAY_SOUND_OPTIONAL("shutdown", false);
1146 QApplication::restoreOverrideCursor();
1148 QTimer timer;
1149 timer.setInterval(1000);
1150 timer.start();
1152 QEventLoop eventLoop(this);
1153 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
1154 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
1156 for(int i = 1; i <= iTimeout; i++)
1158 eventLoop.exec();
1159 if(progressDialog.wasCanceled())
1161 progressDialog.close();
1162 return false;
1164 progressDialog.setValue(i+1);
1165 progressDialog.setLabelText(text.arg(iTimeout-i));
1166 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
1167 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1168 PLAY_SOUND_OPTIONAL(((i < iTimeout) ? "beep" : "beep2"), false);
1171 progressDialog.close();
1172 return true;
1175 ////////////////////////////////////////////////////////////
1176 // HELPER FUNCTIONS
1177 ////////////////////////////////////////////////////////////
1179 bool ProcessingDialog::isFastSeekingDevice(const QString &path)
1181 bool haveFastSeeking;
1182 if (MUtils::OS::get_drive_type(path, &haveFastSeeking) != MUtils::OS::DRIVE_TYPE_ERR)
1184 return haveFastSeeking;
1186 return false;
1189 quint32 ProcessingDialog::cores2instances(const quint32 &cores)
1191 //This function is a "cubic spline" with sampling points at:
1192 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1193 static const double LUT[8][5] =
1195 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1196 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1197 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1198 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1199 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1200 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1201 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1202 {DBL_MAX, 0.0, 0.0, 0.0, 0.0}
1205 double x = abs(static_cast<double>(cores)), y = 1.0;
1207 for(size_t i = 0; i < 7; i++)
1209 if((x >= LUT[i][0]) && (x < LUT[i+1][0]))
1211 y = (((((LUT[i][1] * x) + LUT[i][2]) * x) + LUT[i][3]) * x) + LUT[i][4];
1212 break;
1216 return static_cast<quint32>(qRound(y));
1219 QString ProcessingDialog::time2text(const qint64 &msec)
1221 const qint64 MILLISECONDS_PER_DAY = 86399999; //24x60x60x1000 - 1
1222 const QTime time = QTime().addMSecs(qMin(msec, MILLISECONDS_PER_DAY));
1224 QString a, b;
1226 if (time.hour() > 0)
1228 a = tr("%n hour(s)", "", time.hour());
1229 b = tr("%n minute(s)", "", time.minute());
1231 else if (time.minute() > 0)
1233 a = tr("%n minute(s)", "", time.minute());
1234 b = tr("%n second(s)", "", time.second());
1236 else
1238 a = tr("%n second(s)", "", time.second());
1239 b = tr("%n millisecond(s)", "", time.msec());
1242 return QString("%1, %2").arg(a, b);