1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
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"
26 #include "UIC_ProcessingDialog.h"
30 #include "Model_FileList.h"
31 #include "Model_Progress.h"
32 #include "Model_Settings.h"
33 #include "Thread_Process.h"
34 #include "Thread_CPUObserver.h"
35 #include "Thread_RAMObserver.h"
36 #include "Thread_DiskObserver.h"
37 #include "Dialog_LogView.h"
38 #include "Registry_Decoder.h"
39 #include "Registry_Encoder.h"
40 #include "Filter_Downmix.h"
41 #include "Filter_Normalize.h"
42 #include "Filter_Resample.h"
43 #include "Filter_ToneAdjust.h"
44 #include "WinSevenTaskbar.h"
47 #include <MUtils/Global.h>
48 #include <MUtils/OSSupport.h>
49 #include <MUtils/GUI.h>
50 #include <MUtils/CPUFeatures.h>
53 #include <QApplication>
55 #include <QDesktopWidget>
57 #include <QMessageBox>
59 #include <QCloseEvent>
60 #include <QDesktopServices>
66 #include <QSystemTrayIcon>
68 #include <QProgressDialog>
69 #include <QResizeEvent>
71 #include <QThreadPool>
76 ////////////////////////////////////////////////////////////
78 //Maximum number of parallel instances
79 #define MAX_INSTANCES 32U
81 //Function to calculate the number of instances
82 static int cores2instances(int cores);
84 ////////////////////////////////////////////////////////////
86 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
88 QPalette palette = WIDGET->palette(); \
89 palette.setColor(QPalette::Background, COLOR); \
90 WIDGET->setPalette(palette); \
94 #define SET_PROGRESS_TEXT(TXT) do \
96 ui->label_progress->setText(TXT); \
97 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
101 #define SET_FONT_BOLD(WIDGET,BOLD) do \
103 QFont _font = WIDGET->font(); \
104 _font.setBold(BOLD); WIDGET->setFont(_font); \
108 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
110 QPalette _palette = WIDGET->palette(); \
111 _palette.setColor(QPalette::WindowText, (COLOR)); \
112 _palette.setColor(QPalette::Text, (COLOR)); \
113 WIDGET->setPalette(_palette); \
117 #define UPDATE_MIN_WIDTH(WIDGET) do \
119 if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
123 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
125 if(m_settings->soundsEnabled()) lamexp_play_sound((NAME), (ASYNC)); \
129 #define IS_VBR(RC_MODE) ((RC_MODE) == SettingsModel::VBRMode)
131 ////////////////////////////////////////////////////////////
133 //Dummy class for UserData
134 class IntUserData : public QObjectUserData
137 IntUserData(int value) : m_value(value) {/*NOP*/}
138 int value(void) { return m_value; }
139 void setValue(int value) { m_value = value; }
144 ////////////////////////////////////////////////////////////
146 ////////////////////////////////////////////////////////////
148 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, const AudioFileModel_MetaInfo *metaInfo, SettingsModel *settings, QWidget *parent)
151 ui(new Ui::ProcessingDialog),
153 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
154 m_settings(settings),
155 m_metaInfo(metaInfo),
156 m_shutdownFlag(shutdownFlag_None),
158 m_diskObserver(NULL),
161 m_progressViewFilter(-1),
163 m_defaultColor(new QColor()),
166 //Init the dialog, from the .ui file
168 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
170 //Update the window icon
171 m_windowIcon = lamexp_set_window_icon(this, lamexp_app_icon(), true);
174 ui->label_headerIcon->setPixmap(lamexp_app_icon().pixmap(ui->label_headerIcon->size()));
177 ui->label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
178 ui->label_versionInfo->installEventFilter(this);
181 qRegisterMetaType<QUuid>("QUuid");
183 //Center window in screen
184 QRect desktopRect = QApplication::desktop()->screenGeometry();
185 QRect thisRect = this->geometry();
186 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
187 setMinimumSize(thisRect.width(), thisRect.height());
190 connect(ui->button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
192 //Init progress indicator
193 m_progressIndicator = new QMovie(":/images/Working.gif");
194 m_progressIndicator->setCacheMode(QMovie::CacheAll);
195 ui->label_headerWorking->setMovie(m_progressIndicator);
196 ui->progressBar->setValue(0);
198 //Init progress model
199 m_progressModel = new ProgressModel();
200 ui->view_log->setModel(m_progressModel);
201 ui->view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
202 ui->view_log->verticalHeader()->hide();
203 ui->view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
204 ui->view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
205 ui->view_log->viewport()->installEventFilter(this);
206 connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
207 connect(m_progressModel, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(progressModelChanged()));
208 connect(m_progressModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
209 connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
210 connect(ui->view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
211 connect(ui->view_log->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
213 //Create context menu
214 m_contextMenu = new QMenu();
215 QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
216 QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
217 m_contextMenu->addSeparator();
219 //Create "filter" context menu
220 m_progressViewFilterGroup = new QActionGroup(this);
221 QAction *contextMenuFilterAction[5] = {NULL, NULL, NULL, NULL, NULL};
222 if(QMenu *filterMenu = m_contextMenu->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
224 contextMenuFilterAction[0] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobRunning), tr("Show Running Only"));
225 contextMenuFilterAction[1] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobComplete), tr("Show Succeeded Only"));
226 contextMenuFilterAction[2] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobFailed), tr("Show Failed Only"));
227 contextMenuFilterAction[3] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobSkipped), tr("Show Skipped Only"));
228 contextMenuFilterAction[4] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
229 if(QAction *act = contextMenuFilterAction[0]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobRunning); }
230 if(QAction *act = contextMenuFilterAction[1]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobComplete); }
231 if(QAction *act = contextMenuFilterAction[2]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobFailed); }
232 if(QAction *act = contextMenuFilterAction[3]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobSkipped); }
233 if(QAction *act = contextMenuFilterAction[4]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(-1); act->setChecked(true); }
237 if(m_filterInfoLabel = new QLabel(ui->view_log))
239 m_filterInfoLabel->setFrameShape(QFrame::NoFrame);
240 m_filterInfoLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
241 m_filterInfoLabel->setUserData(0, new IntUserData(-1));
242 SET_FONT_BOLD(m_filterInfoLabel, true);
243 SET_TEXT_COLOR(m_filterInfoLabel, Qt::darkGray);
244 m_filterInfoLabel->setContextMenuPolicy(Qt::CustomContextMenu);
245 connect(m_filterInfoLabel, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
246 m_filterInfoLabel->hide();
248 if(m_filterInfoLabelIcon = new QLabel(ui->view_log))
250 m_filterInfoLabelIcon->setFrameShape(QFrame::NoFrame);
251 m_filterInfoLabelIcon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
252 m_filterInfoLabelIcon->setContextMenuPolicy(Qt::CustomContextMenu);
253 const QIcon &ico = m_progressModel->getIcon(ProgressModel::JobState(-1));
254 m_filterInfoLabelIcon->setPixmap(ico.pixmap(16, 16));
255 connect(m_filterInfoLabelIcon, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
256 m_filterInfoLabelIcon->hide();
259 //Connect context menu
260 ui->view_log->setContextMenuPolicy(Qt::CustomContextMenu);
261 connect(ui->view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
262 connect(contextMenuDetailsAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
263 connect(contextMenuShowFileAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
264 for(size_t i = 0; i < 5; i++)
266 if(contextMenuFilterAction[i]) connect(contextMenuFilterAction[i], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
268 SET_FONT_BOLD(contextMenuDetailsAction, true);
273 for(int i = 0; i < fileListModel->rowCount(); i++)
275 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
280 ui->label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
282 //Enable system tray icon
283 connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
286 m_runningThreads = 0;
289 m_succeededJobs.clear();
290 m_failedJobs.clear();
291 m_skippedJobs.clear();
292 m_userAborted = false;
293 m_forcedAbort = false;
297 ////////////////////////////////////////////////////////////
299 ////////////////////////////////////////////////////////////
301 ProcessingDialog::~ProcessingDialog(void)
303 ui->view_log->setModel(NULL);
305 if(m_progressIndicator)
307 m_progressIndicator->stop();
312 m_diskObserver->stop();
313 if(!m_diskObserver->wait(15000))
315 m_diskObserver->terminate();
316 m_diskObserver->wait();
322 m_cpuObserver->stop();
323 if(!m_cpuObserver->wait(15000))
325 m_cpuObserver->terminate();
326 m_cpuObserver->wait();
332 m_ramObserver->stop();
333 if(!m_ramObserver->wait(15000))
335 m_ramObserver->terminate();
336 m_ramObserver->wait();
342 if(!m_threadPool->waitForDone(100))
344 emit abortRunningTasks();
345 m_threadPool->waitForDone();
349 MUTILS_DELETE(m_progressIndicator);
350 MUTILS_DELETE(m_systemTray);
351 MUTILS_DELETE(m_diskObserver);
352 MUTILS_DELETE(m_cpuObserver);
353 MUTILS_DELETE(m_ramObserver);
354 MUTILS_DELETE(m_progressViewFilterGroup);
355 MUTILS_DELETE(m_filterInfoLabel);
356 MUTILS_DELETE(m_filterInfoLabelIcon);
357 MUTILS_DELETE(m_contextMenu);
358 MUTILS_DELETE(m_progressModel);
359 MUTILS_DELETE(m_threadPool);
360 MUTILS_DELETE(m_defaultColor);
362 WinSevenTaskbar::setOverlayIcon(this, NULL);
363 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
367 lamexp_free_window_icon(m_windowIcon);
374 ////////////////////////////////////////////////////////////
376 ////////////////////////////////////////////////////////////
378 void ProcessingDialog::showEvent(QShowEvent *event)
380 QDialog::showEvent(event);
384 static const char *NA = " N/A";
386 lamexp_enable_close_button(this, false);
387 ui->button_closeDialog->setEnabled(false);
388 ui->button_AbortProcess->setEnabled(false);
389 m_progressIndicator->start();
390 m_systemTray->setVisible(true);
392 MUtils::OS::change_process_priority(1);
394 ui->label_cpu->setText(NA);
395 ui->label_disk->setText(NA);
396 ui->label_ram->setText(NA);
398 QTimer::singleShot(500, this, SLOT(initEncoding()));
402 //Force update geometry
406 void ProcessingDialog::closeEvent(QCloseEvent *event)
408 if(!ui->button_closeDialog->isEnabled())
414 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);
445 bool ProcessingDialog::event(QEvent *e)
449 case MUtils::GUI::USER_EVENT_QUERYENDSESSION:
450 qWarning("System is shutting down, preparing to abort...");
451 if(!m_userAborted) abortEncoding(true);
453 case MUtils::GUI::USER_EVENT_ENDSESSION:
454 qWarning("System is shutting down, encoding will be aborted now...");
459 if(!m_userAborted) abortEncoding(true);
460 qApp->processEvents(QEventLoop::WaitForMoreEvents | QEventLoop::ExcludeUserInputEvents);
463 m_pendingJobs.clear();
466 return QDialog::event(e);
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 bool ProcessingDialog::winEvent(MSG *message, long *result)
487 return WinSevenTaskbar::handleWinEvent(message, result);
490 ////////////////////////////////////////////////////////////
492 ////////////////////////////////////////////////////////////
494 void ProcessingDialog::initEncoding(void)
496 qDebug("Initializing encoding process...");
498 m_runningThreads = 0;
501 m_succeededJobs.clear();
502 m_failedJobs.clear();
503 m_skippedJobs.clear();
504 m_userAborted = false;
505 m_forcedAbort = false;
508 DecoderRegistry::configureDecoders(m_settings);
510 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor(Qt::white));
511 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
513 ui->button_closeDialog->setEnabled(false);
514 ui->button_AbortProcess->setEnabled(true);
515 ui->progressBar->setRange(0, m_pendingJobs.count());
516 ui->checkBox_shutdownComputer->setEnabled(true);
517 ui->checkBox_shutdownComputer->setChecked(false);
519 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
520 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
521 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
525 m_diskObserver = new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder());
526 connect(m_diskObserver, SIGNAL(messageLogged(QString,int)), m_progressModel, SLOT(addSystemMessage(QString,int)), Qt::QueuedConnection);
527 connect(m_diskObserver, SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
528 m_diskObserver->start();
532 m_cpuObserver = new CPUObserverThread();
533 connect(m_cpuObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
534 m_cpuObserver->start();
538 m_ramObserver = new RAMObserverThread();
539 connect(m_ramObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
540 m_ramObserver->start();
545 unsigned int maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
546 if(maximumInstances < 1)
548 const MUtils::CPUFetaures::cpu_info_t cpuFeatures = MUtils::CPUFetaures::detect(MUtils::OS::arguments());
549 maximumInstances = cores2instances(qBound(1U, cpuFeatures.count, 64U));
552 maximumInstances = qBound(1U, maximumInstances, static_cast<unsigned int>(m_pendingJobs.count()));
553 if(maximumInstances > 1)
555 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances)));
558 m_threadPool = new QThreadPool();
559 m_threadPool->setMaxThreadCount(maximumInstances);
562 m_initThreads = m_threadPool->maxThreadCount();
563 QTimer::singleShot(100, this, SLOT(initNextJob()));
564 m_timerStart = MUtils::OS::perfcounter_read();
567 void ProcessingDialog::initNextJob(void)
569 if((m_initThreads > 0) && (!m_userAborted))
572 if(--m_initThreads > 0)
574 QTimer::singleShot(32, this, SLOT(initNextJob()));
579 void ProcessingDialog::startNextJob(void)
581 if(m_pendingJobs.isEmpty())
583 qWarning("No more files left, unable to start another job!");
590 AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
591 bool nativeResampling = false;
593 //Create encoder instance
594 AbstractEncoder *encoder = EncoderRegistry::createInstance(m_settings->compressionEncoder(), m_settings, &nativeResampling);
596 //Create processing thread
597 ProcessThread *thread = new ProcessThread
600 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
601 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder()),
603 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
607 if(m_settings->forceStereoDownmix())
609 thread->addFilter(new DownmixFilter());
611 if((m_settings->samplingRate() > 0) && !nativeResampling)
613 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.techInfo().audioSamplerate() || currentFile.techInfo().audioSamplerate() == 0)
615 thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
618 if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
620 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
622 if(m_settings->normalizationFilterEnabled())
624 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEQMode()));
626 if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
628 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
630 if(m_settings->overwriteMode() != SettingsModel::Overwrite_KeepBoth)
632 thread->setOverwriteMode((m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile), (m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces));
635 m_allJobs.append(thread->getId());
637 //Connect thread signals
638 connect(thread, SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
639 connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
640 connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
641 connect(thread, SIGNAL(processStateFinished(QUuid,QString,int)), this, SLOT(processFinished(QUuid,QString,int)), Qt::QueuedConnection);
642 connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
643 connect(this, SIGNAL(abortRunningTasks()), thread, SLOT(abort()), Qt::DirectConnection);
645 //Initialize thread object
648 qFatal("Fatal Error: Thread initialization has failed!");
652 if(!thread->start(m_threadPool))
654 qWarning("Job failed to start or file was skipped!");
658 void ProcessingDialog::abortEncoding(bool force)
660 m_userAborted = true;
661 if(force) m_forcedAbort = true;
662 ui->button_AbortProcess->setEnabled(false);
663 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
664 emit abortRunningTasks();
667 void ProcessingDialog::doneEncoding(void)
670 ui->progressBar->setValue(ui->progressBar->value() + 1);
674 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui->progressBar->value()).arg(QString::number(ui->progressBar->maximum())));
675 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
678 if((!m_pendingJobs.isEmpty()) && (!m_userAborted))
680 QTimer::singleShot(0, this, SLOT(startNextJob()));
681 qDebug("%d files left, starting next job...", m_pendingJobs.count());
685 if(m_runningThreads > 0)
687 qDebug("No files left, but still have %u running jobs.", m_runningThreads);
691 QApplication::setOverrideCursor(Qt::WaitCursor);
692 qDebug("Running jobs: %u", m_runningThreads);
694 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
696 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
697 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
703 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFFFE0"));
704 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
705 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
706 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!"));
707 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
708 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
709 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
710 if(!m_forcedAbort) PLAY_SOUND_OPTIONAL("aborted", false);
714 const qint64 counter = MUtils::OS::perfcounter_read();
715 const qint64 frequency = MUtils::OS::perfcounter_freq();
716 if((counter >= 0I64) && (frequency >= 0))
718 if((m_timerStart >= 0I64) && (m_timerStart < counter))
720 double timeElapsed = static_cast<double>(counter - m_timerStart) / static_cast<double>(frequency);
721 m_progressModel->addSystemMessage(tr("Process finished after %1.").arg(time2text(timeElapsed)), ProgressModel::SysMsg_Performance);
725 if(m_failedJobs.count() > 0)
727 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFF0F0"));
728 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
729 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
730 if(m_skippedJobs.count() > 0)
732 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())));
736 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())));
738 m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
739 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
740 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
741 PLAY_SOUND_OPTIONAL("error", false);
745 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#F0FFF0"));
746 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
747 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
748 if(m_skippedJobs.count() > 0)
750 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs.count()));
754 SET_PROGRESS_TEXT(tr("All files completed successfully."));
756 m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
757 m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
758 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
759 PLAY_SOUND_OPTIONAL("success", false);
763 lamexp_enable_close_button(this, true);
764 ui->button_closeDialog->setEnabled(true);
765 ui->button_AbortProcess->setEnabled(false);
766 ui->checkBox_shutdownComputer->setEnabled(false);
768 m_progressModel->restoreHiddenItems();
769 ui->view_log->scrollToBottom();
770 m_progressIndicator->stop();
771 ui->progressBar->setValue(ui->progressBar->maximum());
772 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
774 QApplication::restoreOverrideCursor();
776 if(!m_userAborted && ui->checkBox_shutdownComputer->isChecked())
778 if(shutdownComputer())
780 m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
786 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, int success)
790 m_playList.insert(jobId, outFileName);
791 m_succeededJobs.append(jobId);
795 m_playList.insert(jobId, outFileName);
796 m_skippedJobs.append(jobId);
800 m_failedJobs.append(jobId);
803 //Update filter as soon as a job finished!
804 if(m_progressViewFilter >= 0)
806 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
810 void ProcessingDialog::progressModelChanged(void)
812 //Update filter as soon as the model changes!
813 if(m_progressViewFilter >= 0)
815 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
818 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
821 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
823 if(m_runningThreads == 0)
825 const QStringList &logFile = m_progressModel->getLogFile(index);
827 if(!logFile.isEmpty())
829 LogViewDialog *logView = new LogViewDialog(this);
830 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
831 logView->exec(logFile);
832 MUTILS_DELETE(logView);
836 QMessageBox::information(this, windowTitle(), m_progressModel->data(m_progressModel->index(index.row(), 0)).toString());
841 lamexp_beep(lamexp_beep_warning);
845 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
847 if(logicalIndex == 1)
849 if(QHeaderView *hdr = ui->view_log->horizontalHeader())
851 hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
856 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
858 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
859 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
861 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
863 m_contextMenu->popup(sender->mapToGlobal(pos));
867 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
869 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
870 logViewDoubleClicked(index.isValid() ? index : ui->view_log->currentIndex());
873 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
875 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
876 const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : ui->view_log->currentIndex());
877 QString filePath = m_playList.value(jobId, QString());
879 if(filePath.isEmpty())
881 lamexp_beep(lamexp_beep_warning);
885 if(QFileInfo(filePath).exists())
887 QString systemRootPath;
889 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
890 if(systemRoot.exists() && systemRoot.cdUp())
892 systemRootPath = systemRoot.canonicalPath();
895 if(!systemRootPath.isEmpty())
897 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
898 if(explorer.exists() && explorer.isFile())
900 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
906 qWarning("SystemRoot directory could not be detected!");
911 qWarning("File not found: %s", filePath.toLatin1().constData());
912 lamexp_beep(lamexp_beep_error);
916 void ProcessingDialog::contextMenuFilterActionTriggered(void)
918 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
920 if(action->data().type() == QVariant::Int)
922 m_progressViewFilter = action->data().toInt();
923 progressViewFilterChanged();
924 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
925 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
926 action->setChecked(true);
932 * Filter progress items
934 void ProcessingDialog::progressViewFilterChanged(void)
936 bool matchFound = false;
938 for(int i = 0; i < ui->view_log->model()->rowCount(); i++)
940 QModelIndex index = (m_progressViewFilter >= 0) ? m_progressModel->index(i, 0) : QModelIndex();
941 const bool bHide = index.isValid() ? (m_progressModel->getJobState(index) != m_progressViewFilter) : false;
942 ui->view_log->setRowHidden(i, bHide); matchFound = matchFound || (!bHide);
945 if((m_progressViewFilter >= 0) && (!matchFound))
947 if(m_filterInfoLabel->isHidden() || (dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->value() != m_progressViewFilter))
949 dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->setValue(m_progressViewFilter);
950 m_filterInfoLabel->setText(QString("<p>» %1 «</p>").arg(tr("None of the items matches the current filtering rules")));
951 m_filterInfoLabel->show();
952 m_filterInfoLabelIcon->setPixmap(m_progressModel->getIcon(static_cast<ProgressModel::JobState>(m_progressViewFilter)).pixmap(16, 16, QIcon::Disabled));
953 m_filterInfoLabelIcon->show();
957 else if(!m_filterInfoLabel->isHidden())
959 m_filterInfoLabel->hide();
960 m_filterInfoLabelIcon->hide();
964 ////////////////////////////////////////////////////////////
966 ////////////////////////////////////////////////////////////
968 void ProcessingDialog::writePlayList(void)
970 if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
972 qWarning("WritePlayList: Nothing to do!");
976 //Init local variables
978 QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
979 QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
980 QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
981 bool usePrefix[3] = {true, true, true};
982 bool useUtf8 = false;
985 //Generate playlist name
986 QString playListName = (m_metaInfo->album().isEmpty() ? "Playlist" : m_metaInfo->album());
987 if(!m_metaInfo->artist().isEmpty())
989 playListName = QString("%1 - %2").arg(m_metaInfo->artist(), playListName);
992 //Clean playlist name
993 playListName = lamexp_clean_filename(playListName);
995 //Create list of audio files
996 for(int i = 0; i < m_allJobs.count(); i++)
998 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
999 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
1003 for(int i = 0; i < list.count(); i++)
1005 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
1006 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
1007 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
1009 if(usePrefix[0] || usePrefix[1] || usePrefix[2])
1011 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
1014 //Do we need an UTF-8 playlist?
1015 for(int i = 0; i < list.count(); i++)
1017 if(wcscmp(MUTILS_WCHR(QString::fromLatin1(list.at(i).toLatin1().constData())), MUTILS_WCHR(list.at(i))))
1024 //Generate playlist output file
1025 QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
1026 while(QFileInfo(playListFile).exists())
1028 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
1031 //Now write playlist to output file
1032 QFile playList(playListFile);
1033 if(playList.open(QIODevice::WriteOnly))
1037 playList.write("\xef\xbb\xbf");
1039 playList.write("#EXTM3U\r\n");
1040 while(!list.isEmpty())
1042 playList.write(useUtf8 ? MUTILS_UTF8(list.takeFirst()) : list.takeFirst().toLatin1().constData());
1043 playList.write("\r\n");
1049 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
1053 AudioFileModel ProcessingDialog::updateMetaInfo(AudioFileModel &audioFile)
1055 if(!m_settings->writeMetaTags())
1057 audioFile.metaInfo().reset();
1061 audioFile.metaInfo().update(*m_metaInfo, true);
1063 if(audioFile.metaInfo().position() == UINT_MAX)
1065 audioFile.metaInfo().setPosition(m_currentFile);
1071 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
1073 if(reason == QSystemTrayIcon::DoubleClick)
1075 lamexp_bring_to_front(this);
1079 void ProcessingDialog::cpuUsageHasChanged(const double val)
1082 ui->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1083 UPDATE_MIN_WIDTH(ui->label_cpu);
1086 void ProcessingDialog::ramUsageHasChanged(const double val)
1089 ui->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1090 UPDATE_MIN_WIDTH(ui->label_ram);
1093 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
1096 const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1097 double space = static_cast<double>(val);
1099 while((space >= 1000.0) && (postfix < 5))
1101 space = space / 1024.0;
1105 ui->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
1106 UPDATE_MIN_WIDTH(ui->label_disk);
1109 bool ProcessingDialog::shutdownComputer(void)
1111 const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
1112 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
1113 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1115 qWarning("Initiating shutdown sequence!");
1117 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
1118 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
1119 cancelButton->setIcon(QIcon(":/icons/power_on.png"));
1120 progressDialog.setModal(true);
1121 progressDialog.setAutoClose(false);
1122 progressDialog.setAutoReset(false);
1123 progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
1124 progressDialog.setCancelButton(cancelButton);
1125 progressDialog.show();
1127 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1129 QApplication::setOverrideCursor(Qt::WaitCursor);
1130 PLAY_SOUND_OPTIONAL("shutdown", false);
1131 QApplication::restoreOverrideCursor();
1134 timer.setInterval(1000);
1137 QEventLoop eventLoop(this);
1138 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
1139 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
1141 for(int i = 1; i <= iTimeout; i++)
1144 if(progressDialog.wasCanceled())
1146 progressDialog.close();
1149 progressDialog.setValue(i+1);
1150 progressDialog.setLabelText(text.arg(iTimeout-i));
1151 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
1152 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1153 PLAY_SOUND_OPTIONAL(((i < iTimeout) ? "beep" : "beep2"), false);
1156 progressDialog.close();
1160 QString ProcessingDialog::time2text(const double timeVal) const
1163 double frcPart = modf(timeVal, &intPart);
1165 QTime time = QTime().addSecs(qRound(intPart)).addMSecs(qRound(frcPart * 1000.0));
1171 a = tr("%n hour(s)", "", time.hour());
1172 b = tr("%n minute(s)", "", time.minute());
1174 else if(time.minute() > 0)
1176 a = tr("%n minute(s)", "", time.minute());
1177 b = tr("%n second(s)", "", time.second());
1181 a = tr("%n second(s)", "", time.second());
1182 b = tr("%n millisecond(s)", "", time.msec());
1185 return QString("%1, %2").arg(a, b);
1188 ////////////////////////////////////////////////////////////
1190 ////////////////////////////////////////////////////////////
1192 static int cores2instances(int cores)
1194 //This function is a "cubic spline" with sampling points at:
1195 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1196 static const double LUT[8][5] =
1198 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1199 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1200 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1201 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1202 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1203 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1204 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1205 {DBL_MAX, 0.0, 0.0, 0.0, 0.0}
1208 double x = abs(static_cast<double>(cores)), y = 1.0;
1210 for(size_t i = 0; i < 7; i++)
1212 if((x >= LUT[i][0]) && (x < LUT[i+1][0]))
1214 y = (((((LUT[i][1] * x) + LUT[i][2]) * x) + LUT[i][3]) * x) + LUT[i][4];