Make sampling rate option work with Vorbis encoder.
[LameXP.git] / src / Dialog_Processing.cpp
blobe5a46e895c8f52cb173b8917d6ddf6419588a4fe
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 "Dialog_LogView.h"
31 #include "Encoder_MP3.h"
32 #include "Encoder_Vorbis.h"
33 #include "Encoder_AAC.h"
34 #include "Encoder_FLAC.h"
35 #include "Encoder_Wave.h"
36 #include "WinSevenTaskbar.h"
38 #include <QApplication>
39 #include <QRect>
40 #include <QDesktopWidget>
41 #include <QMovie>
42 #include <QMessageBox>
43 #include <QTimer>
44 #include <QCloseEvent>
45 #include <QDesktopServices>
46 #include <QUrl>
47 #include <QUuid>
48 #include <QFileInfo>
49 #include <QDir>
50 #include <QMenu>
51 #include <QSystemTrayIcon>
53 #include <Windows.h>
55 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
56 { \
57 QPalette palette = WIDGET->palette(); \
58 palette.setColor(QPalette::Background, COLOR); \
59 WIDGET->setPalette(palette); \
62 #define SET_PROGRESS_TEXT(TXT) \
63 { \
64 label_progress->setText(TXT); \
65 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
68 ////////////////////////////////////////////////////////////
69 // Constructor
70 ////////////////////////////////////////////////////////////
72 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
74 QDialog(parent),
75 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
76 m_settings(settings),
77 m_metaInfo(metaInfo)
79 //Init the dialog, from the .ui file
80 setupUi(this);
81 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
83 //Setup version info
84 label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
85 label_versionInfo->installEventFilter(this);
87 //Register meta type
88 qRegisterMetaType<QUuid>("QUuid");
90 //Center window in screen
91 QRect desktopRect = QApplication::desktop()->screenGeometry();
92 QRect thisRect = this->geometry();
93 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
94 setMinimumSize(thisRect.width(), thisRect.height());
96 //Enable buttons
97 connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
99 //Init progress indicator
100 m_progressIndicator = new QMovie(":/images/Working.gif");
101 label_headerWorking->setMovie(m_progressIndicator);
102 progressBar->setValue(0);
104 //Init progress model
105 m_progressModel = new ProgressModel();
106 view_log->setModel(m_progressModel);
107 view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
108 view_log->verticalHeader()->hide();
109 view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
110 view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
111 connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
112 connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
113 connect(view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
115 //Create context menu
116 m_contextMenu = new QMenu();
117 QAction *contextMenuAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
118 view_log->setContextMenuPolicy(Qt::CustomContextMenu);
119 connect(view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
120 connect(contextMenuAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuActionTriggered()));
122 //Enque jobs
123 if(fileListModel)
125 for(int i = 0; i < fileListModel->rowCount(); i++)
127 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
131 //Translate
132 label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
134 //Enable system tray icon
135 connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
137 //Init other vars
138 m_runningThreads = 0;
139 m_currentFile = 0;
140 m_allJobs.clear();
141 m_succeededJobs.clear();
142 m_failedJobs.clear();
143 m_userAborted = false;
146 ////////////////////////////////////////////////////////////
147 // Destructor
148 ////////////////////////////////////////////////////////////
150 ProcessingDialog::~ProcessingDialog(void)
152 view_log->setModel(NULL);
153 if(m_progressIndicator) m_progressIndicator->stop();
154 LAMEXP_DELETE(m_progressIndicator);
155 LAMEXP_DELETE(m_progressModel);
156 LAMEXP_DELETE(m_contextMenu);
157 LAMEXP_DELETE(m_systemTray);
159 WinSevenTaskbar::setOverlayIcon(this, NULL);
160 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
162 while(!m_threadList.isEmpty())
164 ProcessThread *thread = m_threadList.takeFirst();
165 thread->terminate();
166 thread->wait(15000);
167 delete thread;
171 ////////////////////////////////////////////////////////////
172 // EVENTS
173 ////////////////////////////////////////////////////////////
175 void ProcessingDialog::showEvent(QShowEvent *event)
177 setCloseButtonEnabled(false);
178 button_closeDialog->setEnabled(false);
179 button_AbortProcess->setEnabled(false);
180 m_systemTray->setVisible(true);
182 if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
184 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
187 QTimer::singleShot(1000, this, SLOT(initEncoding()));
190 void ProcessingDialog::closeEvent(QCloseEvent *event)
192 if(!button_closeDialog->isEnabled())
194 event->ignore();
196 else
198 m_systemTray->setVisible(false);
202 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
204 static QColor defaultColor = QColor();
206 if(obj == label_versionInfo)
208 if(event->type() == QEvent::Enter)
210 QPalette palette = label_versionInfo->palette();
211 defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
212 palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
213 label_versionInfo->setPalette(palette);
215 else if(event->type() == QEvent::Leave)
217 QPalette palette = label_versionInfo->palette();
218 palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
219 label_versionInfo->setPalette(palette);
221 else if(event->type() == QEvent::MouseButtonPress)
223 QUrl url("http://mulder.dummwiedeutsch.de/");
224 QDesktopServices::openUrl(url);
228 return false;
231 ////////////////////////////////////////////////////////////
232 // SLOTS
233 ////////////////////////////////////////////////////////////
235 void ProcessingDialog::initEncoding(void)
237 m_runningThreads = 0;
238 m_currentFile = 0;
239 m_allJobs.clear();
240 m_succeededJobs.clear();
241 m_failedJobs.clear();
242 m_userAborted = false;
243 m_playList.clear();
245 CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
246 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
247 m_progressIndicator->start();
249 button_closeDialog->setEnabled(false);
250 button_AbortProcess->setEnabled(true);
251 progressBar->setRange(0, m_pendingJobs.count());
253 WinSevenTaskbar::initTaskbar();
254 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
255 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
256 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
258 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
260 for(int i = 0; i < min(max(cpuFeatures.count, 1), 4); i++)
262 startNextJob();
266 void ProcessingDialog::abortEncoding(void)
268 m_userAborted = true;
269 button_AbortProcess->setEnabled(false);
271 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
273 for(int i = 0; i < m_threadList.count(); i++)
275 m_threadList.at(i)->abort();
279 void ProcessingDialog::doneEncoding(void)
281 m_runningThreads--;
282 progressBar->setValue(progressBar->value() + 1);
284 if(!m_userAborted)
286 SET_PROGRESS_TEXT(tr("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
287 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
290 int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
291 if(index >= 0)
293 m_threadList.takeAt(index)->deleteLater();
296 if(!m_pendingJobs.isEmpty() && !m_userAborted)
298 startNextJob();
299 qDebug("Running jobs: %u", m_runningThreads);
300 return;
303 if(m_runningThreads > 0)
305 qDebug("Running jobs: %u", m_runningThreads);
306 return;
309 QApplication::setOverrideCursor(Qt::WaitCursor);
310 qDebug("Running jobs: %u", m_runningThreads);
312 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
314 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
315 QApplication::processEvents();
316 writePlayList();
319 if(m_userAborted)
321 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFF3BA"));
322 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
323 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
324 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!"));
325 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
326 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
327 QApplication::processEvents();
328 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
330 else
332 if(m_failedJobs.count() > 0)
334 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFBABA"));
335 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
336 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
337 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())));
338 m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
339 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
340 QApplication::processEvents();
341 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
343 else
345 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#E0FFE2"));
346 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
347 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
348 SET_PROGRESS_TEXT(tr("Alle files completed successfully."));
349 m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
350 m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
351 QApplication::processEvents();
352 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
356 setCloseButtonEnabled(true);
357 button_closeDialog->setEnabled(true);
358 button_AbortProcess->setEnabled(false);
360 view_log->scrollToBottom();
361 m_progressIndicator->stop();
362 progressBar->setValue(progressBar->maximum());
363 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
365 QApplication::restoreOverrideCursor();
368 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
370 if(success)
372 m_playList.insert(jobId, outFileName);
373 m_succeededJobs.append(jobId);
375 else
377 m_failedJobs.append(jobId);
381 void ProcessingDialog::progressModelChanged(void)
383 view_log->scrollToBottom();
386 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
388 if(m_runningThreads == 0)
390 const QStringList &logFile = m_progressModel->getLogFile(index);
391 LogViewDialog *logView = new LogViewDialog(this);
392 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
393 logView->exec(logFile);
394 LAMEXP_DELETE(logView);
396 else
398 MessageBeep(MB_ICONWARNING);
402 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
404 if(pos.x() <= view_log->width() && pos.y() <= view_log->height() && pos.x() >= 0 && pos.y() >= 0)
406 m_contextMenu->popup(view_log->mapToGlobal(pos));
410 void ProcessingDialog::contextMenuActionTriggered(void)
412 QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
413 logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
416 ////////////////////////////////////////////////////////////
417 // Private Functions
418 ////////////////////////////////////////////////////////////
420 void ProcessingDialog::startNextJob(void)
422 if(m_pendingJobs.isEmpty())
424 return;
427 m_currentFile++;
428 AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
429 AbstractEncoder *encoder = NULL;
431 switch(m_settings->compressionEncoder())
433 case SettingsModel::MP3Encoder:
435 MP3Encoder *mp3Encoder = new MP3Encoder();
436 mp3Encoder->setBitrate(m_settings->compressionBitrate());
437 mp3Encoder->setRCMode(m_settings->compressionRCMode());
438 mp3Encoder->setAlgoQuality(m_settings->lameAlgoQuality());
439 if(m_settings->bitrateManagementEnabled())
441 mp3Encoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
443 mp3Encoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
444 mp3Encoder->setChannelMode(m_settings->lameChannelMode());
445 encoder = mp3Encoder;
447 break;
448 case SettingsModel::VorbisEncoder:
450 VorbisEncoder *vorbisEncoder = new VorbisEncoder();
451 vorbisEncoder->setBitrate(m_settings->compressionBitrate());
452 vorbisEncoder->setRCMode(m_settings->compressionRCMode());
453 if(m_settings->bitrateManagementEnabled())
455 vorbisEncoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
457 vorbisEncoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
458 encoder = vorbisEncoder;
460 break;
461 case SettingsModel::AACEncoder:
463 AACEncoder *aacEncoder = new AACEncoder();
464 aacEncoder->setBitrate(m_settings->compressionBitrate());
465 aacEncoder->setRCMode(m_settings->compressionRCMode());
466 aacEncoder->setEnable2Pass(m_settings->neroAACEnable2Pass());
467 aacEncoder->setProfile(m_settings->neroAACProfile());
468 encoder = aacEncoder;
470 break;
471 case SettingsModel::FLACEncoder:
473 FLACEncoder *flacEncoder = new FLACEncoder();
474 flacEncoder->setBitrate(m_settings->compressionBitrate());
475 flacEncoder->setRCMode(m_settings->compressionRCMode());
476 encoder = flacEncoder;
478 break;
479 case SettingsModel::PCMEncoder:
481 WaveEncoder *waveEncoder = new WaveEncoder();
482 waveEncoder->setBitrate(m_settings->compressionBitrate());
483 waveEncoder->setRCMode(m_settings->compressionRCMode());
484 encoder = waveEncoder;
486 break;
487 default:
488 throw "Unsupported encoder!";
491 ProcessThread *thread = new ProcessThread
493 currentFile,
494 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath(): m_settings->outputDir()),
495 encoder,
496 m_settings->prependRelativeSourcePath()
499 m_threadList.append(thread);
500 m_allJobs.append(thread->getId());
502 connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
503 connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
504 connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
505 connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
506 connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
508 m_runningThreads++;
509 thread->start();
512 void ProcessingDialog::writePlayList(void)
514 if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
516 qWarning("WritePlayList: Nothing to do!");
517 return;
520 QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
522 const static char *invalidChars = "\\/:*?\"<>|";
523 for(int i = 0; invalidChars[i]; i++)
525 playListName.replace(invalidChars[i], ' ');
526 playListName = playListName.simplified();
529 QString playListFile = QString("%1/%2.m3u").arg(m_settings->outputDir(), playListName);
531 int counter = 1;
532 while(QFileInfo(playListFile).exists())
534 playListFile = QString("%1/%2 (%3).m3u").arg(m_settings->outputDir(), playListName, QString::number(++counter));
537 QFile playList(playListFile);
538 if(playList.open(QIODevice::WriteOnly))
540 playList.write("#EXTM3U\r\n");
541 for(int i = 0; i < m_allJobs.count(); i++)
544 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
545 playList.write(QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A"))).toUtf8().constData());
546 playList.write("\r\n");
548 playList.close();
550 else
552 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
556 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
558 if(!m_settings->writeMetaTags())
560 return AudioFileModel(audioFile.filePath());
563 AudioFileModel result = audioFile;
565 if(!m_metaInfo->fileArtist().isEmpty()) result.setFileArtist(m_metaInfo->fileArtist());
566 if(!m_metaInfo->fileAlbum().isEmpty()) result.setFileAlbum(m_metaInfo->fileAlbum());
567 if(!m_metaInfo->fileGenre().isEmpty()) result.setFileGenre(m_metaInfo->fileGenre());
568 if(m_metaInfo->fileYear()) result.setFileYear(m_metaInfo->fileYear());
569 if(m_metaInfo->filePosition() == UINT_MAX) result.setFilePosition(m_currentFile);
570 if(!m_metaInfo->fileComment().isEmpty()) result.setFileComment(m_metaInfo->fileComment());
572 return result;
575 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
577 HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
578 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
581 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
583 if(reason == QSystemTrayIcon::DoubleClick)
585 SetForegroundWindow(this->winId());