OSDN Git Service

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