OSDN Git Service

New formula to selected the number of instances based on CPU count.
[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
65 #include <MMSystem.h>
66 #include <math.h>
67
68 ////////////////////////////////////////////////////////////
69
70 //Maximum number of parallel instances
71 #define MAX_INSTANCES 16U
72
73 //Helper function
74 static inline double log5(double X)
75 {
76         return log(X) / log(5.0);
77 }
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 }
186
187 ////////////////////////////////////////////////////////////
188 // Destructor
189 ////////////////////////////////////////////////////////////
190
191 ProcessingDialog::~ProcessingDialog(void)
192 {
193         view_log->setModel(NULL);
194
195         if(m_progressIndicator)
196         {
197                 m_progressIndicator->stop();
198         }
199
200         if(m_diskObserver)
201         {
202                 m_diskObserver->stop();
203                 if(!m_diskObserver->wait(15000))
204                 {
205                         m_diskObserver->terminate();
206                         m_diskObserver->wait();
207                 }
208         }
209         if(m_cpuObserver)
210         {
211                 m_cpuObserver->stop();
212                 if(!m_cpuObserver->wait(15000))
213                 {
214                         m_cpuObserver->terminate();
215                         m_cpuObserver->wait();
216                 }
217         }
218         if(m_ramObserver)
219         {
220                 m_ramObserver->stop();
221                 if(!m_ramObserver->wait(15000))
222                 {
223                         m_ramObserver->terminate();
224                         m_ramObserver->wait();
225                 }
226         }
227
228         LAMEXP_DELETE(m_progressIndicator);
229         LAMEXP_DELETE(m_progressModel);
230         LAMEXP_DELETE(m_contextMenu);
231         LAMEXP_DELETE(m_systemTray);
232         LAMEXP_DELETE(m_diskObserver);
233         LAMEXP_DELETE(m_cpuObserver);
234         LAMEXP_DELETE(m_ramObserver);
235
236         WinSevenTaskbar::setOverlayIcon(this, NULL);
237         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
238
239         while(!m_threadList.isEmpty())
240         {
241                 ProcessThread *thread = m_threadList.takeFirst();
242                 thread->terminate();
243                 thread->wait(15000);
244                 delete thread;
245         }
246 }
247
248 ////////////////////////////////////////////////////////////
249 // EVENTS
250 ////////////////////////////////////////////////////////////
251
252 void ProcessingDialog::showEvent(QShowEvent *event)
253 {
254         static const char *NA = " N/A";
255
256         setCloseButtonEnabled(false);
257         button_closeDialog->setEnabled(false);
258         button_AbortProcess->setEnabled(false);
259         m_systemTray->setVisible(true);
260         
261         if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
262         {
263                 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
264         }
265
266         label_cpu->setText(NA);
267         label_disk->setText(NA);
268         label_ram->setText(NA);
269
270         QTimer::singleShot(1000, this, SLOT(initEncoding()));
271 }
272
273 void ProcessingDialog::closeEvent(QCloseEvent *event)
274 {
275         if(!button_closeDialog->isEnabled())
276         {
277                 event->ignore();
278         }
279         else
280         {
281                 m_systemTray->setVisible(false);
282         }
283 }
284
285 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
286 {
287         static QColor defaultColor = QColor();
288
289         if(obj == label_versionInfo)
290         {
291                 if(event->type() == QEvent::Enter)
292                 {
293                         QPalette palette = label_versionInfo->palette();
294                         defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
295                         palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
296                         label_versionInfo->setPalette(palette);
297                 }
298                 else if(event->type() == QEvent::Leave)
299                 {
300                         QPalette palette = label_versionInfo->palette();
301                         palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
302                         label_versionInfo->setPalette(palette);
303                 }
304                 else if(event->type() == QEvent::MouseButtonPress)
305                 {
306                         QUrl url(lamexp_website_url());
307                         QDesktopServices::openUrl(url);
308                 }
309         }
310
311         return false;
312 }
313
314 bool ProcessingDialog::winEvent(MSG *message, long *result)
315 {
316         return WinSevenTaskbar::handleWinEvent(message, result);
317 }
318
319 ////////////////////////////////////////////////////////////
320 // SLOTS
321 ////////////////////////////////////////////////////////////
322
323 void ProcessingDialog::initEncoding(void)
324 {
325         m_runningThreads = 0;
326         m_currentFile = 0;
327         m_allJobs.clear();
328         m_succeededJobs.clear();
329         m_failedJobs.clear();
330         m_userAborted = false;
331         m_playList.clear();
332         
333         CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
334         SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
335         m_progressIndicator->start();
336         
337         button_closeDialog->setEnabled(false);
338         button_AbortProcess->setEnabled(true);
339         progressBar->setRange(0, m_pendingJobs.count());
340         checkBox_shutdownComputer->setEnabled(true);
341         checkBox_shutdownComputer->setChecked(false);
342
343         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
344         WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
345         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
346
347         if(!m_diskObserver)
348         {
349                 m_diskObserver = new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2());
350                 connect(m_diskObserver, SIGNAL(messageLogged(QString,bool)), m_progressModel, SLOT(addSystemMessage(QString,bool)), Qt::QueuedConnection);
351                 connect(m_diskObserver, SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
352                 m_diskObserver->start();
353         }
354         if(!m_cpuObserver)
355         {
356                 m_cpuObserver = new CPUObserverThread();
357                 connect(m_cpuObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
358                 m_cpuObserver->start();
359         }
360         if(!m_ramObserver)
361         {
362                 m_ramObserver = new RAMObserverThread();
363                 connect(m_ramObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
364                 m_ramObserver->start();
365         }
366         
367         unsigned int maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
368         if(maximumInstances < 1)
369         {
370                 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
371                 double cpu_count = static_cast<double>(qBound(1, cpuFeatures.count, 64));
372                 maximumInstances = qRound(cpu_count / qMax(log5(cpu_count), 1.0));
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
387 void ProcessingDialog::abortEncoding(void)
388 {
389         m_userAborted = true;
390         button_AbortProcess->setEnabled(false);
391         
392         SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
393
394         for(int i = 0; i < m_threadList.count(); i++)
395         {
396                 m_threadList.at(i)->abort();
397         }
398 }
399
400 void ProcessingDialog::doneEncoding(void)
401 {
402         m_runningThreads--;
403         progressBar->setValue(progressBar->value() + 1);
404         
405         if(!m_userAborted)
406         {
407                 SET_PROGRESS_TEXT(tr("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
408                 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
409         }
410         
411         int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
412         if(index >= 0)
413         {
414                 m_threadList.takeAt(index)->deleteLater();
415         }
416
417         if(!m_pendingJobs.isEmpty() && !m_userAborted)
418         {
419                 startNextJob();
420                 qDebug("Running jobs: %u", m_runningThreads);
421                 return;
422         }
423         
424         if(m_runningThreads > 0)
425         {
426                 qDebug("Running jobs: %u", m_runningThreads);
427                 return;
428         }
429
430         QApplication::setOverrideCursor(Qt::WaitCursor);
431         qDebug("Running jobs: %u", m_runningThreads);
432
433         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
434         {
435                 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
436                 QApplication::processEvents();
437                 writePlayList();
438         }
439         
440         if(m_userAborted)
441         {
442                 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFF3BA"));
443                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
444                 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
445                 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!"));
446                 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
447                 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
448                 QApplication::processEvents();
449                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
450         }
451         else
452         {
453                 if(m_failedJobs.count() > 0)
454                 {
455                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFBABA"));
456                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
457                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
458                         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())));
459                         m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
460                         m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
461                         QApplication::processEvents();
462                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
463                 }
464                 else
465                 {
466                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#E0FFE2"));
467                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
468                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
469                         SET_PROGRESS_TEXT(tr("All files completed successfully."));
470                         m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
471                         m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
472                         QApplication::processEvents();
473                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
474                 }
475         }
476         
477         setCloseButtonEnabled(true);
478         button_closeDialog->setEnabled(true);
479         button_AbortProcess->setEnabled(false);
480         checkBox_shutdownComputer->setEnabled(false);
481
482         m_progressModel->restoreHiddenItems();
483         view_log->scrollToBottom();
484         m_progressIndicator->stop();
485         progressBar->setValue(progressBar->maximum());
486         WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
487
488         QApplication::restoreOverrideCursor();
489
490         if(!m_userAborted && checkBox_shutdownComputer->isChecked())
491         {
492                 if(shutdownComputer())
493                 {
494                         m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
495                         accept();
496                 }
497         }
498 }
499
500 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
501 {
502         if(success)
503         {
504                 m_playList.insert(jobId, outFileName);
505                 m_succeededJobs.append(jobId);
506         }
507         else
508         {
509                 m_failedJobs.append(jobId);
510         }
511 }
512
513 void ProcessingDialog::progressModelChanged(void)
514 {
515         view_log->scrollToBottom();
516 }
517
518 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
519 {
520         if(m_runningThreads == 0)
521         {
522                 const QStringList &logFile = m_progressModel->getLogFile(index);
523                 
524                 if(!logFile.isEmpty())
525                 {
526                         LogViewDialog *logView = new LogViewDialog(this);
527                         logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
528                         logView->exec(logFile);
529                         LAMEXP_DELETE(logView);
530                 }
531                 else
532                 {
533                         MessageBeep(MB_ICONWARNING);
534                 }
535         }
536         else
537         {
538                 MessageBeep(MB_ICONWARNING);
539         }
540 }
541
542 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
543 {
544         if(logicalIndex == 1)
545         {
546                 if(QHeaderView *hdr = view_log->horizontalHeader())
547                 {
548                         hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
549                 }
550         }
551 }
552
553 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
554 {
555         QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
556         QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());      
557
558         if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
559         {
560                 m_contextMenu->popup(sender->mapToGlobal(pos));
561         }
562 }
563
564 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
565 {
566         QModelIndex index = view_log->indexAt(view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
567         logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
568 }
569
570 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
571 {
572         QModelIndex index = view_log->indexAt(view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
573         const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : view_log->currentIndex());
574         QString filePath = m_playList.value(jobId, QString());
575
576         if(filePath.isEmpty())
577         {
578                 MessageBeep(MB_ICONWARNING);
579                 return;
580         }
581
582         if(QFileInfo(filePath).exists())
583         {
584                 QString systemRootPath;
585
586                 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
587                 if(systemRoot.exists() && systemRoot.cdUp())
588                 {
589                         systemRootPath = systemRoot.canonicalPath();
590                 }
591
592                 if(!systemRootPath.isEmpty())
593                 {
594                         QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
595                         if(explorer.exists() && explorer.isFile())
596                         {
597                                 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
598                                 return;
599                         }
600                 }
601                 else
602                 {
603                         qWarning("SystemRoot directory could not be detected!");
604                 }
605         }
606         else
607         {
608                 qWarning("File not found: %s", filePath.toLatin1().constData());
609                 MessageBeep(MB_ICONERROR);
610         }
611 }
612
613 ////////////////////////////////////////////////////////////
614 // Private Functions
615 ////////////////////////////////////////////////////////////
616
617 void ProcessingDialog::startNextJob(void)
618 {
619         if(m_pendingJobs.isEmpty())
620         {
621                 return;
622         }
623         
624         m_currentFile++;
625         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
626         AbstractEncoder *encoder = NULL;
627         bool nativeResampling = false;
628
629         //Create encoder instance
630         switch(m_settings->compressionEncoder())
631         {
632         case SettingsModel::MP3Encoder:
633                 {
634                         MP3Encoder *mp3Encoder = new MP3Encoder();
635                         mp3Encoder->setBitrate(m_settings->compressionBitrate());
636                         mp3Encoder->setRCMode(m_settings->compressionRCMode());
637                         mp3Encoder->setAlgoQuality(m_settings->lameAlgoQuality());
638                         if(m_settings->bitrateManagementEnabled())
639                         {
640                                 mp3Encoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
641                         }
642                         if(m_settings->samplingRate() > 0)
643                         {
644                                 mp3Encoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
645                                 nativeResampling = true;
646                         }
647                         mp3Encoder->setChannelMode(m_settings->lameChannelMode());
648                         mp3Encoder->setCustomParams(m_settings->customParametersLAME());
649                         encoder = mp3Encoder;
650                 }
651                 break;
652         case SettingsModel::VorbisEncoder:
653                 {
654                         VorbisEncoder *vorbisEncoder = new VorbisEncoder();
655                         vorbisEncoder->setBitrate(m_settings->compressionBitrate());
656                         vorbisEncoder->setRCMode(m_settings->compressionRCMode());
657                         if(m_settings->bitrateManagementEnabled())
658                         {
659                                 vorbisEncoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
660                         }
661                         if(m_settings->samplingRate() > 0)
662                         {
663                                 vorbisEncoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
664                                 nativeResampling = true;
665                         }
666                         vorbisEncoder->setCustomParams(m_settings->customParametersOggEnc());
667                         encoder = vorbisEncoder;
668                 }
669                 break;
670         case SettingsModel::AACEncoder:
671                 {
672                         if(lamexp_check_tool("qaac.exe") && lamexp_check_tool("libsoxrate.dll"))
673                         {
674                                 QAACEncoder *aacEncoder = new QAACEncoder();
675                                 aacEncoder->setBitrate(m_settings->compressionBitrate());
676                                 aacEncoder->setRCMode(m_settings->compressionRCMode());
677                                 aacEncoder->setProfile(m_settings->aacEncProfile());
678                                 aacEncoder->setCustomParams(m_settings->customParametersAacEnc());
679                                 encoder = aacEncoder;
680                         }
681                         else if(lamexp_check_tool("fhgaacenc.exe") && lamexp_check_tool("enc_fhgaac.dll"))
682                         {
683                                 FHGAACEncoder *aacEncoder = new FHGAACEncoder();
684                                 aacEncoder->setBitrate(m_settings->compressionBitrate());
685                                 aacEncoder->setRCMode(m_settings->compressionRCMode());
686                                 aacEncoder->setProfile(m_settings->aacEncProfile());
687                                 aacEncoder->setCustomParams(m_settings->customParametersAacEnc());
688                                 encoder = aacEncoder;
689                         }
690                         else
691                         {
692                                 AACEncoder *aacEncoder = new AACEncoder();
693                                 aacEncoder->setBitrate(m_settings->compressionBitrate());
694                                 aacEncoder->setRCMode(m_settings->compressionRCMode());
695                                 aacEncoder->setEnable2Pass(m_settings->neroAACEnable2Pass());
696                                 aacEncoder->setProfile(m_settings->aacEncProfile());
697                                 aacEncoder->setCustomParams(m_settings->customParametersAacEnc());
698                                 encoder = aacEncoder;
699                         }
700                 }
701                 break;
702         case SettingsModel::AC3Encoder:
703                 {
704                         AC3Encoder *ac3Encoder = new AC3Encoder();
705                         ac3Encoder->setBitrate(m_settings->compressionBitrate());
706                         ac3Encoder->setRCMode(m_settings->compressionRCMode());
707                         ac3Encoder->setCustomParams(m_settings->customParametersAften());
708                         ac3Encoder->setAudioCodingMode(m_settings->aftenAudioCodingMode());
709                         ac3Encoder->setDynamicRangeCompression(m_settings->aftenDynamicRangeCompression());
710                         ac3Encoder->setExponentSearchSize(m_settings->aftenExponentSearchSize());
711                         ac3Encoder->setFastBitAllocation(m_settings->aftenFastBitAllocation());
712                         encoder = ac3Encoder;
713                 }
714                 break;
715         case SettingsModel::FLACEncoder:
716                 {
717                         FLACEncoder *flacEncoder = new FLACEncoder();
718                         flacEncoder->setBitrate(m_settings->compressionBitrate());
719                         flacEncoder->setRCMode(m_settings->compressionRCMode());
720                         flacEncoder->setCustomParams(m_settings->customParametersFLAC());
721                         encoder = flacEncoder;
722                 }
723                 break;
724         case SettingsModel::PCMEncoder:
725                 {
726                         WaveEncoder *waveEncoder = new WaveEncoder();
727                         waveEncoder->setBitrate(m_settings->compressionBitrate());
728                         waveEncoder->setRCMode(m_settings->compressionRCMode());
729                         encoder = waveEncoder;
730                 }
731                 break;
732         default:
733                 throw "Unsupported encoder!";
734         }
735
736         //Create processing thread
737         ProcessThread *thread = new ProcessThread
738         (
739                 currentFile,
740                 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
741                 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2()),
742                 encoder,
743                 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
744         );
745
746         //Add audio filters
747         if(m_settings->forceStereoDownmix())
748         {
749                 thread->addFilter(new DownmixFilter());
750         }
751         if((m_settings->samplingRate() > 0) && !nativeResampling)
752         {
753                 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.formatAudioSamplerate() || currentFile.formatAudioSamplerate() == 0)
754                 {
755                         thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
756                 }
757         }
758         if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
759         {
760                 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
761         }
762         if(m_settings->normalizationFilterEnabled())
763         {
764                 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEqualizationMode()));
765         }
766         if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
767         {
768                 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
769         }
770
771         m_threadList.append(thread);
772         m_allJobs.append(thread->getId());
773         
774         //Connect thread signals
775         connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
776         connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
777         connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
778         connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
779         connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
780         
781         //Give it a go!
782         m_runningThreads++;
783         thread->start();
784 }
785
786 void ProcessingDialog::writePlayList(void)
787 {
788         if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
789         {
790                 qWarning("WritePlayList: Nothing to do!");
791                 return;
792         }
793         
794         //Init local variables
795         QStringList list;
796         QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
797         QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
798         QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
799         bool usePrefix[3] = {true, true, true};
800         bool useUtf8 = false;
801         int counter = 1;
802
803         //Generate playlist name
804         QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
805         if(!m_metaInfo->fileArtist().isEmpty())
806         {
807                 playListName = QString("%1 - %2").arg(m_metaInfo->fileArtist(), playListName);
808         }
809
810         //Clean playlist name
811         playListName = lamexp_clean_filename(playListName);
812
813         //Create list of audio files
814         for(int i = 0; i < m_allJobs.count(); i++)
815         {
816                 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
817                 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
818         }
819
820         //Use prefix?
821         for(int i = 0; i < list.count(); i++)
822         {
823                 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
824                 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
825                 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
826         }
827         if(usePrefix[0] || usePrefix[1] || usePrefix[2])
828         {
829                 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
830         }
831
832         //Do we need an UTF-8 playlist?
833         for(int i = 0; i < list.count(); i++)
834         {
835                 if(wcscmp(QWCHAR(QString::fromLatin1(list.at(i).toLatin1().constData())), QWCHAR(list.at(i))))
836                 {
837                         useUtf8 = true;
838                         break;
839                 }
840         }
841
842         //Generate playlist output file
843         QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
844         while(QFileInfo(playListFile).exists())
845         {
846                 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
847         }
848
849         //Now write playlist to output file
850         QFile playList(playListFile);
851         if(playList.open(QIODevice::WriteOnly))
852         {
853                 if(useUtf8)
854                 {
855                         playList.write("\xef\xbb\xbf");
856                 }
857                 playList.write("#EXTM3U\r\n");
858                 while(!list.isEmpty())
859                 {
860                         playList.write(useUtf8 ? list.takeFirst().toUtf8().constData() : list.takeFirst().toLatin1().constData());
861                         playList.write("\r\n");
862                 }
863                 playList.close();
864         }
865         else
866         {
867                 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
868         }
869 }
870
871 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
872 {
873         if(!m_settings->writeMetaTags())
874         {
875                 return AudioFileModel(audioFile, false);
876         }
877         
878         AudioFileModel result = audioFile;
879         result.updateMetaInfo(*m_metaInfo);
880         
881         if(m_metaInfo->filePosition() == UINT_MAX)
882         {
883                 result.setFilePosition(m_currentFile);
884         }
885
886         return result;
887 }
888
889 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
890 {
891         HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
892         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
893 }
894
895 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
896 {
897         if(reason == QSystemTrayIcon::DoubleClick)
898         {
899                 SetForegroundWindow(this->winId());
900         }
901 }
902
903 void ProcessingDialog::cpuUsageHasChanged(const double val)
904 {
905         
906         this->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
907         UPDATE_MIN_WIDTH(label_cpu);
908 }
909
910 void ProcessingDialog::ramUsageHasChanged(const double val)
911 {
912         
913         this->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
914         UPDATE_MIN_WIDTH(label_ram);
915 }
916
917 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
918 {
919         int postfix = 0;
920         const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
921         double space = static_cast<double>(val);
922
923         while((space >= 1000.0) && (postfix < 5))
924         {
925                 space = space / 1024.0;
926                 postfix++;
927         }
928
929         this->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
930         UPDATE_MIN_WIDTH(label_disk);
931 }
932
933 bool ProcessingDialog::shutdownComputer(void)
934 {
935         const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
936         const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
937         const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
938         
939         qWarning("Initiating shutdown sequence!");
940         
941         QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
942         QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
943         cancelButton->setIcon(QIcon(":/icons/power_on.png"));
944         progressDialog.setModal(true);
945         progressDialog.setAutoClose(false);
946         progressDialog.setAutoReset(false);
947         progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
948         progressDialog.setCancelButton(cancelButton);
949         progressDialog.show();
950         
951         QApplication::processEvents();
952
953         if(m_settings->soundsEnabled())
954         {
955                 QApplication::setOverrideCursor(Qt::WaitCursor);
956                 PlaySound(MAKEINTRESOURCE(IDR_WAVE_SHUTDOWN), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
957                 QApplication::restoreOverrideCursor();
958         }
959
960         QTimer timer;
961         timer.setInterval(1000);
962         timer.start();
963
964         QEventLoop eventLoop(this);
965         connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
966         connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
967
968         for(int i = 1; i <= iTimeout; i++)
969         {
970                 eventLoop.exec();
971                 if(progressDialog.wasCanceled())
972                 {
973                         progressDialog.close();
974                         return false;
975                 }
976                 progressDialog.setValue(i+1);
977                 progressDialog.setLabelText(text.arg(iTimeout-i));
978                 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
979                 QApplication::processEvents();
980                 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE_BEEP : IDR_WAVE_BEEP_LONG), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
981         }
982         
983         progressDialog.close();
984         return true;
985 }