Adapt for latest MUtils changes.
[LameXP.git] / src / Dialog_Processing.cpp
blobddb9a2b22fc92e9b65e801c76455022a98e720e4
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2016 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, but always including the *additional*
9 // restrictions defined in the "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 ////////////////////////////////////////////////////////////
82 //Maximum number of parallel instances
83 #define MAX_INSTANCES 32U
85 //Function to calculate the number of instances
86 static int cores2instances(int cores);
88 ////////////////////////////////////////////////////////////
90 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
91 { \
92 QPalette palette = WIDGET->palette(); \
93 palette.setColor(QPalette::Background, COLOR); \
94 WIDGET->setPalette(palette); \
95 } \
96 while(0)
98 #define SET_PROGRESS_TEXT(TXT) do \
99 { \
100 ui->label_progress->setText(TXT); \
101 if(!m_systemTray.isNull()) \
103 if(!m_systemTray->isVisible()) m_systemTray->setVisible(true); \
104 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
107 while(0)
109 #define SET_FONT_BOLD(WIDGET,BOLD) do \
111 QFont _font = WIDGET->font(); \
112 _font.setBold(BOLD); WIDGET->setFont(_font); \
114 while(0)
116 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
118 QPalette _palette = WIDGET->palette(); \
119 _palette.setColor(QPalette::WindowText, (COLOR)); \
120 _palette.setColor(QPalette::Text, (COLOR)); \
121 WIDGET->setPalette(_palette); \
123 while(0)
125 #define UPDATE_MIN_WIDTH(WIDGET) do \
127 if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
129 while(0)
131 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
133 if(m_settings->soundsEnabled()) MUtils::Sound::play_sound((NAME), (ASYNC)); \
135 while(0)
137 #define IS_VBR(RC_MODE) ((RC_MODE) == SettingsModel::VBRMode)
139 ////////////////////////////////////////////////////////////
141 //Dummy class for UserData
142 class IntUserData : public QObjectUserData
144 public:
145 IntUserData(int value) : m_value(value) {/*NOP*/}
146 int value(void) { return m_value; }
147 void setValue(int value) { m_value = value; }
148 private:
149 int m_value;
152 ////////////////////////////////////////////////////////////
153 // Constructor
154 ////////////////////////////////////////////////////////////
156 ProcessingDialog::ProcessingDialog(FileListModel *const fileListModel, const AudioFileModel_MetaInfo *const metaInfo, const SettingsModel *const settings, QWidget *const parent)
158 QDialog(parent),
159 ui(new Ui::ProcessingDialog),
160 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
161 m_taskbar(new MUtils::Taskbar7(this)),
162 m_settings(settings),
163 m_metaInfo(metaInfo),
164 m_shutdownFlag(SHUTDOWN_FLAG_NONE),
165 m_progressViewFilter(-1),
166 m_initThreads(0),
167 m_defaultColor(new QColor()),
168 m_firstShow(true)
170 //Init the dialog, from the .ui file
171 ui->setupUi(this);
172 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
174 //Update the window icon
175 MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
177 //Update header icon
178 ui->label_headerIcon->setPixmap(lamexp_app_icon().pixmap(ui->label_headerIcon->size()));
180 //Setup version info
181 ui->label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
182 ui->label_versionInfo->installEventFilter(this);
184 //Register meta type
185 qRegisterMetaType<QUuid>("QUuid");
187 //Center window in screen
188 QRect desktopRect = QApplication::desktop()->screenGeometry();
189 QRect thisRect = this->geometry();
190 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
191 setMinimumSize(thisRect.width(), thisRect.height());
193 //Enable buttons
194 connect(ui->button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
196 //Init progress indicator
197 m_progressIndicator.reset(new QMovie(":/images/Working.gif"));
198 m_progressIndicator->setCacheMode(QMovie::CacheAll);
199 ui->label_headerWorking->setMovie(m_progressIndicator.data());
200 ui->progressBar->setValue(0);
202 //Init progress model
203 m_progressModel.reset(new ProgressModel());
204 ui->view_log->setModel(m_progressModel.data());
205 ui->view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
206 ui->view_log->verticalHeader()->hide();
207 ui->view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
208 ui->view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
209 ui->view_log->viewport()->installEventFilter(this);
210 connect(m_progressModel.data(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
211 connect(m_progressModel.data(), SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(progressModelChanged()));
212 connect(m_progressModel.data(), SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
213 connect(m_progressModel.data(), SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
214 connect(ui->view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
215 connect(ui->view_log->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
217 //Create context menu
218 m_contextMenu.reset(new QMenu());
219 QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
220 QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
221 m_contextMenu->addSeparator();
223 //Create "filter" context menu
224 m_progressViewFilterGroup.reset(new QActionGroup(this));
225 QAction *contextMenuFilterAction[5] = {NULL, NULL, NULL, NULL, NULL};
226 if(QMenu *filterMenu = m_contextMenu->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
228 contextMenuFilterAction[0] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobRunning), tr("Show Running Only"));
229 contextMenuFilterAction[1] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobComplete), tr("Show Succeeded Only"));
230 contextMenuFilterAction[2] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobFailed), tr("Show Failed Only"));
231 contextMenuFilterAction[3] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobSkipped), tr("Show Skipped Only"));
232 contextMenuFilterAction[4] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
233 if(QAction *act = contextMenuFilterAction[0]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobRunning); }
234 if(QAction *act = contextMenuFilterAction[1]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobComplete); }
235 if(QAction *act = contextMenuFilterAction[2]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobFailed); }
236 if(QAction *act = contextMenuFilterAction[3]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobSkipped); }
237 if(QAction *act = contextMenuFilterAction[4]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(-1); act->setChecked(true); }
240 //Create info label
241 m_filterInfoLabel.reset(new QLabel(ui->view_log));
242 m_filterInfoLabel->setFrameShape(QFrame::NoFrame);
243 m_filterInfoLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
244 m_filterInfoLabel->setUserData(0, new IntUserData(-1));
245 SET_FONT_BOLD(m_filterInfoLabel, true);
246 SET_TEXT_COLOR(m_filterInfoLabel, Qt::darkGray);
247 m_filterInfoLabel->setContextMenuPolicy(Qt::CustomContextMenu);
248 connect(m_filterInfoLabel.data(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
249 m_filterInfoLabel->hide();
251 m_filterInfoLabelIcon .reset(new QLabel(ui->view_log));
252 m_filterInfoLabelIcon->setFrameShape(QFrame::NoFrame);
253 m_filterInfoLabelIcon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
254 m_filterInfoLabelIcon->setContextMenuPolicy(Qt::CustomContextMenu);
255 const QIcon &ico = m_progressModel->getIcon(ProgressModel::JobState(-1));
256 m_filterInfoLabelIcon->setPixmap(ico.pixmap(16, 16));
257 connect(m_filterInfoLabelIcon.data(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
258 m_filterInfoLabelIcon->hide();
260 //Connect context menu
261 ui->view_log->setContextMenuPolicy(Qt::CustomContextMenu);
262 connect(ui->view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
263 connect(contextMenuDetailsAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
264 connect(contextMenuShowFileAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
265 for(size_t i = 0; i < 5; i++)
267 if(contextMenuFilterAction[i]) connect(contextMenuFilterAction[i], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
269 SET_FONT_BOLD(contextMenuDetailsAction, true);
271 //Setup file extensions
272 if(!m_settings->renameFiles_fileExtension().isEmpty())
274 m_fileExts.reset(new FileExtsModel());
275 m_fileExts->importItems(m_settings->renameFiles_fileExtension());
278 //Enque jobs
279 if(fileListModel)
281 for(int i = 0; i < fileListModel->rowCount(); i++)
283 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
287 //Translate
288 ui->label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
290 //Enable system tray icon
291 connect(m_systemTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
293 //Init other vars
294 m_runningThreads = 0;
295 m_currentFile = 0;
296 m_allJobs.clear();
297 m_succeededJobs.clear();
298 m_failedJobs.clear();
299 m_skippedJobs.clear();
300 m_userAborted = false;
301 m_forcedAbort = false;
304 ////////////////////////////////////////////////////////////
305 // Destructor
306 ////////////////////////////////////////////////////////////
308 ProcessingDialog::~ProcessingDialog(void)
310 ui->view_log->setModel(NULL);
312 if(!m_progressIndicator.isNull())
314 m_progressIndicator->stop();
317 if(!m_diskObserver.isNull())
319 m_diskObserver->stop();
320 if(!m_diskObserver->wait(15000))
322 m_diskObserver->terminate();
323 m_diskObserver->wait();
327 if(!m_cpuObserver.isNull())
329 m_cpuObserver->stop();
330 if(!m_cpuObserver->wait(15000))
332 m_cpuObserver->terminate();
333 m_cpuObserver->wait();
337 if(!m_ramObserver.isNull())
339 m_ramObserver->stop();
340 if(!m_ramObserver->wait(15000))
342 m_ramObserver->terminate();
343 m_ramObserver->wait();
347 if(!m_threadPool.isNull())
349 if(!m_threadPool->waitForDone(100))
351 emit abortRunningTasks();
352 m_threadPool->waitForDone();
356 m_taskbar->setOverlayIcon(NULL);
357 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
359 MUTILS_DELETE(ui);
362 ////////////////////////////////////////////////////////////
363 // EVENTS
364 ////////////////////////////////////////////////////////////
366 void ProcessingDialog::showEvent(QShowEvent *event)
368 QDialog::showEvent(event);
370 if(m_firstShow)
372 static const char *NA = " N/A";
374 MUtils::GUI::enable_close_button(this, false);
375 ui->button_closeDialog->setEnabled(false);
376 ui->button_AbortProcess->setEnabled(false);
378 MUtils::OS::change_process_priority(1);
380 ui->label_cpu->setText(NA);
381 ui->label_disk->setText(NA);
382 ui->label_ram->setText(NA);
384 QTimer::singleShot(500, this, SLOT(initEncoding()));
385 m_firstShow = false;
388 //Force update geometry
389 resizeEvent(NULL);
392 void ProcessingDialog::closeEvent(QCloseEvent *event)
394 if(!ui->button_closeDialog->isEnabled())
396 event->ignore();
398 else
400 m_systemTray->setVisible(false);
404 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
406 if(obj == ui->label_versionInfo)
408 if(event->type() == QEvent::Enter)
410 QPalette palette = ui->label_versionInfo->palette();
411 *m_defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
412 palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
413 ui->label_versionInfo->setPalette(palette);
415 else if(event->type() == QEvent::Leave)
417 QPalette palette = ui->label_versionInfo->palette();
418 palette.setColor(QPalette::Normal, QPalette::WindowText, *m_defaultColor);
419 ui->label_versionInfo->setPalette(palette);
421 else if(event->type() == QEvent::MouseButtonPress)
423 QUrl url(lamexp_website_url());
424 QDesktopServices::openUrl(url);
428 return false;
431 bool ProcessingDialog::event(QEvent *e)
433 switch(e->type())
435 case MUtils::GUI::USER_EVENT_QUERYENDSESSION:
436 qWarning("System is shutting down, preparing to abort...");
437 if(!m_userAborted) abortEncoding(true);
438 return true;
439 case MUtils::GUI::USER_EVENT_ENDSESSION:
440 qWarning("System is shutting down, encoding will be aborted now...");
441 if(isVisible())
443 while(!close())
445 if(!m_userAborted) abortEncoding(true);
446 qApp->processEvents(QEventLoop::WaitForMoreEvents | QEventLoop::ExcludeUserInputEvents);
449 m_pendingJobs.clear();
450 return true;
451 default:
452 return QDialog::event(e);
457 * Window was resized
459 void ProcessingDialog::resizeEvent(QResizeEvent *event)
461 if(event) QDialog::resizeEvent(event);
463 if(QWidget *port = ui->view_log->viewport())
465 QRect geom = port->geometry();
466 m_filterInfoLabel->setGeometry(geom.left() + 16, geom.top() + 16, geom.width() - 32, 48);
467 m_filterInfoLabelIcon->setGeometry(geom.left() + 16, geom.top() + 64, geom.width() - 32, geom.height() - 80);
471 ////////////////////////////////////////////////////////////
472 // SLOTS
473 ////////////////////////////////////////////////////////////
475 void ProcessingDialog::initEncoding(void)
477 qDebug("Initializing encoding process...");
479 m_runningThreads = 0;
480 m_currentFile = 0;
481 m_allJobs.clear();
482 m_succeededJobs.clear();
483 m_failedJobs.clear();
484 m_skippedJobs.clear();
485 m_userAborted = m_forcedAbort = false;
486 m_playList.clear();
487 m_progressIndicator->start();
489 DecoderRegistry::configureDecoders(m_settings);
491 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor(Qt::white));
492 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
494 ui->button_closeDialog->setEnabled(false);
495 ui->button_AbortProcess->setEnabled(true);
496 ui->progressBar->setRange(0, m_pendingJobs.count());
497 ui->checkBox_shutdownComputer->setEnabled(true);
498 ui->checkBox_shutdownComputer->setChecked(false);
500 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
501 m_taskbar->setTaskbarProgress(0, m_pendingJobs.count());
502 m_taskbar->setOverlayIcon(&QIcon(":/icons/control_play_blue.png"));
504 if(!m_diskObserver)
506 m_diskObserver.reset(new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder()));
507 connect(m_diskObserver.data(), SIGNAL(messageLogged(QString,int)), m_progressModel.data(), SLOT(addSystemMessage(QString,int)), Qt::QueuedConnection);
508 connect(m_diskObserver.data(), SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
509 m_diskObserver->start();
511 if(!m_cpuObserver)
513 m_cpuObserver.reset(new CPUObserverThread());
514 connect(m_cpuObserver.data(), SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
515 m_cpuObserver->start();
517 if(!m_ramObserver)
519 m_ramObserver.reset(new RAMObserverThread());
520 connect(m_ramObserver.data(), SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
521 m_ramObserver->start();
524 if(m_threadPool.isNull())
526 unsigned int maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
527 if(maximumInstances < 1)
529 const MUtils::CPUFetaures::cpu_info_t cpuFeatures = MUtils::CPUFetaures::detect();
530 maximumInstances = cores2instances(qBound(1U, cpuFeatures.count, 64U));
533 maximumInstances = qBound(1U, maximumInstances, static_cast<unsigned int>(m_pendingJobs.count()));
534 if(maximumInstances > 1)
536 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances)));
539 m_threadPool.reset(new QThreadPool());
540 m_threadPool->setMaxThreadCount(maximumInstances);
543 m_initThreads = m_threadPool->maxThreadCount();
544 QTimer::singleShot(100, this, SLOT(initNextJob()));
546 m_totalTime.reset(new QElapsedTimer());
547 m_totalTime->start();
550 void ProcessingDialog::initNextJob(void)
552 if((m_initThreads > 0) && (!m_userAborted))
554 startNextJob();
555 if(--m_initThreads > 0)
557 QTimer::singleShot(32, this, SLOT(initNextJob()));
562 void ProcessingDialog::startNextJob(void)
564 if(m_pendingJobs.isEmpty())
566 qWarning("No more files left, unable to start another job!");
567 return;
570 m_currentFile++;
571 m_runningThreads++;
573 AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
575 //Create encoder instance
576 AbstractEncoder *encoder = EncoderRegistry::createInstance(m_settings->compressionEncoder(), m_settings);
578 //Create processing thread
579 ProcessThread *thread = new ProcessThread
581 currentFile,
582 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
583 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder()),
584 encoder,
585 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
588 //Add audio filters
589 if(m_settings->forceStereoDownmix())
591 thread->addFilter(new DownmixFilter());
593 if(m_settings->samplingRate() > 0)
595 const int targetRate = SettingsModel::samplingRates[qBound(1, m_settings->samplingRate(), 6)];
596 if((targetRate != currentFile.techInfo().audioSamplerate()) || (currentFile.techInfo().audioSamplerate() == 0))
598 if (encoder->toEncoderInfo()->isResamplingSupported())
600 encoder->setSamplingRate(targetRate);
602 else
604 thread->addFilter(new ResampleFilter(targetRate));
608 if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
610 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
612 if(m_settings->normalizationFilterEnabled())
614 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterDynamic(), m_settings->normalizationFilterCoupled(), m_settings->normalizationFilterSize()));
616 if(m_settings->renameFiles_renameEnabled() && (!m_settings->renameFiles_renamePattern().simplified().isEmpty()))
618 thread->setRenamePattern(m_settings->renameFiles_renamePattern());
620 if(m_settings->renameFiles_regExpEnabled() && (!m_settings->renameFiles_regExpSearch().trimmed().isEmpty()) && (!m_settings->renameFiles_regExpReplace().simplified().isEmpty()))
622 thread->setRenameRegExp(m_settings->renameFiles_regExpSearch(), m_settings->renameFiles_regExpReplace());
624 if(!m_fileExts.isNull())
626 thread->setRenameFileExt(m_fileExts->apply(QString::fromUtf8(EncoderRegistry::getEncoderInfo(m_settings->compressionEncoder())->extension())));
628 if(m_settings->overwriteMode() != SettingsModel::Overwrite_KeepBoth)
630 thread->setOverwriteMode((m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile), (m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces));
632 if (m_settings->keepOriginalDataTime())
634 thread->setKeepDateTime(m_settings->keepOriginalDataTime());
637 m_allJobs.append(thread->getId());
639 //Connect thread signals
640 connect(thread, SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
641 connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel.data(), SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
642 connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel.data(), SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
643 connect(thread, SIGNAL(processStateFinished(QUuid,QString,int)), this, SLOT(processFinished(QUuid,QString,int)), Qt::QueuedConnection);
644 connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel.data(), SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
645 connect(this, SIGNAL(abortRunningTasks()), thread, SLOT(abort()), Qt::DirectConnection);
647 //Initialize thread object
648 if(!thread->init())
650 qFatal("Fatal Error: Thread initialization has failed!");
653 //Give it a go!
654 if(!thread->start(m_threadPool.data()))
656 qWarning("Job failed to start or file was skipped!");
660 void ProcessingDialog::abortEncoding(bool force)
662 m_userAborted = true;
663 if(force) m_forcedAbort = true;
664 ui->button_AbortProcess->setEnabled(false);
665 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
666 emit abortRunningTasks();
669 void ProcessingDialog::doneEncoding(void)
671 m_runningThreads--;
672 ui->progressBar->setValue(ui->progressBar->value() + 1);
674 if(!m_userAborted)
676 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui->progressBar->value()).arg(QString::number(ui->progressBar->maximum())));
677 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
680 if((!m_pendingJobs.isEmpty()) && (!m_userAborted))
682 QTimer::singleShot(0, this, SLOT(startNextJob()));
683 qDebug("%d files left, starting next job...", m_pendingJobs.count());
684 return;
687 if(m_runningThreads > 0)
689 qDebug("No files left, but still have %u running jobs.", m_runningThreads);
690 return;
693 QApplication::setOverrideCursor(Qt::WaitCursor);
694 qDebug("Running jobs: %u", m_runningThreads);
696 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
698 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
699 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
700 writePlayList();
703 if(m_userAborted)
705 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFFFE0"));
706 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
707 m_taskbar->setOverlayIcon(&QIcon(":/icons/error.png"));
708 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!"));
709 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
710 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
711 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
712 if(!m_forcedAbort) PLAY_SOUND_OPTIONAL("aborted", false);
714 else
716 if((!m_totalTime.isNull()) && m_totalTime->isValid())
718 m_progressModel->addSystemMessage(tr("Process finished after %1.").arg(time2text(m_totalTime->elapsed())), ProgressModel::SysMsg_Performance);
719 m_totalTime->invalidate();
722 if(m_failedJobs.count() > 0)
724 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFF0F0"));
725 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
726 m_taskbar->setOverlayIcon(&QIcon(":/icons/exclamation.png"));
727 if(m_skippedJobs.count() > 0)
729 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())));
731 else
733 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())));
735 m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
736 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
737 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
738 PLAY_SOUND_OPTIONAL("error", false);
740 else
742 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#F0FFF0"));
743 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
744 m_taskbar->setOverlayIcon(&QIcon(":/icons/accept.png"));
745 if(m_skippedJobs.count() > 0)
747 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs.count()));
749 else
751 SET_PROGRESS_TEXT(tr("All files completed successfully."));
753 m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
754 m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
755 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
756 PLAY_SOUND_OPTIONAL("success", false);
760 MUtils::GUI::enable_close_button(this, true);
761 ui->button_closeDialog->setEnabled(true);
762 ui->button_AbortProcess->setEnabled(false);
763 ui->checkBox_shutdownComputer->setEnabled(false);
765 m_progressModel->restoreHiddenItems();
766 ui->view_log->scrollToBottom();
767 m_progressIndicator->stop();
768 ui->progressBar->setValue(ui->progressBar->maximum());
769 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
771 QApplication::restoreOverrideCursor();
773 if(!m_userAborted && ui->checkBox_shutdownComputer->isChecked())
775 if(shutdownComputer())
777 m_shutdownFlag = m_settings->hibernateComputer() ? SHUTDOWN_FLAG_HIBERNATE : SHUTDOWN_FLAG_POWER_OFF;
778 accept();
783 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, int success)
785 if(success > 0)
787 m_playList.insert(jobId, outFileName);
788 m_succeededJobs.append(jobId);
790 else if(success < 0)
792 m_playList.insert(jobId, outFileName);
793 m_skippedJobs.append(jobId);
795 else
797 m_failedJobs.append(jobId);
800 //Update filter as soon as a job finished!
801 if(m_progressViewFilter >= 0)
803 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
807 void ProcessingDialog::progressModelChanged(void)
809 //Update filter as soon as the model changes!
810 if(m_progressViewFilter >= 0)
812 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
815 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
818 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
820 if(m_runningThreads == 0)
822 const QStringList &logFile = m_progressModel->getLogFile(index);
824 if(!logFile.isEmpty())
826 LogViewDialog *logView = new LogViewDialog(this);
827 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
828 logView->exec(logFile);
829 MUTILS_DELETE(logView);
831 else
833 QMessageBox::information(this, windowTitle(), m_progressModel->data(m_progressModel->index(index.row(), 0)).toString());
836 else
838 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
842 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
844 if(logicalIndex == 1)
846 if(QHeaderView *hdr = ui->view_log->horizontalHeader())
848 hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
853 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
855 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
856 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
858 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
860 m_contextMenu->popup(sender->mapToGlobal(pos));
864 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
866 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
867 logViewDoubleClicked(index.isValid() ? index : ui->view_log->currentIndex());
870 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
872 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
873 const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : ui->view_log->currentIndex());
874 QString filePath = m_playList.value(jobId, QString());
876 if(filePath.isEmpty())
878 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
879 return;
882 if(QFileInfo(filePath).exists())
884 QString systemRootPath;
886 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
887 if(systemRoot.exists() && systemRoot.cdUp())
889 systemRootPath = systemRoot.canonicalPath();
892 if(!systemRootPath.isEmpty())
894 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
895 if(explorer.exists() && explorer.isFile())
897 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
898 return;
901 else
903 qWarning("SystemRoot directory could not be detected!");
906 else
908 qWarning("File not found: %s", filePath.toLatin1().constData());
909 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
913 void ProcessingDialog::contextMenuFilterActionTriggered(void)
915 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
917 if(action->data().type() == QVariant::Int)
919 m_progressViewFilter = action->data().toInt();
920 progressViewFilterChanged();
921 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
922 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
923 action->setChecked(true);
929 * Filter progress items
931 void ProcessingDialog::progressViewFilterChanged(void)
933 bool matchFound = false;
935 for(int i = 0; i < ui->view_log->model()->rowCount(); i++)
937 QModelIndex index = (m_progressViewFilter >= 0) ? m_progressModel->index(i, 0) : QModelIndex();
938 const bool bHide = index.isValid() ? (m_progressModel->getJobState(index) != m_progressViewFilter) : false;
939 ui->view_log->setRowHidden(i, bHide); matchFound = matchFound || (!bHide);
942 if((m_progressViewFilter >= 0) && (!matchFound))
944 if(m_filterInfoLabel->isHidden() || (dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->value() != m_progressViewFilter))
946 dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->setValue(m_progressViewFilter);
947 m_filterInfoLabel->setText(QString("<p>&raquo; %1 &laquo;</p>").arg(tr("None of the items matches the current filtering rules")));
948 m_filterInfoLabel->show();
949 m_filterInfoLabelIcon->setPixmap(m_progressModel->getIcon(static_cast<ProgressModel::JobState>(m_progressViewFilter)).pixmap(16, 16, QIcon::Disabled));
950 m_filterInfoLabelIcon->show();
951 resizeEvent(NULL);
954 else if(!m_filterInfoLabel->isHidden())
956 m_filterInfoLabel->hide();
957 m_filterInfoLabelIcon->hide();
961 ////////////////////////////////////////////////////////////
962 // Private Functions
963 ////////////////////////////////////////////////////////////
965 void ProcessingDialog::writePlayList(void)
967 if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
969 qWarning("WritePlayList: Nothing to do!");
970 return;
973 //Init local variables
974 QStringList list;
975 QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
976 QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
977 QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
978 bool usePrefix[3] = {true, true, true};
979 bool useUtf8 = false;
980 int counter = 1;
982 //Generate playlist name
983 QString playListName = (m_metaInfo->album().isEmpty() ? "Playlist" : m_metaInfo->album());
984 if(!m_metaInfo->artist().isEmpty())
986 playListName = QString("%1 - %2").arg(m_metaInfo->artist(), playListName);
989 //Clean playlist name
990 playListName = MUtils::clean_file_name(playListName);
992 //Create list of audio files
993 for(int i = 0; i < m_allJobs.count(); i++)
995 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
996 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
999 //Use prefix?
1000 for(int i = 0; i < list.count(); i++)
1002 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
1003 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
1004 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
1006 if(usePrefix[0] || usePrefix[1] || usePrefix[2])
1008 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
1011 //Do we need an UTF-8 playlist?
1012 for(int i = 0; i < list.count(); i++)
1014 if(wcscmp(MUTILS_WCHR(QString::fromLatin1(list.at(i).toLatin1().constData())), MUTILS_WCHR(list.at(i))))
1016 useUtf8 = true;
1017 break;
1021 //Generate playlist output file
1022 QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
1023 while(QFileInfo(playListFile).exists())
1025 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
1028 //Now write playlist to output file
1029 QFile playList(playListFile);
1030 if(playList.open(QIODevice::WriteOnly))
1032 if(useUtf8)
1034 playList.write("\xef\xbb\xbf");
1036 playList.write("#EXTM3U\r\n");
1037 while(!list.isEmpty())
1039 playList.write(useUtf8 ? MUTILS_UTF8(list.takeFirst()) : list.takeFirst().toLatin1().constData());
1040 playList.write("\r\n");
1042 playList.close();
1044 else
1046 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
1050 AudioFileModel ProcessingDialog::updateMetaInfo(AudioFileModel &audioFile)
1052 if(!m_settings->writeMetaTags())
1054 audioFile.metaInfo().reset();
1055 return audioFile;
1058 audioFile.metaInfo().update(*m_metaInfo, true);
1060 if(audioFile.metaInfo().position() == UINT_MAX)
1062 audioFile.metaInfo().setPosition(m_currentFile);
1065 return audioFile;
1068 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
1070 if(reason == QSystemTrayIcon::DoubleClick)
1072 MUtils::GUI::bring_to_front(this);
1076 void ProcessingDialog::cpuUsageHasChanged(const double val)
1079 ui->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1080 UPDATE_MIN_WIDTH(ui->label_cpu);
1083 void ProcessingDialog::ramUsageHasChanged(const double val)
1086 ui->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1087 UPDATE_MIN_WIDTH(ui->label_ram);
1090 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
1092 int postfix = 0;
1093 const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1094 double space = static_cast<double>(val);
1096 while((space >= 1000.0) && (postfix < 5))
1098 space = space / 1024.0;
1099 postfix++;
1102 ui->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
1103 UPDATE_MIN_WIDTH(ui->label_disk);
1106 bool ProcessingDialog::shutdownComputer(void)
1108 const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
1109 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
1110 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1112 qWarning("Initiating shutdown sequence!");
1114 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
1115 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
1116 cancelButton->setIcon(QIcon(":/icons/power_on.png"));
1117 progressDialog.setModal(true);
1118 progressDialog.setAutoClose(false);
1119 progressDialog.setAutoReset(false);
1120 progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
1121 progressDialog.setCancelButton(cancelButton);
1122 progressDialog.show();
1124 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1126 QApplication::setOverrideCursor(Qt::WaitCursor);
1127 PLAY_SOUND_OPTIONAL("shutdown", false);
1128 QApplication::restoreOverrideCursor();
1130 QTimer timer;
1131 timer.setInterval(1000);
1132 timer.start();
1134 QEventLoop eventLoop(this);
1135 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
1136 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
1138 for(int i = 1; i <= iTimeout; i++)
1140 eventLoop.exec();
1141 if(progressDialog.wasCanceled())
1143 progressDialog.close();
1144 return false;
1146 progressDialog.setValue(i+1);
1147 progressDialog.setLabelText(text.arg(iTimeout-i));
1148 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
1149 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1150 PLAY_SOUND_OPTIONAL(((i < iTimeout) ? "beep" : "beep2"), false);
1153 progressDialog.close();
1154 return true;
1157 QString ProcessingDialog::time2text(const qint64 &msec) const
1159 const qint64 MILLISECONDS_PER_DAY = 86399999; //24x60x60x1000 - 1
1160 const QTime time = QTime().addMSecs(qMin(msec, MILLISECONDS_PER_DAY));
1162 QString a, b;
1164 if(time.hour() > 0)
1166 a = tr("%n hour(s)", "", time.hour());
1167 b = tr("%n minute(s)", "", time.minute());
1169 else if(time.minute() > 0)
1171 a = tr("%n minute(s)", "", time.minute());
1172 b = tr("%n second(s)", "", time.second());
1174 else
1176 a = tr("%n second(s)", "", time.second());
1177 b = tr("%n millisecond(s)", "", time.msec());
1180 return QString("%1, %2").arg(a, b);
1183 ////////////////////////////////////////////////////////////
1184 // HELPER FUNCTIONS
1185 ////////////////////////////////////////////////////////////
1187 static int cores2instances(int cores)
1189 //This function is a "cubic spline" with sampling points at:
1190 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1191 static const double LUT[8][5] =
1193 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1194 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1195 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1196 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1197 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1198 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1199 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1200 {DBL_MAX, 0.0, 0.0, 0.0, 0.0}
1203 double x = abs(static_cast<double>(cores)), y = 1.0;
1205 for(size_t i = 0; i < 7; i++)
1207 if((x >= LUT[i][0]) && (x < LUT[i+1][0]))
1209 y = (((((LUT[i][1] * x) + LUT[i][2]) * x) + LUT[i][3]) * x) + LUT[i][4];
1210 break;
1214 return qRound(y);