OSDN Git Service

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