Updated CueImportDialog and CueSheetModel as well as the CueSheet helper classes...
[LameXP.git] / src / Dialog_Processing.cpp
blob349e8a894fd47a0bfe21d44f9a251ed05004eaf7
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 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.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Dialog_Processing.h"
24 //UIC includes
25 #include "../tmp/UIC_ProcessingDialog.h"
27 #include "Global.h"
28 #include "Resource.h"
29 #include "Model_FileList.h"
30 #include "Model_Progress.h"
31 #include "Model_Settings.h"
32 #include "Thread_Process.h"
33 #include "Thread_CPUObserver.h"
34 #include "Thread_RAMObserver.h"
35 #include "Thread_DiskObserver.h"
36 #include "Dialog_LogView.h"
37 #include "Registry_Decoder.h"
38 #include "Registry_Encoder.h"
39 #include "Filter_Downmix.h"
40 #include "Filter_Normalize.h"
41 #include "Filter_Resample.h"
42 #include "Filter_ToneAdjust.h"
43 #include "WinSevenTaskbar.h"
45 #include <QApplication>
46 #include <QRect>
47 #include <QDesktopWidget>
48 #include <QMovie>
49 #include <QMessageBox>
50 #include <QTimer>
51 #include <QCloseEvent>
52 #include <QDesktopServices>
53 #include <QUrl>
54 #include <QUuid>
55 #include <QFileInfo>
56 #include <QDir>
57 #include <QMenu>
58 #include <QSystemTrayIcon>
59 #include <QProcess>
60 #include <QProgressDialog>
61 #include <QResizeEvent>
62 #include <QTime>
63 #include <QThreadPool>
65 #include <math.h>
66 #include <float.h>
68 ////////////////////////////////////////////////////////////
70 //Maximum number of parallel instances
71 #define MAX_INSTANCES 16U
73 //Function to calculate the number of instances
74 static int cores2instances(int cores);
76 ////////////////////////////////////////////////////////////
78 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
79 { \
80 QPalette palette = WIDGET->palette(); \
81 palette.setColor(QPalette::Background, COLOR); \
82 WIDGET->setPalette(palette); \
83 } \
84 while(0)
86 #define SET_PROGRESS_TEXT(TXT) do \
87 { \
88 ui->label_progress->setText(TXT); \
89 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
90 } \
91 while(0)
93 #define SET_FONT_BOLD(WIDGET,BOLD) do \
94 { \
95 QFont _font = WIDGET->font(); \
96 _font.setBold(BOLD); WIDGET->setFont(_font); \
97 } \
98 while(0)
100 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
102 QPalette _palette = WIDGET->palette(); \
103 _palette.setColor(QPalette::WindowText, (COLOR)); \
104 _palette.setColor(QPalette::Text, (COLOR)); \
105 WIDGET->setPalette(_palette); \
107 while(0)
109 #define UPDATE_MIN_WIDTH(WIDGET) do \
111 if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
113 while(0)
115 #define IS_VBR(RC_MODE) ((RC_MODE) == SettingsModel::VBRMode)
117 ////////////////////////////////////////////////////////////
119 //Dummy class for UserData
120 class IntUserData : public QObjectUserData
122 public:
123 IntUserData(int value) : m_value(value) {/*NOP*/}
124 int value(void) { return m_value; }
125 void setValue(int value) { m_value = value; }
126 private:
127 int m_value;
130 ////////////////////////////////////////////////////////////
131 // Constructor
132 ////////////////////////////////////////////////////////////
134 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, const AudioFileModel_MetaInfo *metaInfo, SettingsModel *settings, QWidget *parent)
136 QDialog(parent),
137 ui(new Ui::ProcessingDialog),
138 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
139 m_settings(settings),
140 m_metaInfo(metaInfo),
141 m_shutdownFlag(shutdownFlag_None),
142 m_threadPool(NULL),
143 m_diskObserver(NULL),
144 m_cpuObserver(NULL),
145 m_ramObserver(NULL),
146 m_progressViewFilter(-1),
147 m_firstShow(true)
149 //Init the dialog, from the .ui file
150 ui->setupUi(this);
151 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
153 //Update header icon
154 ui->label_headerIcon->setPixmap(lamexp_app_icon().pixmap(ui->label_headerIcon->size()));
156 //Setup version info
157 ui->label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
158 ui->label_versionInfo->installEventFilter(this);
160 //Register meta type
161 qRegisterMetaType<QUuid>("QUuid");
163 //Center window in screen
164 QRect desktopRect = QApplication::desktop()->screenGeometry();
165 QRect thisRect = this->geometry();
166 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
167 setMinimumSize(thisRect.width(), thisRect.height());
169 //Enable buttons
170 connect(ui->button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
172 //Init progress indicator
173 m_progressIndicator = new QMovie(":/images/Working.gif");
174 m_progressIndicator->setCacheMode(QMovie::CacheAll);
175 m_progressIndicator->setSpeed(50);
176 ui->label_headerWorking->setMovie(m_progressIndicator);
177 ui->progressBar->setValue(0);
179 //Init progress model
180 m_progressModel = new ProgressModel();
181 ui->view_log->setModel(m_progressModel);
182 ui->view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
183 ui->view_log->verticalHeader()->hide();
184 ui->view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
185 ui->view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
186 ui->view_log->viewport()->installEventFilter(this);
187 connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
188 connect(m_progressModel, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(progressModelChanged()));
189 connect(m_progressModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
190 connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
191 connect(ui->view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
192 connect(ui->view_log->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
194 //Create context menu
195 m_contextMenu = new QMenu();
196 QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
197 QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
198 m_contextMenu->addSeparator();
200 //Create "filter" context menu
201 m_progressViewFilterGroup = new QActionGroup(this);
202 QAction *contextMenuFilterAction[5] = {NULL, NULL, NULL, NULL, NULL};
203 if(QMenu *filterMenu = m_contextMenu->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
205 contextMenuFilterAction[0] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobRunning), tr("Show Running Only"));
206 contextMenuFilterAction[1] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobComplete), tr("Show Succeeded Only"));
207 contextMenuFilterAction[2] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobFailed), tr("Show Failed Only"));
208 contextMenuFilterAction[3] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobSkipped), tr("Show Skipped Only"));
209 contextMenuFilterAction[4] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
210 if(QAction *act = contextMenuFilterAction[0]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobRunning); }
211 if(QAction *act = contextMenuFilterAction[1]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobComplete); }
212 if(QAction *act = contextMenuFilterAction[2]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobFailed); }
213 if(QAction *act = contextMenuFilterAction[3]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobSkipped); }
214 if(QAction *act = contextMenuFilterAction[4]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(-1); act->setChecked(true); }
217 //Create info label
218 if(m_filterInfoLabel = new QLabel(ui->view_log))
220 m_filterInfoLabel->setFrameShape(QFrame::NoFrame);
221 m_filterInfoLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
222 m_filterInfoLabel->setUserData(0, new IntUserData(-1));
223 SET_FONT_BOLD(m_filterInfoLabel, true);
224 SET_TEXT_COLOR(m_filterInfoLabel, Qt::darkGray);
225 m_filterInfoLabel->setContextMenuPolicy(Qt::CustomContextMenu);
226 connect(m_filterInfoLabel, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
227 m_filterInfoLabel->hide();
229 if(m_filterInfoLabelIcon = new QLabel(ui->view_log))
231 m_filterInfoLabelIcon->setFrameShape(QFrame::NoFrame);
232 m_filterInfoLabelIcon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
233 m_filterInfoLabelIcon->setContextMenuPolicy(Qt::CustomContextMenu);
234 const QIcon &ico = m_progressModel->getIcon(ProgressModel::JobState(-1));
235 m_filterInfoLabelIcon->setPixmap(ico.pixmap(16, 16));
236 connect(m_filterInfoLabelIcon, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
237 m_filterInfoLabelIcon->hide();
240 //Connect context menu
241 ui->view_log->setContextMenuPolicy(Qt::CustomContextMenu);
242 connect(ui->view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
243 connect(contextMenuDetailsAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
244 connect(contextMenuShowFileAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
245 for(size_t i = 0; i < 5; i++)
247 if(contextMenuFilterAction[i]) connect(contextMenuFilterAction[i], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
249 SET_FONT_BOLD(contextMenuDetailsAction, true);
251 //Enque jobs
252 if(fileListModel)
254 for(int i = 0; i < fileListModel->rowCount(); i++)
256 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
260 //Translate
261 ui->label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
263 //Enable system tray icon
264 connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
266 //Init other vars
267 m_runningThreads = 0;
268 m_currentFile = 0;
269 m_allJobs.clear();
270 m_succeededJobs.clear();
271 m_failedJobs.clear();
272 m_skippedJobs.clear();
273 m_userAborted = false;
274 m_forcedAbort = false;
275 m_timerStart = 0I64;
278 ////////////////////////////////////////////////////////////
279 // Destructor
280 ////////////////////////////////////////////////////////////
282 ProcessingDialog::~ProcessingDialog(void)
284 ui->view_log->setModel(NULL);
286 if(m_progressIndicator)
288 m_progressIndicator->stop();
291 if(m_diskObserver)
293 m_diskObserver->stop();
294 if(!m_diskObserver->wait(15000))
296 m_diskObserver->terminate();
297 m_diskObserver->wait();
300 if(m_cpuObserver)
302 m_cpuObserver->stop();
303 if(!m_cpuObserver->wait(15000))
305 m_cpuObserver->terminate();
306 m_cpuObserver->wait();
309 if(m_ramObserver)
311 m_ramObserver->stop();
312 if(!m_ramObserver->wait(15000))
314 m_ramObserver->terminate();
315 m_ramObserver->wait();
319 //while(!m_threadList.isEmpty())
321 // ProcessThread *thread = m_threadList.takeFirst();
322 // thread->terminate();
323 // thread->wait(15000);
324 // delete thread;
327 if(m_threadPool)
329 if(!m_threadPool->waitForDone(100))
331 emit abortRunningTasks();
332 m_threadPool->waitForDone();
336 LAMEXP_DELETE(m_progressIndicator);
337 LAMEXP_DELETE(m_systemTray);
338 LAMEXP_DELETE(m_diskObserver);
339 LAMEXP_DELETE(m_cpuObserver);
340 LAMEXP_DELETE(m_ramObserver);
341 LAMEXP_DELETE(m_progressViewFilterGroup);
342 LAMEXP_DELETE(m_filterInfoLabel);
343 LAMEXP_DELETE(m_filterInfoLabelIcon);
344 LAMEXP_DELETE(m_contextMenu);
345 LAMEXP_DELETE(m_progressModel);
346 LAMEXP_DELETE(m_threadPool);
348 WinSevenTaskbar::setOverlayIcon(this, NULL);
349 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
351 LAMEXP_DELETE(ui);
354 ////////////////////////////////////////////////////////////
355 // EVENTS
356 ////////////////////////////////////////////////////////////
358 void ProcessingDialog::showEvent(QShowEvent *event)
360 QDialog::showEvent(event);
362 if(m_firstShow)
364 static const char *NA = " N/A";
366 lamexp_enable_close_button(this, false);
367 ui->button_closeDialog->setEnabled(false);
368 ui->button_AbortProcess->setEnabled(false);
369 m_systemTray->setVisible(true);
371 lamexp_change_process_priority(1);
373 ui->label_cpu->setText(NA);
374 ui->label_disk->setText(NA);
375 ui->label_ram->setText(NA);
377 QTimer::singleShot(1000, this, SLOT(initEncoding()));
378 m_firstShow = false;
381 //Force update geometry
382 resizeEvent(NULL);
385 void ProcessingDialog::closeEvent(QCloseEvent *event)
387 if(!ui->button_closeDialog->isEnabled())
389 event->ignore();
391 else
393 m_systemTray->setVisible(false);
397 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
399 static QColor defaultColor = QColor();
401 if(obj == ui->label_versionInfo)
403 if(event->type() == QEvent::Enter)
405 QPalette palette = ui->label_versionInfo->palette();
406 defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
407 palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
408 ui->label_versionInfo->setPalette(palette);
410 else if(event->type() == QEvent::Leave)
412 QPalette palette = ui->label_versionInfo->palette();
413 palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
414 ui->label_versionInfo->setPalette(palette);
416 else if(event->type() == QEvent::MouseButtonPress)
418 QUrl url(lamexp_website_url());
419 QDesktopServices::openUrl(url);
423 return false;
426 bool ProcessingDialog::event(QEvent *e)
428 switch(e->type())
430 case lamexp_event_queryendsession:
431 qWarning("System is shutting down, preparing to abort...");
432 if(!m_userAborted) abortEncoding(true);
433 return true;
434 case lamexp_event_endsession:
435 qWarning("System is shutting down, encoding will be aborted now...");
436 if(isVisible())
438 while(!close())
440 if(!m_userAborted) abortEncoding(true);
441 qApp->processEvents(QEventLoop::WaitForMoreEvents | QEventLoop::ExcludeUserInputEvents);
444 m_pendingJobs.clear();
445 return true;
446 default:
447 return QDialog::event(e);
452 * Window was resized
454 void ProcessingDialog::resizeEvent(QResizeEvent *event)
456 if(event) QDialog::resizeEvent(event);
458 if(QWidget *port = ui->view_log->viewport())
460 QRect geom = port->geometry();
461 m_filterInfoLabel->setGeometry(geom.left() + 16, geom.top() + 16, geom.width() - 32, 48);
462 m_filterInfoLabelIcon->setGeometry(geom.left() + 16, geom.top() + 64, geom.width() - 32, geom.height() - 80);
466 bool ProcessingDialog::winEvent(MSG *message, long *result)
468 return WinSevenTaskbar::handleWinEvent(message, result);
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 = false;
486 m_forcedAbort = false;
487 m_playList.clear();
489 DecoderRegistry::configureDecoders(m_settings);
491 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor(Qt::white));
492 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
493 m_progressIndicator->start();
495 ui->button_closeDialog->setEnabled(false);
496 ui->button_AbortProcess->setEnabled(true);
497 ui->progressBar->setRange(0, m_pendingJobs.count());
498 ui->checkBox_shutdownComputer->setEnabled(true);
499 ui->checkBox_shutdownComputer->setChecked(false);
501 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
502 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
503 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
505 if(!m_diskObserver)
507 m_diskObserver = new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2());
508 connect(m_diskObserver, SIGNAL(messageLogged(QString,int)), m_progressModel, SLOT(addSystemMessage(QString,int)), Qt::QueuedConnection);
509 connect(m_diskObserver, SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
510 m_diskObserver->start();
512 if(!m_cpuObserver)
514 m_cpuObserver = new CPUObserverThread();
515 connect(m_cpuObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
516 m_cpuObserver->start();
518 if(!m_ramObserver)
520 m_ramObserver = new RAMObserverThread();
521 connect(m_ramObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
522 m_ramObserver->start();
525 if(!m_threadPool)
527 unsigned int maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
528 if(maximumInstances < 1)
530 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features(lamexp_arguments());
531 maximumInstances = cores2instances(qBound(1, cpuFeatures.count, 64));
534 maximumInstances = qBound(1U, maximumInstances, static_cast<unsigned int>(m_pendingJobs.count()));
535 if(maximumInstances > 1)
537 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances)));
540 m_threadPool = new QThreadPool();
541 m_threadPool->setMaxThreadCount(maximumInstances);
544 for(int i = 0; i < m_threadPool->maxThreadCount(); i++)
546 startNextJob();
547 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
548 QThread::yieldCurrentThread();
551 m_timerStart = lamexp_perfcounter_value();
554 void ProcessingDialog::startNextJob(void)
556 if(m_pendingJobs.isEmpty())
558 qWarning("No more files left, unable to start another job!");
559 return;
562 m_currentFile++;
563 m_runningThreads++;
565 AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
566 bool nativeResampling = false;
568 //Create encoder instance
569 AbstractEncoder *encoder = EncoderRegistry::createInstance(m_settings->compressionEncoder(), m_settings, &nativeResampling);
571 //Create processing thread
572 ProcessThread *thread = new ProcessThread
574 currentFile,
575 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
576 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2()),
577 encoder,
578 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
581 //Add audio filters
582 if(m_settings->forceStereoDownmix())
584 thread->addFilter(new DownmixFilter());
586 if((m_settings->samplingRate() > 0) && !nativeResampling)
588 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.techInfo().audioSamplerate() || currentFile.techInfo().audioSamplerate() == 0)
590 thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
593 if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
595 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
597 if(m_settings->normalizationFilterEnabled())
599 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEQMode()));
601 if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
603 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
605 if(m_settings->overwriteMode() != SettingsModel::Overwrite_KeepBoth)
607 thread->setOverwriteMode((m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile), (m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces));
610 m_allJobs.append(thread->getId());
612 //Connect thread signals
613 connect(thread, SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
614 connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
615 connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
616 connect(thread, SIGNAL(processStateFinished(QUuid,QString,int)), this, SLOT(processFinished(QUuid,QString,int)), Qt::QueuedConnection);
617 connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
618 connect(this, SIGNAL(abortRunningTasks()), thread, SLOT(abort()), Qt::DirectConnection);
620 //Initialize thread object
621 if(!thread->init())
623 qFatal("Fatal Error: Thread initialization has failed!");
626 //Update GUI
627 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
629 //Give it a go!
630 if(!thread->start(m_threadPool))
632 qWarning("Job failed to start or file was skipped!");
636 void ProcessingDialog::abortEncoding(bool force)
638 m_userAborted = true;
639 if(force) m_forcedAbort = true;
640 ui->button_AbortProcess->setEnabled(false);
641 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
642 emit abortRunningTasks();
645 void ProcessingDialog::doneEncoding(void)
647 m_runningThreads--;
648 ui->progressBar->setValue(ui->progressBar->value() + 1);
650 if(!m_userAborted)
652 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui->progressBar->value()).arg(QString::number(ui->progressBar->maximum())));
653 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
656 if((!m_pendingJobs.isEmpty()) && (!m_userAborted))
658 QTimer::singleShot(0, this, SLOT(startNextJob()));
659 qDebug("%d files left, starting next job...", m_pendingJobs.count());
660 return;
663 if(m_runningThreads > 0)
665 qDebug("No files left, but still have %u running jobs.", m_runningThreads);
666 return;
669 QApplication::setOverrideCursor(Qt::WaitCursor);
670 qDebug("Running jobs: %u", m_runningThreads);
672 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
674 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
675 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
676 writePlayList();
679 if(m_userAborted)
681 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFF3BA"));
682 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
683 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
684 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!"));
685 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
686 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
687 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
688 if(m_settings->soundsEnabled() && (!m_forcedAbort))
690 lamexp_play_sound(IDR_WAVE_ABORTED, false);
693 else
695 const __int64 counter = lamexp_perfcounter_value();
696 const __int64 frequency = lamexp_perfcounter_frequ();
697 if((counter >= 0I64) && (frequency >= 0))
699 if((m_timerStart >= 0I64) && (m_timerStart < counter))
701 double timeElapsed = static_cast<double>(counter - m_timerStart) / static_cast<double>(frequency);
702 m_progressModel->addSystemMessage(tr("Process finished after %1.").arg(time2text(timeElapsed)), ProgressModel::SysMsg_Performance);
706 if(m_failedJobs.count() > 0)
708 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFBABA"));
709 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
710 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
711 if(m_skippedJobs.count() > 0)
713 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())));
715 else
717 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())));
719 m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
720 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
721 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
722 if(m_settings->soundsEnabled()) lamexp_play_sound(IDR_WAVE_ERROR, false);
724 else
726 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#E0FFE2"));
727 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
728 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
729 if(m_skippedJobs.count() > 0)
731 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs.count()));
733 else
735 SET_PROGRESS_TEXT(tr("All files completed successfully."));
737 m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
738 m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
739 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
740 if(m_settings->soundsEnabled()) lamexp_play_sound(IDR_WAVE_SUCCESS, false);
744 lamexp_enable_close_button(this, true);
745 ui->button_closeDialog->setEnabled(true);
746 ui->button_AbortProcess->setEnabled(false);
747 ui->checkBox_shutdownComputer->setEnabled(false);
749 m_progressModel->restoreHiddenItems();
750 ui->view_log->scrollToBottom();
751 m_progressIndicator->stop();
752 ui->progressBar->setValue(ui->progressBar->maximum());
753 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
755 QApplication::restoreOverrideCursor();
757 if(!m_userAborted && ui->checkBox_shutdownComputer->isChecked())
759 if(shutdownComputer())
761 m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
762 accept();
767 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, int success)
769 if(success > 0)
771 m_playList.insert(jobId, outFileName);
772 m_succeededJobs.append(jobId);
774 else if(success < 0)
776 m_playList.insert(jobId, outFileName);
777 m_skippedJobs.append(jobId);
779 else
781 m_failedJobs.append(jobId);
784 //Update filter as soon as a job finished!
785 if(m_progressViewFilter >= 0)
787 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
791 void ProcessingDialog::progressModelChanged(void)
793 //Update filter as soon as the model changes!
794 if(m_progressViewFilter >= 0)
796 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
799 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
802 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
804 if(m_runningThreads == 0)
806 const QStringList &logFile = m_progressModel->getLogFile(index);
808 if(!logFile.isEmpty())
810 LogViewDialog *logView = new LogViewDialog(this);
811 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
812 logView->exec(logFile);
813 LAMEXP_DELETE(logView);
815 else
817 QMessageBox::information(this, windowTitle(), m_progressModel->data(m_progressModel->index(index.row(), 0)).toString());
820 else
822 lamexp_beep(lamexp_beep_warning);
826 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
828 if(logicalIndex == 1)
830 if(QHeaderView *hdr = ui->view_log->horizontalHeader())
832 hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
837 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
839 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
840 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
842 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
844 m_contextMenu->popup(sender->mapToGlobal(pos));
848 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
850 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
851 logViewDoubleClicked(index.isValid() ? index : ui->view_log->currentIndex());
854 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
856 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
857 const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : ui->view_log->currentIndex());
858 QString filePath = m_playList.value(jobId, QString());
860 if(filePath.isEmpty())
862 lamexp_beep(lamexp_beep_warning);
863 return;
866 if(QFileInfo(filePath).exists())
868 QString systemRootPath;
870 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
871 if(systemRoot.exists() && systemRoot.cdUp())
873 systemRootPath = systemRoot.canonicalPath();
876 if(!systemRootPath.isEmpty())
878 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
879 if(explorer.exists() && explorer.isFile())
881 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
882 return;
885 else
887 qWarning("SystemRoot directory could not be detected!");
890 else
892 qWarning("File not found: %s", filePath.toLatin1().constData());
893 lamexp_beep(lamexp_beep_error);
897 void ProcessingDialog::contextMenuFilterActionTriggered(void)
899 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
901 if(action->data().type() == QVariant::Int)
903 m_progressViewFilter = action->data().toInt();
904 progressViewFilterChanged();
905 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
906 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
907 action->setChecked(true);
913 * Filter progress items
915 void ProcessingDialog::progressViewFilterChanged(void)
917 bool matchFound = false;
919 for(int i = 0; i < ui->view_log->model()->rowCount(); i++)
921 QModelIndex index = (m_progressViewFilter >= 0) ? m_progressModel->index(i, 0) : QModelIndex();
922 const bool bHide = index.isValid() ? (m_progressModel->getJobState(index) != m_progressViewFilter) : false;
923 ui->view_log->setRowHidden(i, bHide); matchFound = matchFound || (!bHide);
926 if((m_progressViewFilter >= 0) && (!matchFound))
928 if(m_filterInfoLabel->isHidden() || (dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->value() != m_progressViewFilter))
930 dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->setValue(m_progressViewFilter);
931 m_filterInfoLabel->setText(QString("<p>&raquo; %1 &laquo;</p>").arg(tr("None of the items matches the current filtering rules")));
932 m_filterInfoLabel->show();
933 m_filterInfoLabelIcon->setPixmap(m_progressModel->getIcon(static_cast<ProgressModel::JobState>(m_progressViewFilter)).pixmap(16, 16, QIcon::Disabled));
934 m_filterInfoLabelIcon->show();
935 resizeEvent(NULL);
938 else if(!m_filterInfoLabel->isHidden())
940 m_filterInfoLabel->hide();
941 m_filterInfoLabelIcon->hide();
945 ////////////////////////////////////////////////////////////
946 // Private Functions
947 ////////////////////////////////////////////////////////////
949 void ProcessingDialog::writePlayList(void)
951 if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
953 qWarning("WritePlayList: Nothing to do!");
954 return;
957 //Init local variables
958 QStringList list;
959 QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
960 QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
961 QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
962 bool usePrefix[3] = {true, true, true};
963 bool useUtf8 = false;
964 int counter = 1;
966 //Generate playlist name
967 QString playListName = (m_metaInfo->album().isEmpty() ? "Playlist" : m_metaInfo->album());
968 if(!m_metaInfo->artist().isEmpty())
970 playListName = QString("%1 - %2").arg(m_metaInfo->artist(), playListName);
973 //Clean playlist name
974 playListName = lamexp_clean_filename(playListName);
976 //Create list of audio files
977 for(int i = 0; i < m_allJobs.count(); i++)
979 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
980 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
983 //Use prefix?
984 for(int i = 0; i < list.count(); i++)
986 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
987 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
988 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
990 if(usePrefix[0] || usePrefix[1] || usePrefix[2])
992 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
995 //Do we need an UTF-8 playlist?
996 for(int i = 0; i < list.count(); i++)
998 if(wcscmp(QWCHAR(QString::fromLatin1(list.at(i).toLatin1().constData())), QWCHAR(list.at(i))))
1000 useUtf8 = true;
1001 break;
1005 //Generate playlist output file
1006 QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
1007 while(QFileInfo(playListFile).exists())
1009 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
1012 //Now write playlist to output file
1013 QFile playList(playListFile);
1014 if(playList.open(QIODevice::WriteOnly))
1016 if(useUtf8)
1018 playList.write("\xef\xbb\xbf");
1020 playList.write("#EXTM3U\r\n");
1021 while(!list.isEmpty())
1023 playList.write(useUtf8 ? list.takeFirst().toUtf8().constData() : list.takeFirst().toLatin1().constData());
1024 playList.write("\r\n");
1026 playList.close();
1028 else
1030 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
1034 AudioFileModel ProcessingDialog::updateMetaInfo(AudioFileModel &audioFile)
1036 if(!m_settings->writeMetaTags())
1038 audioFile.metaInfo().reset();
1039 return audioFile;
1042 audioFile.metaInfo().update(*m_metaInfo, true);
1044 if(audioFile.metaInfo().position() == UINT_MAX)
1046 audioFile.metaInfo().setPosition(m_currentFile);
1049 return audioFile;
1052 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
1054 if(reason == QSystemTrayIcon::DoubleClick)
1056 lamexp_bring_to_front(this);
1060 void ProcessingDialog::cpuUsageHasChanged(const double val)
1063 ui->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1064 UPDATE_MIN_WIDTH(ui->label_cpu);
1067 void ProcessingDialog::ramUsageHasChanged(const double val)
1070 ui->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1071 UPDATE_MIN_WIDTH(ui->label_ram);
1074 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
1076 int postfix = 0;
1077 const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1078 double space = static_cast<double>(val);
1080 while((space >= 1000.0) && (postfix < 5))
1082 space = space / 1024.0;
1083 postfix++;
1086 ui->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
1087 UPDATE_MIN_WIDTH(ui->label_disk);
1090 bool ProcessingDialog::shutdownComputer(void)
1092 const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
1093 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
1094 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1096 qWarning("Initiating shutdown sequence!");
1098 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
1099 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
1100 cancelButton->setIcon(QIcon(":/icons/power_on.png"));
1101 progressDialog.setModal(true);
1102 progressDialog.setAutoClose(false);
1103 progressDialog.setAutoReset(false);
1104 progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
1105 progressDialog.setCancelButton(cancelButton);
1106 progressDialog.show();
1108 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1110 if(m_settings->soundsEnabled())
1112 QApplication::setOverrideCursor(Qt::WaitCursor);
1113 lamexp_play_sound(IDR_WAVE_SHUTDOWN, false);
1114 QApplication::restoreOverrideCursor();
1117 QTimer timer;
1118 timer.setInterval(1000);
1119 timer.start();
1121 QEventLoop eventLoop(this);
1122 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
1123 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
1125 for(int i = 1; i <= iTimeout; i++)
1127 eventLoop.exec();
1128 if(progressDialog.wasCanceled())
1130 progressDialog.close();
1131 return false;
1133 progressDialog.setValue(i+1);
1134 progressDialog.setLabelText(text.arg(iTimeout-i));
1135 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
1136 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1137 lamexp_play_sound(((i < iTimeout) ? IDR_WAVE_BEEP : IDR_WAVE_BEEP_LONG), false);
1140 progressDialog.close();
1141 return true;
1144 QString ProcessingDialog::time2text(const double timeVal) const
1146 double intPart = 0;
1147 double frcPart = modf(timeVal, &intPart);
1149 QTime time = QTime().addSecs(qRound(intPart)).addMSecs(qRound(frcPart * 1000.0));
1151 QString a, b;
1153 if(time.hour() > 0)
1155 a = tr("%n hour(s)", "", time.hour());
1156 b = tr("%n minute(s)", "", time.minute());
1158 else if(time.minute() > 0)
1160 a = tr("%n minute(s)", "", time.minute());
1161 b = tr("%n second(s)", "", time.second());
1163 else
1165 a = tr("%n second(s)", "", time.second());
1166 b = tr("%n millisecond(s)", "", time.msec());
1169 return QString("%1, %2").arg(a, b);
1172 ////////////////////////////////////////////////////////////
1173 // HELPER FUNCTIONS
1174 ////////////////////////////////////////////////////////////
1176 static int cores2instances(int cores)
1178 //This function is a "cubic spline" with sampling points at:
1179 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1180 static const double LUT[8][5] =
1182 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1183 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1184 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1185 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1186 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1187 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1188 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1189 {DBL_MAX, 0.0, 0.0, 0.0, 0.0}
1192 double x = abs(static_cast<double>(cores)), y = 1.0;
1194 for(size_t i = 0; i < 7; i++)
1196 if((x >= LUT[i][0]) && (x < LUT[i+1][0]))
1198 y = (((((LUT[i][1] * x) + LUT[i][2]) * x) + LUT[i][3]) * x) + LUT[i][4];
1199 break;
1203 return qRound(y);