Updated avs2wav tool.
[LameXP.git] / src / Dialog_Processing.cpp
blob9ef71cd05b6df66ff8771b8bfb1a72eb95f11cd3
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_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_Normalize.h"
39 #include "Filter_Resample.h"
40 #include "Filter_ToneAdjust.h"
41 #include "WinSevenTaskbar.h"
43 #include <QApplication>
44 #include <QRect>
45 #include <QDesktopWidget>
46 #include <QMovie>
47 #include <QMessageBox>
48 #include <QTimer>
49 #include <QCloseEvent>
50 #include <QDesktopServices>
51 #include <QUrl>
52 #include <QUuid>
53 #include <QFileInfo>
54 #include <QDir>
55 #include <QMenu>
56 #include <QSystemTrayIcon>
57 #include <QProcess>
58 #include <QProgressDialog>
60 #include <MMSystem.h>
62 ////////////////////////////////////////////////////////////
64 //Maximum number of parallel instances
65 #define MAX_INSTANCES 16
67 //Maximum number of CPU cores for auto-detection
68 #define MAX_CPU_COUNT 4
70 ////////////////////////////////////////////////////////////
72 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
73 { \
74 QPalette palette = WIDGET->palette(); \
75 palette.setColor(QPalette::Background, COLOR); \
76 WIDGET->setPalette(palette); \
79 #define SET_PROGRESS_TEXT(TXT) \
80 { \
81 label_progress->setText(TXT); \
82 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
85 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
87 ////////////////////////////////////////////////////////////
88 // Constructor
89 ////////////////////////////////////////////////////////////
91 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
93 QDialog(parent),
94 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
95 m_settings(settings),
96 m_metaInfo(metaInfo),
97 m_shutdownFlag(false),
98 m_diskObserver(NULL)
100 //Init the dialog, from the .ui file
101 setupUi(this);
102 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
104 //Setup version info
105 label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
106 label_versionInfo->installEventFilter(this);
108 //Register meta type
109 qRegisterMetaType<QUuid>("QUuid");
111 //Center window in screen
112 QRect desktopRect = QApplication::desktop()->screenGeometry();
113 QRect thisRect = this->geometry();
114 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
115 setMinimumSize(thisRect.width(), thisRect.height());
117 //Enable buttons
118 connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
120 //Init progress indicator
121 m_progressIndicator = new QMovie(":/images/Working.gif");
122 label_headerWorking->setMovie(m_progressIndicator);
123 progressBar->setValue(0);
125 //Init progress model
126 m_progressModel = new ProgressModel();
127 view_log->setModel(m_progressModel);
128 view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
129 view_log->verticalHeader()->hide();
130 view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
131 view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
132 connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
133 connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
134 connect(view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
136 //Create context menu
137 m_contextMenu = new QMenu();
138 QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
139 QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
141 view_log->setContextMenuPolicy(Qt::CustomContextMenu);
142 connect(view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
143 connect(contextMenuDetailsAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
144 connect(contextMenuShowFileAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
145 SET_FONT_BOLD(contextMenuDetailsAction, true);
147 //Enque jobs
148 if(fileListModel)
150 for(int i = 0; i < fileListModel->rowCount(); i++)
152 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
156 //Translate
157 label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
159 //Enable system tray icon
160 connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
162 //Init other vars
163 m_runningThreads = 0;
164 m_currentFile = 0;
165 m_allJobs.clear();
166 m_succeededJobs.clear();
167 m_failedJobs.clear();
168 m_userAborted = false;
171 ////////////////////////////////////////////////////////////
172 // Destructor
173 ////////////////////////////////////////////////////////////
175 ProcessingDialog::~ProcessingDialog(void)
177 view_log->setModel(NULL);
179 if(m_progressIndicator)
181 m_progressIndicator->stop();
184 if(m_diskObserver)
186 m_diskObserver->stop();
187 m_diskObserver->wait(15000);
190 LAMEXP_DELETE(m_progressIndicator);
191 LAMEXP_DELETE(m_progressModel);
192 LAMEXP_DELETE(m_contextMenu);
193 LAMEXP_DELETE(m_systemTray);
194 LAMEXP_DELETE(m_diskObserver);
196 WinSevenTaskbar::setOverlayIcon(this, NULL);
197 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
199 while(!m_threadList.isEmpty())
201 ProcessThread *thread = m_threadList.takeFirst();
202 thread->terminate();
203 thread->wait(15000);
204 delete thread;
208 ////////////////////////////////////////////////////////////
209 // EVENTS
210 ////////////////////////////////////////////////////////////
212 void ProcessingDialog::showEvent(QShowEvent *event)
214 setCloseButtonEnabled(false);
215 button_closeDialog->setEnabled(false);
216 button_AbortProcess->setEnabled(false);
217 m_systemTray->setVisible(true);
219 if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
221 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
224 QTimer::singleShot(1000, this, SLOT(initEncoding()));
227 void ProcessingDialog::closeEvent(QCloseEvent *event)
229 if(!button_closeDialog->isEnabled())
231 event->ignore();
233 else
235 m_systemTray->setVisible(false);
239 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
241 static QColor defaultColor = QColor();
243 if(obj == label_versionInfo)
245 if(event->type() == QEvent::Enter)
247 QPalette palette = label_versionInfo->palette();
248 defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
249 palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
250 label_versionInfo->setPalette(palette);
252 else if(event->type() == QEvent::Leave)
254 QPalette palette = label_versionInfo->palette();
255 palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
256 label_versionInfo->setPalette(palette);
258 else if(event->type() == QEvent::MouseButtonPress)
260 QUrl url(lamexp_website_url());
261 QDesktopServices::openUrl(url);
265 return false;
268 ////////////////////////////////////////////////////////////
269 // SLOTS
270 ////////////////////////////////////////////////////////////
272 void ProcessingDialog::initEncoding(void)
274 m_runningThreads = 0;
275 m_currentFile = 0;
276 m_allJobs.clear();
277 m_succeededJobs.clear();
278 m_failedJobs.clear();
279 m_userAborted = false;
280 m_playList.clear();
282 CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
283 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
284 m_progressIndicator->start();
286 button_closeDialog->setEnabled(false);
287 button_AbortProcess->setEnabled(true);
288 progressBar->setRange(0, m_pendingJobs.count());
289 checkBox_shutdownComputer->setEnabled(true);
290 checkBox_shutdownComputer->setChecked(false);
292 WinSevenTaskbar::initTaskbar();
293 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
294 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
295 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
297 if(!m_diskObserver)
299 m_diskObserver = new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2());
300 connect(m_diskObserver, SIGNAL(messageLogged(QString,bool)), m_progressModel, SLOT(addSystemMessage(QString,bool)), Qt::QueuedConnection);
301 m_diskObserver->start();
304 int maximumInstances = max(min(m_settings->maximumInstances(), MAX_INSTANCES), 0);
305 if(maximumInstances < 1)
307 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
308 maximumInstances = max(min(cpuFeatures.count, MAX_CPU_COUNT), 1);
311 int parallelThreadCount = max(min(maximumInstances, m_pendingJobs.count()), 1);
312 if(parallelThreadCount > 1)
314 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(parallelThreadCount)));
317 for(int i = 0; i < parallelThreadCount; i++)
319 startNextJob();
323 void ProcessingDialog::abortEncoding(void)
325 m_userAborted = true;
326 button_AbortProcess->setEnabled(false);
328 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
330 for(int i = 0; i < m_threadList.count(); i++)
332 m_threadList.at(i)->abort();
336 void ProcessingDialog::doneEncoding(void)
338 m_runningThreads--;
339 progressBar->setValue(progressBar->value() + 1);
341 if(!m_userAborted)
343 SET_PROGRESS_TEXT(tr("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
344 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
347 int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
348 if(index >= 0)
350 m_threadList.takeAt(index)->deleteLater();
353 if(!m_pendingJobs.isEmpty() && !m_userAborted)
355 startNextJob();
356 qDebug("Running jobs: %u", m_runningThreads);
357 return;
360 if(m_runningThreads > 0)
362 qDebug("Running jobs: %u", m_runningThreads);
363 return;
366 QApplication::setOverrideCursor(Qt::WaitCursor);
367 qDebug("Running jobs: %u", m_runningThreads);
369 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
371 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
372 QApplication::processEvents();
373 writePlayList();
376 if(m_userAborted)
378 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFF3BA"));
379 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
380 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
381 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!"));
382 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
383 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
384 QApplication::processEvents();
385 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
387 else
389 if(m_failedJobs.count() > 0)
391 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFBABA"));
392 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
393 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
394 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())));
395 m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
396 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
397 QApplication::processEvents();
398 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
400 else
402 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#E0FFE2"));
403 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
404 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
405 SET_PROGRESS_TEXT(tr("All files completed successfully."));
406 m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
407 m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
408 QApplication::processEvents();
409 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
413 setCloseButtonEnabled(true);
414 button_closeDialog->setEnabled(true);
415 button_AbortProcess->setEnabled(false);
416 checkBox_shutdownComputer->setEnabled(false);
418 view_log->scrollToBottom();
419 m_progressIndicator->stop();
420 progressBar->setValue(progressBar->maximum());
421 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
423 QApplication::restoreOverrideCursor();
425 if(!m_userAborted && checkBox_shutdownComputer->isChecked())
427 if(shutdownComputer())
429 m_shutdownFlag = true;
430 accept();
435 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
437 if(success)
439 m_playList.insert(jobId, outFileName);
440 m_succeededJobs.append(jobId);
442 else
444 m_failedJobs.append(jobId);
448 void ProcessingDialog::progressModelChanged(void)
450 view_log->scrollToBottom();
453 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
455 if(m_runningThreads == 0)
457 const QStringList &logFile = m_progressModel->getLogFile(index);
459 if(!logFile.isEmpty())
461 LogViewDialog *logView = new LogViewDialog(this);
462 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
463 logView->exec(logFile);
464 LAMEXP_DELETE(logView);
466 else
468 MessageBeep(MB_ICONWARNING);
471 else
473 MessageBeep(MB_ICONWARNING);
477 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
479 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
480 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
482 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
484 m_contextMenu->popup(sender->mapToGlobal(pos));
488 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
490 QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
491 logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
494 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
496 QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
497 const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : view_log->currentIndex());
498 QString filePath = m_playList.value(jobId, QString());
500 if(filePath.isEmpty())
502 MessageBeep(MB_ICONWARNING);
503 return;
506 if(QFileInfo(filePath).exists())
508 QString systemRootPath;
510 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
511 if(systemRoot.exists() && systemRoot.cdUp())
513 systemRootPath = systemRoot.canonicalPath();
516 if(!systemRootPath.isEmpty())
518 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
519 if(explorer.exists() && explorer.isFile())
521 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
522 return;
525 else
527 qWarning("SystemRoot directory could not be detected!");
530 else
532 qWarning("File not found: %s", filePath.toLatin1().constData());
533 MessageBeep(MB_ICONERROR);
537 ////////////////////////////////////////////////////////////
538 // Private Functions
539 ////////////////////////////////////////////////////////////
541 void ProcessingDialog::startNextJob(void)
543 if(m_pendingJobs.isEmpty())
545 return;
548 m_currentFile++;
549 AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
550 AbstractEncoder *encoder = NULL;
551 bool nativeResampling = false;
553 switch(m_settings->compressionEncoder())
555 case SettingsModel::MP3Encoder:
557 MP3Encoder *mp3Encoder = new MP3Encoder();
558 mp3Encoder->setBitrate(m_settings->compressionBitrate());
559 mp3Encoder->setRCMode(m_settings->compressionRCMode());
560 mp3Encoder->setAlgoQuality(m_settings->lameAlgoQuality());
561 if(m_settings->bitrateManagementEnabled())
563 mp3Encoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
565 if(m_settings->samplingRate() > 0)
567 mp3Encoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
568 nativeResampling = true;
570 mp3Encoder->setChannelMode(m_settings->lameChannelMode());
571 mp3Encoder->setCustomParams(m_settings->customParametersLAME());
572 encoder = mp3Encoder;
574 break;
575 case SettingsModel::VorbisEncoder:
577 VorbisEncoder *vorbisEncoder = new VorbisEncoder();
578 vorbisEncoder->setBitrate(m_settings->compressionBitrate());
579 vorbisEncoder->setRCMode(m_settings->compressionRCMode());
580 if(m_settings->bitrateManagementEnabled())
582 vorbisEncoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
584 if(m_settings->samplingRate() > 0)
586 vorbisEncoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
587 nativeResampling = true;
589 vorbisEncoder->setCustomParams(m_settings->customParametersOggEnc());
590 encoder = vorbisEncoder;
592 break;
593 case SettingsModel::AACEncoder:
595 AACEncoder *aacEncoder = new AACEncoder();
596 aacEncoder->setBitrate(m_settings->compressionBitrate());
597 aacEncoder->setRCMode(m_settings->compressionRCMode());
598 aacEncoder->setEnable2Pass(m_settings->neroAACEnable2Pass());
599 aacEncoder->setProfile(m_settings->neroAACProfile());
600 aacEncoder->setCustomParams(m_settings->customParametersNeroAAC());
601 encoder = aacEncoder;
603 break;
604 case SettingsModel::AC3Encoder:
606 AC3Encoder *ac3Encoder = new AC3Encoder();
607 ac3Encoder->setBitrate(m_settings->compressionBitrate());
608 ac3Encoder->setRCMode(m_settings->compressionRCMode());
609 ac3Encoder->setCustomParams(m_settings->customParametersAften());
610 ac3Encoder->setAudioCodingMode(m_settings->aftenAudioCodingMode());
611 ac3Encoder->setDynamicRangeCompression(m_settings->aftenDynamicRangeCompression());
612 ac3Encoder->setExponentSearchSize(m_settings->aftenExponentSearchSize());
613 ac3Encoder->setFastBitAllocation(m_settings->aftenFastBitAllocation());
614 encoder = ac3Encoder;
616 break;
617 case SettingsModel::FLACEncoder:
619 FLACEncoder *flacEncoder = new FLACEncoder();
620 flacEncoder->setBitrate(m_settings->compressionBitrate());
621 flacEncoder->setRCMode(m_settings->compressionRCMode());
622 flacEncoder->setCustomParams(m_settings->customParametersFLAC());
623 encoder = flacEncoder;
625 break;
626 case SettingsModel::PCMEncoder:
628 WaveEncoder *waveEncoder = new WaveEncoder();
629 waveEncoder->setBitrate(m_settings->compressionBitrate());
630 waveEncoder->setRCMode(m_settings->compressionRCMode());
631 encoder = waveEncoder;
633 break;
634 default:
635 throw "Unsupported encoder!";
638 ProcessThread *thread = new ProcessThread
640 currentFile,
641 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
642 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2()),
643 encoder,
644 m_settings->prependRelativeSourcePath()
647 if((m_settings->samplingRate() > 0) && !nativeResampling)
649 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.formatAudioSamplerate() || currentFile.formatAudioSamplerate() == 0)
651 thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
654 if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
656 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
658 if(m_settings->normalizationFilterEnabled())
660 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume()));
663 m_threadList.append(thread);
664 m_allJobs.append(thread->getId());
666 connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
667 connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
668 connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
669 connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
670 connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
672 m_runningThreads++;
673 thread->start();
676 void ProcessingDialog::writePlayList(void)
678 if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
680 qWarning("WritePlayList: Nothing to do!");
681 return;
684 QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
686 const static char *invalidChars = "\\/:*?\"<>|";
687 for(int i = 0; invalidChars[i]; i++)
689 playListName.replace(invalidChars[i], ' ');
690 playListName = playListName.simplified();
693 QString playListFile = QString("%1/%2.m3u").arg(m_settings->outputDir(), playListName);
695 int counter = 1;
696 while(QFileInfo(playListFile).exists())
698 playListFile = QString("%1/%2 (%3).m3u").arg(m_settings->outputDir(), playListName, QString::number(++counter));
701 QFile playList(playListFile);
702 if(playList.open(QIODevice::WriteOnly))
704 playList.write("#EXTM3U\r\n");
705 for(int i = 0; i < m_allJobs.count(); i++)
708 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
709 playList.write(QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A"))).toUtf8().constData());
710 playList.write("\r\n");
712 playList.close();
714 else
716 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
720 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
722 if(!m_settings->writeMetaTags())
724 return AudioFileModel(audioFile, false);
727 AudioFileModel result = audioFile;
728 result.updateMetaInfo(*m_metaInfo);
730 if(m_metaInfo->filePosition() == UINT_MAX)
732 result.setFilePosition(m_currentFile);
735 return result;
738 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
740 HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
741 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
744 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
746 if(reason == QSystemTrayIcon::DoubleClick)
748 SetForegroundWindow(this->winId());
752 bool ProcessingDialog::shutdownComputer(void)
754 const int iTimeout = 30;
755 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
756 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
758 qWarning("Initiating shutdown sequence!");
760 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
761 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
762 cancelButton->setIcon(QIcon(":/icons/power_on.png"));
763 progressDialog.setModal(true);
764 progressDialog.setAutoClose(false);
765 progressDialog.setAutoReset(false);
766 progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
767 progressDialog.setCancelButton(cancelButton);
768 progressDialog.show();
770 QApplication::processEvents();
772 if(m_settings->soundsEnabled())
774 QApplication::setOverrideCursor(Qt::WaitCursor);
775 PlaySound(MAKEINTRESOURCE(IDR_WAVE_SHUTDOWN), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
776 QApplication::restoreOverrideCursor();
779 QTimer timer;
780 timer.setInterval(1000);
781 timer.start();
783 QEventLoop eventLoop(this);
784 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
785 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
787 for(int i = 1; i <= iTimeout; i++)
789 eventLoop.exec();
790 if(progressDialog.wasCanceled())
792 progressDialog.close();
793 return false;
795 progressDialog.setValue(i+1);
796 progressDialog.setLabelText(text.arg(iTimeout-i));
797 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
798 QApplication::processEvents();
799 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE_BEEP : IDR_WAVE_BEEP_LONG), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
802 progressDialog.close();
803 return true;