OSDN Git Service

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