OSDN Git Service

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