OSDN Git Service

Print the total duration when the process is completed.
[lamexp/LameXP.git] / src / Dialog_Processing.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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.
14 //
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.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Dialog_Processing.h"
23
24 #include "Global.h"
25 #include "Resource.h"
26 #include "Model_FileList.h"
27 #include "Model_Progress.h"
28 #include "Model_Settings.h"
29 #include "Thread_Process.h"
30 #include "Thread_CPUObserver.h"
31 #include "Thread_RAMObserver.h"
32 #include "Thread_DiskObserver.h"
33 #include "Dialog_LogView.h"
34 #include "Encoder_MP3.h"
35 #include "Encoder_Vorbis.h"
36 #include "Encoder_AAC.h"
37 #include "Encoder_AAC_FHG.h"
38 #include "Encoder_AAC_QAAC.h"
39 #include "Encoder_AC3.h"
40 #include "Encoder_FLAC.h"
41 #include "Encoder_Wave.h"
42 #include "Filter_Downmix.h"
43 #include "Filter_Normalize.h"
44 #include "Filter_Resample.h"
45 #include "Filter_ToneAdjust.h"
46 #include "WinSevenTaskbar.h"
47
48 #include <QApplication>
49 #include <QRect>
50 #include <QDesktopWidget>
51 #include <QMovie>
52 #include <QMessageBox>
53 #include <QTimer>
54 #include <QCloseEvent>
55 #include <QDesktopServices>
56 #include <QUrl>
57 #include <QUuid>
58 #include <QFileInfo>
59 #include <QDir>
60 #include <QMenu>
61 #include <QSystemTrayIcon>
62 #include <QProcess>
63 #include <QProgressDialog>
64 #include <QTime>
65
66 #include <MMSystem.h>
67 #include <math.h>
68 #include <float.h>
69
70 ////////////////////////////////////////////////////////////
71
72 //Maximum number of parallel instances
73 #define MAX_INSTANCES 16U
74
75 //Function to calculate the number of instances
76 static int cores2instances(int cores);
77 static QString time2text(const double timeVal);
78
79 ////////////////////////////////////////////////////////////
80
81 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
82 { \
83         QPalette palette = WIDGET->palette(); \
84         palette.setColor(QPalette::Background, COLOR); \
85         WIDGET->setPalette(palette); \
86 }
87
88 #define SET_PROGRESS_TEXT(TXT) \
89 { \
90         label_progress->setText(TXT); \
91         m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
92 }
93
94 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
95 #define UPDATE_MIN_WIDTH(WIDGET) { if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); }
96
97 ////////////////////////////////////////////////////////////
98 // Constructor
99 ////////////////////////////////////////////////////////////
100
101 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
102 :
103         QDialog(parent),
104         m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
105         m_settings(settings),
106         m_metaInfo(metaInfo),
107         m_shutdownFlag(shutdownFlag_None),
108         m_diskObserver(NULL),
109         m_cpuObserver(NULL),
110         m_ramObserver(NULL)
111 {
112         //Init the dialog, from the .ui file
113         setupUi(this);
114         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
115         
116         //Setup version info
117         label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
118         label_versionInfo->installEventFilter(this);
119
120         //Register meta type
121         qRegisterMetaType<QUuid>("QUuid");
122
123         //Center window in screen
124         QRect desktopRect = QApplication::desktop()->screenGeometry();
125         QRect thisRect = this->geometry();
126         move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
127         setMinimumSize(thisRect.width(), thisRect.height());
128
129         //Enable buttons
130         connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
131         
132         //Init progress indicator
133         m_progressIndicator = new QMovie(":/images/Working.gif");
134         m_progressIndicator->setCacheMode(QMovie::CacheAll);
135         m_progressIndicator->setSpeed(50);
136         label_headerWorking->setMovie(m_progressIndicator);
137         progressBar->setValue(0);
138
139         //Init progress model
140         m_progressModel = new ProgressModel();
141         view_log->setModel(m_progressModel);
142         view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
143         view_log->verticalHeader()->hide();
144         view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
145         view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
146         view_log->viewport()->installEventFilter(this);
147         connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
148         connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
149         connect(view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
150         connect(view_log->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
151
152         //Create context menu
153         m_contextMenu = new QMenu();
154         QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
155         QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
156
157         view_log->setContextMenuPolicy(Qt::CustomContextMenu);
158         connect(view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
159         connect(contextMenuDetailsAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
160         connect(contextMenuShowFileAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
161         SET_FONT_BOLD(contextMenuDetailsAction, true);
162
163         //Enque jobs
164         if(fileListModel)
165         {
166                 for(int i = 0; i < fileListModel->rowCount(); i++)
167                 {
168                         m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
169                 }
170         }
171
172         //Translate
173         label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
174         
175         //Enable system tray icon
176         connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
177
178         //Init other vars
179         m_runningThreads = 0;
180         m_currentFile = 0;
181         m_allJobs.clear();
182         m_succeededJobs.clear();
183         m_failedJobs.clear();
184         m_userAborted = false;
185         m_timerStart = 0I64;
186 }
187
188 ////////////////////////////////////////////////////////////
189 // Destructor
190 ////////////////////////////////////////////////////////////
191
192 ProcessingDialog::~ProcessingDialog(void)
193 {
194         view_log->setModel(NULL);
195
196         if(m_progressIndicator)
197         {
198                 m_progressIndicator->stop();
199         }
200
201         if(m_diskObserver)
202         {
203                 m_diskObserver->stop();
204                 if(!m_diskObserver->wait(15000))
205                 {
206                         m_diskObserver->terminate();
207                         m_diskObserver->wait();
208                 }
209         }
210         if(m_cpuObserver)
211         {
212                 m_cpuObserver->stop();
213                 if(!m_cpuObserver->wait(15000))
214                 {
215                         m_cpuObserver->terminate();
216                         m_cpuObserver->wait();
217                 }
218         }
219         if(m_ramObserver)
220         {
221                 m_ramObserver->stop();
222                 if(!m_ramObserver->wait(15000))
223                 {
224                         m_ramObserver->terminate();
225                         m_ramObserver->wait();
226                 }
227         }
228
229         LAMEXP_DELETE(m_progressIndicator);
230         LAMEXP_DELETE(m_progressModel);
231         LAMEXP_DELETE(m_contextMenu);
232         LAMEXP_DELETE(m_systemTray);
233         LAMEXP_DELETE(m_diskObserver);
234         LAMEXP_DELETE(m_cpuObserver);
235         LAMEXP_DELETE(m_ramObserver);
236
237         WinSevenTaskbar::setOverlayIcon(this, NULL);
238         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
239
240         while(!m_threadList.isEmpty())
241         {
242                 ProcessThread *thread = m_threadList.takeFirst();
243                 thread->terminate();
244                 thread->wait(15000);
245                 delete thread;
246         }
247 }
248
249 ////////////////////////////////////////////////////////////
250 // EVENTS
251 ////////////////////////////////////////////////////////////
252
253 void ProcessingDialog::showEvent(QShowEvent *event)
254 {
255         static const char *NA = " N/A";
256
257         setCloseButtonEnabled(false);
258         button_closeDialog->setEnabled(false);
259         button_AbortProcess->setEnabled(false);
260         m_systemTray->setVisible(true);
261         
262         if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
263         {
264                 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
265         }
266
267         label_cpu->setText(NA);
268         label_disk->setText(NA);
269         label_ram->setText(NA);
270
271         QTimer::singleShot(1000, this, SLOT(initEncoding()));
272 }
273
274 void ProcessingDialog::closeEvent(QCloseEvent *event)
275 {
276         if(!button_closeDialog->isEnabled())
277         {
278                 event->ignore();
279         }
280         else
281         {
282                 m_systemTray->setVisible(false);
283         }
284 }
285
286 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
287 {
288         static QColor defaultColor = QColor();
289
290         if(obj == label_versionInfo)
291         {
292                 if(event->type() == QEvent::Enter)
293                 {
294                         QPalette palette = label_versionInfo->palette();
295                         defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
296                         palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
297                         label_versionInfo->setPalette(palette);
298                 }
299                 else if(event->type() == QEvent::Leave)
300                 {
301                         QPalette palette = label_versionInfo->palette();
302                         palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
303                         label_versionInfo->setPalette(palette);
304                 }
305                 else if(event->type() == QEvent::MouseButtonPress)
306                 {
307                         QUrl url(lamexp_website_url());
308                         QDesktopServices::openUrl(url);
309                 }
310         }
311
312         return false;
313 }
314
315 bool ProcessingDialog::winEvent(MSG *message, long *result)
316 {
317         return WinSevenTaskbar::handleWinEvent(message, result);
318 }
319
320 ////////////////////////////////////////////////////////////
321 // SLOTS
322 ////////////////////////////////////////////////////////////
323
324 void ProcessingDialog::initEncoding(void)
325 {
326         m_runningThreads = 0;
327         m_currentFile = 0;
328         m_allJobs.clear();
329         m_succeededJobs.clear();
330         m_failedJobs.clear();
331         m_userAborted = false;
332         m_playList.clear();
333         
334         CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
335         SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
336         m_progressIndicator->start();
337         
338         button_closeDialog->setEnabled(false);
339         button_AbortProcess->setEnabled(true);
340         progressBar->setRange(0, m_pendingJobs.count());
341         checkBox_shutdownComputer->setEnabled(true);
342         checkBox_shutdownComputer->setChecked(false);
343
344         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
345         WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
346         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
347
348         if(!m_diskObserver)
349         {
350                 m_diskObserver = new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2());
351                 connect(m_diskObserver, SIGNAL(messageLogged(QString,int)), m_progressModel, SLOT(addSystemMessage(QString,int)), Qt::QueuedConnection);
352                 connect(m_diskObserver, SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
353                 m_diskObserver->start();
354         }
355         if(!m_cpuObserver)
356         {
357                 m_cpuObserver = new CPUObserverThread();
358                 connect(m_cpuObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
359                 m_cpuObserver->start();
360         }
361         if(!m_ramObserver)
362         {
363                 m_ramObserver = new RAMObserverThread();
364                 connect(m_ramObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
365                 m_ramObserver->start();
366         }
367         
368         unsigned int maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
369         if(maximumInstances < 1)
370         {
371                 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
372                 maximumInstances = cores2instances(qBound(1, cpuFeatures.count, 64));
373         }
374
375         maximumInstances = qBound(1U, maximumInstances, static_cast<unsigned int>(m_pendingJobs.count()));
376         if(maximumInstances > 1)
377         {
378                 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances)));
379         }
380
381         for(unsigned int i = 0; i < maximumInstances; i++)
382         {
383                 startNextJob();
384         }
385
386         LARGE_INTEGER counter;
387         if(QueryPerformanceCounter(&counter))
388         {
389                 m_timerStart = counter.QuadPart;
390         }
391 }
392
393 void ProcessingDialog::abortEncoding(void)
394 {
395         m_userAborted = true;
396         button_AbortProcess->setEnabled(false);
397         
398         SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
399
400         for(int i = 0; i < m_threadList.count(); i++)
401         {
402                 m_threadList.at(i)->abort();
403         }
404 }
405
406 void ProcessingDialog::doneEncoding(void)
407 {
408         m_runningThreads--;
409         progressBar->setValue(progressBar->value() + 1);
410         
411         if(!m_userAborted)
412         {
413                 SET_PROGRESS_TEXT(tr("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
414                 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
415         }
416         
417         int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
418         if(index >= 0)
419         {
420                 m_threadList.takeAt(index)->deleteLater();
421         }
422
423         if(!m_pendingJobs.isEmpty() && !m_userAborted)
424         {
425                 startNextJob();
426                 qDebug("Running jobs: %u", m_runningThreads);
427                 return;
428         }
429         
430         if(m_runningThreads > 0)
431         {
432                 qDebug("Running jobs: %u", m_runningThreads);
433                 return;
434         }
435
436         QApplication::setOverrideCursor(Qt::WaitCursor);
437         qDebug("Running jobs: %u", m_runningThreads);
438
439         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
440         {
441                 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
442                 QApplication::processEvents();
443                 writePlayList();
444         }
445         
446         if(m_userAborted)
447         {
448                 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFF3BA"));
449                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
450                 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
451                 SET_PROGRESS_TEXT((m_succeededJobs.count() > 0) ? tr("Process was aborted by the user after %1 file(s)!").arg(QString::number(m_succeededJobs.count())) : tr("Process was aborted prematurely by the user!"));
452                 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
453                 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
454                 QApplication::processEvents();
455                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
456         }
457         else
458         {
459                 LARGE_INTEGER counter, frequency;
460                 if(QueryPerformanceCounter(&counter) && QueryPerformanceFrequency(&frequency))
461                 {
462                         if((m_timerStart > 0I64) && (frequency.QuadPart > 0I64) && (m_timerStart < counter.QuadPart))
463                         {
464                                 double timeElapsed = static_cast<double>(counter.QuadPart - m_timerStart) / static_cast<double>(frequency.QuadPart);
465                                 m_progressModel->addSystemMessage(tr("Process finished after %1.").arg(time2text(timeElapsed)), ProgressModel::SysMsg_Performance);
466                         }
467                 }
468
469                 if(m_failedJobs.count() > 0)
470                 {
471                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFBABA"));
472                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
473                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
474                         SET_PROGRESS_TEXT(tr("Error: %1 of %2 files failed. Double-click failed items for detailed information!").arg(QString::number(m_failedJobs.count()), QString::number(m_failedJobs.count() + m_succeededJobs.count())));
475                         m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
476                         m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
477                         QApplication::processEvents();
478                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
479                 }
480                 else
481                 {
482                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#E0FFE2"));
483                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
484                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
485                         SET_PROGRESS_TEXT(tr("All files completed successfully."));
486                         m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
487                         m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
488                         QApplication::processEvents();
489                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
490                 }
491         }
492         
493         setCloseButtonEnabled(true);
494         button_closeDialog->setEnabled(true);
495         button_AbortProcess->setEnabled(false);
496         checkBox_shutdownComputer->setEnabled(false);
497
498         m_progressModel->restoreHiddenItems();
499         view_log->scrollToBottom();
500         m_progressIndicator->stop();
501         progressBar->setValue(progressBar->maximum());
502         WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
503
504         QApplication::restoreOverrideCursor();
505
506         if(!m_userAborted && checkBox_shutdownComputer->isChecked())
507         {
508                 if(shutdownComputer())
509                 {
510                         m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
511                         accept();
512                 }
513         }
514 }
515
516 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
517 {
518         if(success)
519         {
520                 m_playList.insert(jobId, outFileName);
521                 m_succeededJobs.append(jobId);
522         }
523         else
524         {
525                 m_failedJobs.append(jobId);
526         }
527 }
528
529 void ProcessingDialog::progressModelChanged(void)
530 {
531         view_log->scrollToBottom();
532 }
533
534 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
535 {
536         if(m_runningThreads == 0)
537         {
538                 const QStringList &logFile = m_progressModel->getLogFile(index);
539                 
540                 if(!logFile.isEmpty())
541                 {
542                         LogViewDialog *logView = new LogViewDialog(this);
543                         logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
544                         logView->exec(logFile);
545                         LAMEXP_DELETE(logView);
546                 }
547                 else
548                 {
549                         MessageBeep(MB_ICONWARNING);
550                 }
551         }
552         else
553         {
554                 MessageBeep(MB_ICONWARNING);
555         }
556 }
557
558 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
559 {
560         if(logicalIndex == 1)
561         {
562                 if(QHeaderView *hdr = view_log->horizontalHeader())
563                 {
564                         hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
565                 }
566         }
567 }
568
569 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
570 {
571         QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
572         QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());      
573
574         if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
575         {
576                 m_contextMenu->popup(sender->mapToGlobal(pos));
577         }
578 }
579
580 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
581 {
582         QModelIndex index = view_log->indexAt(view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
583         logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
584 }
585
586 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
587 {
588         QModelIndex index = view_log->indexAt(view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
589         const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : view_log->currentIndex());
590         QString filePath = m_playList.value(jobId, QString());
591
592         if(filePath.isEmpty())
593         {
594                 MessageBeep(MB_ICONWARNING);
595                 return;
596         }
597
598         if(QFileInfo(filePath).exists())
599         {
600                 QString systemRootPath;
601
602                 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
603                 if(systemRoot.exists() && systemRoot.cdUp())
604                 {
605                         systemRootPath = systemRoot.canonicalPath();
606                 }
607
608                 if(!systemRootPath.isEmpty())
609                 {
610                         QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
611                         if(explorer.exists() && explorer.isFile())
612                         {
613                                 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
614                                 return;
615                         }
616                 }
617                 else
618                 {
619                         qWarning("SystemRoot directory could not be detected!");
620                 }
621         }
622         else
623         {
624                 qWarning("File not found: %s", filePath.toLatin1().constData());
625                 MessageBeep(MB_ICONERROR);
626         }
627 }
628
629 ////////////////////////////////////////////////////////////
630 // Private Functions
631 ////////////////////////////////////////////////////////////
632
633 void ProcessingDialog::startNextJob(void)
634 {
635         if(m_pendingJobs.isEmpty())
636         {
637                 return;
638         }
639         
640         m_currentFile++;
641         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
642         AbstractEncoder *encoder = NULL;
643         bool nativeResampling = false;
644
645         //Create encoder instance
646         switch(m_settings->compressionEncoder())
647         {
648         case SettingsModel::MP3Encoder:
649                 {
650                         MP3Encoder *mp3Encoder = new MP3Encoder();
651                         mp3Encoder->setBitrate(m_settings->compressionBitrate());
652                         mp3Encoder->setRCMode(m_settings->compressionRCMode());
653                         mp3Encoder->setAlgoQuality(m_settings->lameAlgoQuality());
654                         if(m_settings->bitrateManagementEnabled())
655                         {
656                                 mp3Encoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
657                         }
658                         if(m_settings->samplingRate() > 0)
659                         {
660                                 mp3Encoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
661                                 nativeResampling = true;
662                         }
663                         mp3Encoder->setChannelMode(m_settings->lameChannelMode());
664                         mp3Encoder->setCustomParams(m_settings->customParametersLAME());
665                         encoder = mp3Encoder;
666                 }
667                 break;
668         case SettingsModel::VorbisEncoder:
669                 {
670                         VorbisEncoder *vorbisEncoder = new VorbisEncoder();
671                         vorbisEncoder->setBitrate(m_settings->compressionBitrate());
672                         vorbisEncoder->setRCMode(m_settings->compressionRCMode());
673                         if(m_settings->bitrateManagementEnabled())
674                         {
675                                 vorbisEncoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
676                         }
677                         if(m_settings->samplingRate() > 0)
678                         {
679                                 vorbisEncoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
680                                 nativeResampling = true;
681                         }
682                         vorbisEncoder->setCustomParams(m_settings->customParametersOggEnc());
683                         encoder = vorbisEncoder;
684                 }
685                 break;
686         case SettingsModel::AACEncoder:
687                 {
688                         if(lamexp_check_tool("qaac.exe") && lamexp_check_tool("libsoxrate.dll"))
689                         {
690                                 QAACEncoder *aacEncoder = new QAACEncoder();
691                                 aacEncoder->setBitrate(m_settings->compressionBitrate());
692                                 aacEncoder->setRCMode(m_settings->compressionRCMode());
693                                 aacEncoder->setProfile(m_settings->aacEncProfile());
694                                 aacEncoder->setCustomParams(m_settings->customParametersAacEnc());
695                                 encoder = aacEncoder;
696                         }
697                         else if(lamexp_check_tool("fhgaacenc.exe") && lamexp_check_tool("enc_fhgaac.dll"))
698                         {
699                                 FHGAACEncoder *aacEncoder = new FHGAACEncoder();
700                                 aacEncoder->setBitrate(m_settings->compressionBitrate());
701                                 aacEncoder->setRCMode(m_settings->compressionRCMode());
702                                 aacEncoder->setProfile(m_settings->aacEncProfile());
703                                 aacEncoder->setCustomParams(m_settings->customParametersAacEnc());
704                                 encoder = aacEncoder;
705                         }
706                         else
707                         {
708                                 AACEncoder *aacEncoder = new AACEncoder();
709                                 aacEncoder->setBitrate(m_settings->compressionBitrate());
710                                 aacEncoder->setRCMode(m_settings->compressionRCMode());
711                                 aacEncoder->setEnable2Pass(m_settings->neroAACEnable2Pass());
712                                 aacEncoder->setProfile(m_settings->aacEncProfile());
713                                 aacEncoder->setCustomParams(m_settings->customParametersAacEnc());
714                                 encoder = aacEncoder;
715                         }
716                 }
717                 break;
718         case SettingsModel::AC3Encoder:
719                 {
720                         AC3Encoder *ac3Encoder = new AC3Encoder();
721                         ac3Encoder->setBitrate(m_settings->compressionBitrate());
722                         ac3Encoder->setRCMode(m_settings->compressionRCMode());
723                         ac3Encoder->setCustomParams(m_settings->customParametersAften());
724                         ac3Encoder->setAudioCodingMode(m_settings->aftenAudioCodingMode());
725                         ac3Encoder->setDynamicRangeCompression(m_settings->aftenDynamicRangeCompression());
726                         ac3Encoder->setExponentSearchSize(m_settings->aftenExponentSearchSize());
727                         ac3Encoder->setFastBitAllocation(m_settings->aftenFastBitAllocation());
728                         encoder = ac3Encoder;
729                 }
730                 break;
731         case SettingsModel::FLACEncoder:
732                 {
733                         FLACEncoder *flacEncoder = new FLACEncoder();
734                         flacEncoder->setBitrate(m_settings->compressionBitrate());
735                         flacEncoder->setRCMode(m_settings->compressionRCMode());
736                         flacEncoder->setCustomParams(m_settings->customParametersFLAC());
737                         encoder = flacEncoder;
738                 }
739                 break;
740         case SettingsModel::PCMEncoder:
741                 {
742                         WaveEncoder *waveEncoder = new WaveEncoder();
743                         waveEncoder->setBitrate(m_settings->compressionBitrate());
744                         waveEncoder->setRCMode(m_settings->compressionRCMode());
745                         encoder = waveEncoder;
746                 }
747                 break;
748         default:
749                 throw "Unsupported encoder!";
750         }
751
752         //Create processing thread
753         ProcessThread *thread = new ProcessThread
754         (
755                 currentFile,
756                 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
757                 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2()),
758                 encoder,
759                 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
760         );
761
762         //Add audio filters
763         if(m_settings->forceStereoDownmix())
764         {
765                 thread->addFilter(new DownmixFilter());
766         }
767         if((m_settings->samplingRate() > 0) && !nativeResampling)
768         {
769                 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.formatAudioSamplerate() || currentFile.formatAudioSamplerate() == 0)
770                 {
771                         thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
772                 }
773         }
774         if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
775         {
776                 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
777         }
778         if(m_settings->normalizationFilterEnabled())
779         {
780                 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEqualizationMode()));
781         }
782         if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
783         {
784                 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
785         }
786
787         m_threadList.append(thread);
788         m_allJobs.append(thread->getId());
789         
790         //Connect thread signals
791         connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
792         connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
793         connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
794         connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
795         connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
796         
797         //Give it a go!
798         m_runningThreads++;
799         thread->start();
800 }
801
802 void ProcessingDialog::writePlayList(void)
803 {
804         if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
805         {
806                 qWarning("WritePlayList: Nothing to do!");
807                 return;
808         }
809         
810         //Init local variables
811         QStringList list;
812         QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
813         QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
814         QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
815         bool usePrefix[3] = {true, true, true};
816         bool useUtf8 = false;
817         int counter = 1;
818
819         //Generate playlist name
820         QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
821         if(!m_metaInfo->fileArtist().isEmpty())
822         {
823                 playListName = QString("%1 - %2").arg(m_metaInfo->fileArtist(), playListName);
824         }
825
826         //Clean playlist name
827         playListName = lamexp_clean_filename(playListName);
828
829         //Create list of audio files
830         for(int i = 0; i < m_allJobs.count(); i++)
831         {
832                 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
833                 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
834         }
835
836         //Use prefix?
837         for(int i = 0; i < list.count(); i++)
838         {
839                 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
840                 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
841                 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
842         }
843         if(usePrefix[0] || usePrefix[1] || usePrefix[2])
844         {
845                 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
846         }
847
848         //Do we need an UTF-8 playlist?
849         for(int i = 0; i < list.count(); i++)
850         {
851                 if(wcscmp(QWCHAR(QString::fromLatin1(list.at(i).toLatin1().constData())), QWCHAR(list.at(i))))
852                 {
853                         useUtf8 = true;
854                         break;
855                 }
856         }
857
858         //Generate playlist output file
859         QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
860         while(QFileInfo(playListFile).exists())
861         {
862                 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
863         }
864
865         //Now write playlist to output file
866         QFile playList(playListFile);
867         if(playList.open(QIODevice::WriteOnly))
868         {
869                 if(useUtf8)
870                 {
871                         playList.write("\xef\xbb\xbf");
872                 }
873                 playList.write("#EXTM3U\r\n");
874                 while(!list.isEmpty())
875                 {
876                         playList.write(useUtf8 ? list.takeFirst().toUtf8().constData() : list.takeFirst().toLatin1().constData());
877                         playList.write("\r\n");
878                 }
879                 playList.close();
880         }
881         else
882         {
883                 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
884         }
885 }
886
887 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
888 {
889         if(!m_settings->writeMetaTags())
890         {
891                 return AudioFileModel(audioFile, false);
892         }
893         
894         AudioFileModel result = audioFile;
895         result.updateMetaInfo(*m_metaInfo);
896         
897         if(m_metaInfo->filePosition() == UINT_MAX)
898         {
899                 result.setFilePosition(m_currentFile);
900         }
901
902         return result;
903 }
904
905 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
906 {
907         HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
908         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
909 }
910
911 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
912 {
913         if(reason == QSystemTrayIcon::DoubleClick)
914         {
915                 SetForegroundWindow(this->winId());
916         }
917 }
918
919 void ProcessingDialog::cpuUsageHasChanged(const double val)
920 {
921         
922         this->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
923         UPDATE_MIN_WIDTH(label_cpu);
924 }
925
926 void ProcessingDialog::ramUsageHasChanged(const double val)
927 {
928         
929         this->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
930         UPDATE_MIN_WIDTH(label_ram);
931 }
932
933 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
934 {
935         int postfix = 0;
936         const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
937         double space = static_cast<double>(val);
938
939         while((space >= 1000.0) && (postfix < 5))
940         {
941                 space = space / 1024.0;
942                 postfix++;
943         }
944
945         this->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
946         UPDATE_MIN_WIDTH(label_disk);
947 }
948
949 bool ProcessingDialog::shutdownComputer(void)
950 {
951         const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
952         const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
953         const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
954         
955         qWarning("Initiating shutdown sequence!");
956         
957         QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
958         QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
959         cancelButton->setIcon(QIcon(":/icons/power_on.png"));
960         progressDialog.setModal(true);
961         progressDialog.setAutoClose(false);
962         progressDialog.setAutoReset(false);
963         progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
964         progressDialog.setCancelButton(cancelButton);
965         progressDialog.show();
966         
967         QApplication::processEvents();
968
969         if(m_settings->soundsEnabled())
970         {
971                 QApplication::setOverrideCursor(Qt::WaitCursor);
972                 PlaySound(MAKEINTRESOURCE(IDR_WAVE_SHUTDOWN), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
973                 QApplication::restoreOverrideCursor();
974         }
975
976         QTimer timer;
977         timer.setInterval(1000);
978         timer.start();
979
980         QEventLoop eventLoop(this);
981         connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
982         connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
983
984         for(int i = 1; i <= iTimeout; i++)
985         {
986                 eventLoop.exec();
987                 if(progressDialog.wasCanceled())
988                 {
989                         progressDialog.close();
990                         return false;
991                 }
992                 progressDialog.setValue(i+1);
993                 progressDialog.setLabelText(text.arg(iTimeout-i));
994                 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
995                 QApplication::processEvents();
996                 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE_BEEP : IDR_WAVE_BEEP_LONG), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
997         }
998         
999         progressDialog.close();
1000         return true;
1001 }
1002
1003 QString ProcessingDialog::time2text(const double timeVal) const
1004 {
1005         double intPart = 0;
1006         double frcPart = modf(timeVal, &intPart);
1007         int x = 0, y = 0; QString a, b;
1008
1009         QTime time = QTime().addSecs(qRound(intPart)).addMSecs(qRound(frcPart * 1000.0));
1010
1011         if(time.hour() > 0)
1012         {
1013                 x = time.hour();   a = tr("hour(s)");
1014                 y = time.minute(); b = tr("minute(s)");
1015         }
1016         else if(time.minute() > 0)
1017         {
1018                 x = time.minute(); a = tr("minute(s)");
1019                 y = time.second(); b = tr("second(s)");
1020         }
1021         else
1022         {
1023                 x = time.second(); a = tr("second(s)");
1024                 y = time.msec();   b = tr("millisecond(s)");
1025         }
1026
1027         return QString("%1 %2, %3 %4").arg(QString::number(x), a, QString::number(y), b);
1028 }
1029
1030 ////////////////////////////////////////////////////////////
1031 // HELPER FUNCTIONS
1032 ////////////////////////////////////////////////////////////
1033
1034 static int cores2instances(int cores)
1035 {
1036         //This function is a "cubic spline" with sampling points at:
1037         //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1038         static const double LUT[8][5] =
1039         {
1040                 { 1.0,  0.014353554, -0.043060662, 1.028707108,  0.000000000},
1041                 { 2.0, -0.028707108,  0.215303309, 0.511979167,  0.344485294},
1042                 { 4.0,  0.010016468, -0.249379596, 2.370710784, -2.133823529},
1043                 { 8.0,  0.000282437, -0.015762868, 0.501776961,  2.850000000},
1044                 {16.0,  0.000033270, -0.003802849, 0.310416667,  3.870588235},
1045                 {32.0,  0.000006343, -0.001217831, 0.227696078,  4.752941176},
1046                 {64.0,  0.000000000,  0.000000000, 0.000000000, 16.000000000},
1047                 {DBL_MAX, 0.0, 0.0, 0.0, 0.0}
1048         };
1049
1050         double x = abs(static_cast<double>(cores)), y = 1.0;
1051         
1052         for(size_t i = 0; i < 7; i++)
1053         {
1054                 if((x >= LUT[i][0]) && (x < LUT[i+1][0]))
1055                 {
1056                         y = (LUT[i][1] * pow(x, 3.0)) + (LUT[i][2] * pow(x, 2.0)) + (LUT[i][3] * x) + LUT[i][4];
1057                         break;
1058                 }
1059         }
1060
1061         return qRound(y);
1062 }