Adjusted QAAC detection for shared 'libsoxrate' library.
[LameXP.git] / src / Dialog_Processing.cpp
blob7eb6f3599fac4aad409480ad4fba401d9418e903
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.
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.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Dialog_Processing.h"
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"
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>
65 #include <MMSystem.h>
67 ////////////////////////////////////////////////////////////
69 //Maximum number of parallel instances
70 #define MAX_INSTANCES 16U
72 ////////////////////////////////////////////////////////////
74 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
75 { \
76 QPalette palette = WIDGET->palette(); \
77 palette.setColor(QPalette::Background, COLOR); \
78 WIDGET->setPalette(palette); \
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())); \
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()); }
90 ////////////////////////////////////////////////////////////
91 // Constructor
92 ////////////////////////////////////////////////////////////
94 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
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)
105 //Init the dialog, from the .ui file
106 setupUi(this);
107 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
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);
113 //Register meta type
114 qRegisterMetaType<QUuid>("QUuid");
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());
122 //Enable buttons
123 connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
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);
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)));
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"));
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);
156 //Enque jobs
157 if(fileListModel)
159 for(int i = 0; i < fileListModel->rowCount(); i++)
161 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
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...")));
168 //Enable system tray icon
169 connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
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;
180 ////////////////////////////////////////////////////////////
181 // Destructor
182 ////////////////////////////////////////////////////////////
184 ProcessingDialog::~ProcessingDialog(void)
186 view_log->setModel(NULL);
188 if(m_progressIndicator)
190 m_progressIndicator->stop();
193 if(m_diskObserver)
195 m_diskObserver->stop();
196 if(!m_diskObserver->wait(15000))
198 m_diskObserver->terminate();
199 m_diskObserver->wait();
202 if(m_cpuObserver)
204 m_cpuObserver->stop();
205 if(!m_cpuObserver->wait(15000))
207 m_cpuObserver->terminate();
208 m_cpuObserver->wait();
211 if(m_ramObserver)
213 m_ramObserver->stop();
214 if(!m_ramObserver->wait(15000))
216 m_ramObserver->terminate();
217 m_ramObserver->wait();
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);
229 WinSevenTaskbar::setOverlayIcon(this, NULL);
230 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
232 while(!m_threadList.isEmpty())
234 ProcessThread *thread = m_threadList.takeFirst();
235 thread->terminate();
236 thread->wait(15000);
237 delete thread;
241 ////////////////////////////////////////////////////////////
242 // EVENTS
243 ////////////////////////////////////////////////////////////
245 void ProcessingDialog::showEvent(QShowEvent *event)
247 static const char *NA = " N/A";
249 setCloseButtonEnabled(false);
250 button_closeDialog->setEnabled(false);
251 button_AbortProcess->setEnabled(false);
252 m_systemTray->setVisible(true);
254 if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
256 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
259 label_cpu->setText(NA);
260 label_disk->setText(NA);
261 label_ram->setText(NA);
263 QTimer::singleShot(1000, this, SLOT(initEncoding()));
266 void ProcessingDialog::closeEvent(QCloseEvent *event)
268 if(!button_closeDialog->isEnabled())
270 event->ignore();
272 else
274 m_systemTray->setVisible(false);
278 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
280 static QColor defaultColor = QColor();
282 if(obj == label_versionInfo)
284 if(event->type() == QEvent::Enter)
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);
291 else if(event->type() == QEvent::Leave)
293 QPalette palette = label_versionInfo->palette();
294 palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
295 label_versionInfo->setPalette(palette);
297 else if(event->type() == QEvent::MouseButtonPress)
299 QUrl url(lamexp_website_url());
300 QDesktopServices::openUrl(url);
304 return false;
307 bool ProcessingDialog::winEvent(MSG *message, long *result)
309 return WinSevenTaskbar::handleWinEvent(message, result);
312 ////////////////////////////////////////////////////////////
313 // SLOTS
314 ////////////////////////////////////////////////////////////
316 void ProcessingDialog::initEncoding(void)
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();
326 CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
327 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
328 m_progressIndicator->start();
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);
336 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
337 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
338 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
340 if(!m_diskObserver)
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();
347 if(!m_cpuObserver)
349 m_cpuObserver = new CPUObserverThread();
350 connect(m_cpuObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
351 m_cpuObserver->start();
353 if(!m_ramObserver)
355 m_ramObserver = new RAMObserverThread();
356 connect(m_ramObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
357 m_ramObserver->start();
360 unsigned int maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
361 if(maximumInstances < 1)
363 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
364 maximumInstances = (cpuFeatures.count > 4) ? ((cpuFeatures.count / 2) + 2) : cpuFeatures.count;
367 unsigned int parallelThreadCount = qBound(1U, maximumInstances, static_cast<unsigned int>(m_pendingJobs.count()));
368 if(parallelThreadCount > 1)
370 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(parallelThreadCount)));
373 for(unsigned int i = 0; i < parallelThreadCount; i++)
375 startNextJob();
379 void ProcessingDialog::abortEncoding(void)
381 m_userAborted = true;
382 button_AbortProcess->setEnabled(false);
384 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
386 for(int i = 0; i < m_threadList.count(); i++)
388 m_threadList.at(i)->abort();
392 void ProcessingDialog::doneEncoding(void)
394 m_runningThreads--;
395 progressBar->setValue(progressBar->value() + 1);
397 if(!m_userAborted)
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());
403 int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
404 if(index >= 0)
406 m_threadList.takeAt(index)->deleteLater();
409 if(!m_pendingJobs.isEmpty() && !m_userAborted)
411 startNextJob();
412 qDebug("Running jobs: %u", m_runningThreads);
413 return;
416 if(m_runningThreads > 0)
418 qDebug("Running jobs: %u", m_runningThreads);
419 return;
422 QApplication::setOverrideCursor(Qt::WaitCursor);
423 qDebug("Running jobs: %u", m_runningThreads);
425 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
427 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
428 QApplication::processEvents();
429 writePlayList();
432 if(m_userAborted)
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);
443 else
445 if(m_failedJobs.count() > 0)
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);
456 else
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);
469 setCloseButtonEnabled(true);
470 button_closeDialog->setEnabled(true);
471 button_AbortProcess->setEnabled(false);
472 checkBox_shutdownComputer->setEnabled(false);
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());
480 QApplication::restoreOverrideCursor();
482 if(!m_userAborted && checkBox_shutdownComputer->isChecked())
484 if(shutdownComputer())
486 m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
487 accept();
492 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
494 if(success)
496 m_playList.insert(jobId, outFileName);
497 m_succeededJobs.append(jobId);
499 else
501 m_failedJobs.append(jobId);
505 void ProcessingDialog::progressModelChanged(void)
507 view_log->scrollToBottom();
510 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
512 if(m_runningThreads == 0)
514 const QStringList &logFile = m_progressModel->getLogFile(index);
516 if(!logFile.isEmpty())
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);
523 else
525 MessageBeep(MB_ICONWARNING);
528 else
530 MessageBeep(MB_ICONWARNING);
534 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
536 if(logicalIndex == 1)
538 if(QHeaderView *hdr = view_log->horizontalHeader())
540 hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
545 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
547 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
548 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
550 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
552 m_contextMenu->popup(sender->mapToGlobal(pos));
556 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
558 QModelIndex index = view_log->indexAt(view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
559 logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
562 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
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());
568 if(filePath.isEmpty())
570 MessageBeep(MB_ICONWARNING);
571 return;
574 if(QFileInfo(filePath).exists())
576 QString systemRootPath;
578 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
579 if(systemRoot.exists() && systemRoot.cdUp())
581 systemRootPath = systemRoot.canonicalPath();
584 if(!systemRootPath.isEmpty())
586 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
587 if(explorer.exists() && explorer.isFile())
589 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
590 return;
593 else
595 qWarning("SystemRoot directory could not be detected!");
598 else
600 qWarning("File not found: %s", filePath.toLatin1().constData());
601 MessageBeep(MB_ICONERROR);
605 ////////////////////////////////////////////////////////////
606 // Private Functions
607 ////////////////////////////////////////////////////////////
609 void ProcessingDialog::startNextJob(void)
611 if(m_pendingJobs.isEmpty())
613 return;
616 m_currentFile++;
617 AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
618 AbstractEncoder *encoder = NULL;
619 bool nativeResampling = false;
621 //Create encoder instance
622 switch(m_settings->compressionEncoder())
624 case SettingsModel::MP3Encoder:
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())
632 mp3Encoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
634 if(m_settings->samplingRate() > 0)
636 mp3Encoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
637 nativeResampling = true;
639 mp3Encoder->setChannelMode(m_settings->lameChannelMode());
640 mp3Encoder->setCustomParams(m_settings->customParametersLAME());
641 encoder = mp3Encoder;
643 break;
644 case SettingsModel::VorbisEncoder:
646 VorbisEncoder *vorbisEncoder = new VorbisEncoder();
647 vorbisEncoder->setBitrate(m_settings->compressionBitrate());
648 vorbisEncoder->setRCMode(m_settings->compressionRCMode());
649 if(m_settings->bitrateManagementEnabled())
651 vorbisEncoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
653 if(m_settings->samplingRate() > 0)
655 vorbisEncoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
656 nativeResampling = true;
658 vorbisEncoder->setCustomParams(m_settings->customParametersOggEnc());
659 encoder = vorbisEncoder;
661 break;
662 case SettingsModel::AACEncoder:
664 if(lamexp_check_tool("qaac.exe") && lamexp_check_tool("libsoxrate.dll"))
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;
673 else if(lamexp_check_tool("fhgaacenc.exe") && lamexp_check_tool("enc_fhgaac.dll"))
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;
682 else
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;
693 break;
694 case SettingsModel::AC3Encoder:
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;
706 break;
707 case SettingsModel::FLACEncoder:
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;
715 break;
716 case SettingsModel::PCMEncoder:
718 WaveEncoder *waveEncoder = new WaveEncoder();
719 waveEncoder->setBitrate(m_settings->compressionBitrate());
720 waveEncoder->setRCMode(m_settings->compressionRCMode());
721 encoder = waveEncoder;
723 break;
724 default:
725 throw "Unsupported encoder!";
728 //Create processing thread
729 ProcessThread *thread = new ProcessThread
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())
738 //Add audio filters
739 if(m_settings->forceStereoDownmix())
741 thread->addFilter(new DownmixFilter());
743 if((m_settings->samplingRate() > 0) && !nativeResampling)
745 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.formatAudioSamplerate() || currentFile.formatAudioSamplerate() == 0)
747 thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
750 if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
752 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
754 if(m_settings->normalizationFilterEnabled())
756 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEqualizationMode()));
758 if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
760 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
763 m_threadList.append(thread);
764 m_allJobs.append(thread->getId());
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);
773 //Give it a go!
774 m_runningThreads++;
775 thread->start();
778 void ProcessingDialog::writePlayList(void)
780 if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
782 qWarning("WritePlayList: Nothing to do!");
783 return;
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;
795 //Generate playlist name
796 QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
797 if(!m_metaInfo->fileArtist().isEmpty())
799 playListName = QString("%1 - %2").arg(m_metaInfo->fileArtist(), playListName);
802 //Clean playlist name
803 playListName = lamexp_clean_filename(playListName);
805 //Create list of audio files
806 for(int i = 0; i < m_allJobs.count(); i++)
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")));
812 //Use prefix?
813 for(int i = 0; i < list.count(); i++)
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;
819 if(usePrefix[0] || usePrefix[1] || usePrefix[2])
821 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
824 //Do we need an UTF-8 playlist?
825 for(int i = 0; i < list.count(); i++)
827 if(wcscmp(QWCHAR(QString::fromLatin1(list.at(i).toLatin1().constData())), QWCHAR(list.at(i))))
829 useUtf8 = true;
830 break;
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())
838 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
841 //Now write playlist to output file
842 QFile playList(playListFile);
843 if(playList.open(QIODevice::WriteOnly))
845 if(useUtf8)
847 playList.write("\xef\xbb\xbf");
849 playList.write("#EXTM3U\r\n");
850 while(!list.isEmpty())
852 playList.write(useUtf8 ? list.takeFirst().toUtf8().constData() : list.takeFirst().toLatin1().constData());
853 playList.write("\r\n");
855 playList.close();
857 else
859 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
863 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
865 if(!m_settings->writeMetaTags())
867 return AudioFileModel(audioFile, false);
870 AudioFileModel result = audioFile;
871 result.updateMetaInfo(*m_metaInfo);
873 if(m_metaInfo->filePosition() == UINT_MAX)
875 result.setFilePosition(m_currentFile);
878 return result;
881 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
883 HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
884 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
887 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
889 if(reason == QSystemTrayIcon::DoubleClick)
891 SetForegroundWindow(this->winId());
895 void ProcessingDialog::cpuUsageHasChanged(const double val)
898 this->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
899 UPDATE_MIN_WIDTH(label_cpu);
902 void ProcessingDialog::ramUsageHasChanged(const double val)
905 this->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
906 UPDATE_MIN_WIDTH(label_ram);
909 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
911 int postfix = 0;
912 const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
913 double space = static_cast<double>(val);
915 while((space >= 1000.0) && (postfix < 5))
917 space = space / 1024.0;
918 postfix++;
921 this->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
922 UPDATE_MIN_WIDTH(label_disk);
925 bool ProcessingDialog::shutdownComputer(void)
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..."));
931 qWarning("Initiating shutdown sequence!");
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();
943 QApplication::processEvents();
945 if(m_settings->soundsEnabled())
947 QApplication::setOverrideCursor(Qt::WaitCursor);
948 PlaySound(MAKEINTRESOURCE(IDR_WAVE_SHUTDOWN), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
949 QApplication::restoreOverrideCursor();
952 QTimer timer;
953 timer.setInterval(1000);
954 timer.start();
956 QEventLoop eventLoop(this);
957 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
958 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
960 for(int i = 1; i <= iTimeout; i++)
962 eventLoop.exec();
963 if(progressDialog.wasCanceled())
965 progressDialog.close();
966 return false;
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);
975 progressDialog.close();
976 return true;