1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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"
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 "Filter_Normalize.h"
37 #include "Filter_Resample.h"
38 #include "Filter_ToneAdjust.h"
39 #include "WinSevenTaskbar.h"
41 #include <QApplication>
43 #include <QDesktopWidget>
45 #include <QMessageBox>
47 #include <QCloseEvent>
48 #include <QDesktopServices>
54 #include <QSystemTrayIcon>
58 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
60 QPalette palette = WIDGET->palette(); \
61 palette.setColor(QPalette::Background, COLOR); \
62 WIDGET->setPalette(palette); \
65 #define SET_PROGRESS_TEXT(TXT) \
67 label_progress->setText(TXT); \
68 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
71 ////////////////////////////////////////////////////////////
73 ////////////////////////////////////////////////////////////
75 ProcessingDialog::ProcessingDialog(FileListModel
*fileListModel
, AudioFileModel
*metaInfo
, SettingsModel
*settings
, QWidget
*parent
)
78 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
82 //Init the dialog, from the .ui file
84 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint
);
87 label_versionInfo
->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
88 label_versionInfo
->installEventFilter(this);
91 qRegisterMetaType
<QUuid
>("QUuid");
93 //Center window in screen
94 QRect desktopRect
= QApplication::desktop()->screenGeometry();
95 QRect thisRect
= this->geometry();
96 move((desktopRect
.width() - thisRect
.width()) / 2, (desktopRect
.height() - thisRect
.height()) / 2);
97 setMinimumSize(thisRect
.width(), thisRect
.height());
100 connect(button_AbortProcess
, SIGNAL(clicked()), this, SLOT(abortEncoding()));
102 //Init progress indicator
103 m_progressIndicator
= new QMovie(":/images/Working.gif");
104 label_headerWorking
->setMovie(m_progressIndicator
);
105 progressBar
->setValue(0);
107 //Init progress model
108 m_progressModel
= new ProgressModel();
109 view_log
->setModel(m_progressModel
);
110 view_log
->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
111 view_log
->verticalHeader()->hide();
112 view_log
->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
113 view_log
->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch
);
114 connect(m_progressModel
, SIGNAL(rowsInserted(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
115 connect(m_progressModel
, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
116 connect(view_log
, SIGNAL(activated(QModelIndex
)), this, SLOT(logViewDoubleClicked(QModelIndex
)));
118 //Create context menu
119 m_contextMenu
= new QMenu();
120 QAction
*contextMenuAction
= m_contextMenu
->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
121 view_log
->setContextMenuPolicy(Qt::CustomContextMenu
);
122 connect(view_log
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
123 connect(contextMenuAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuActionTriggered()));
128 for(int i
= 0; i
< fileListModel
->rowCount(); i
++)
130 m_pendingJobs
.append(fileListModel
->getFile(fileListModel
->index(i
,0)));
135 label_headerStatus
->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
137 //Enable system tray icon
138 connect(m_systemTray
, SIGNAL(activated(QSystemTrayIcon::ActivationReason
)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason
)));
141 m_runningThreads
= 0;
144 m_succeededJobs
.clear();
145 m_failedJobs
.clear();
146 m_userAborted
= false;
149 ////////////////////////////////////////////////////////////
151 ////////////////////////////////////////////////////////////
153 ProcessingDialog::~ProcessingDialog(void)
155 view_log
->setModel(NULL
);
156 if(m_progressIndicator
) m_progressIndicator
->stop();
157 LAMEXP_DELETE(m_progressIndicator
);
158 LAMEXP_DELETE(m_progressModel
);
159 LAMEXP_DELETE(m_contextMenu
);
160 LAMEXP_DELETE(m_systemTray
);
162 WinSevenTaskbar::setOverlayIcon(this, NULL
);
163 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState
);
165 while(!m_threadList
.isEmpty())
167 ProcessThread
*thread
= m_threadList
.takeFirst();
174 ////////////////////////////////////////////////////////////
176 ////////////////////////////////////////////////////////////
178 void ProcessingDialog::showEvent(QShowEvent
*event
)
180 setCloseButtonEnabled(false);
181 button_closeDialog
->setEnabled(false);
182 button_AbortProcess
->setEnabled(false);
183 m_systemTray
->setVisible(true);
185 if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS
))
187 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
);
190 QTimer::singleShot(1000, this, SLOT(initEncoding()));
193 void ProcessingDialog::closeEvent(QCloseEvent
*event
)
195 if(!button_closeDialog
->isEnabled())
201 m_systemTray
->setVisible(false);
205 bool ProcessingDialog::eventFilter(QObject
*obj
, QEvent
*event
)
207 static QColor defaultColor
= QColor();
209 if(obj
== label_versionInfo
)
211 if(event
->type() == QEvent::Enter
)
213 QPalette palette
= label_versionInfo
->palette();
214 defaultColor
= palette
.color(QPalette::Normal
, QPalette::WindowText
);
215 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, Qt::red
);
216 label_versionInfo
->setPalette(palette
);
218 else if(event
->type() == QEvent::Leave
)
220 QPalette palette
= label_versionInfo
->palette();
221 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, defaultColor
);
222 label_versionInfo
->setPalette(palette
);
224 else if(event
->type() == QEvent::MouseButtonPress
)
226 QUrl
url("http://mulder.dummwiedeutsch.de/");
227 QDesktopServices::openUrl(url
);
234 ////////////////////////////////////////////////////////////
236 ////////////////////////////////////////////////////////////
238 void ProcessingDialog::initEncoding(void)
240 m_runningThreads
= 0;
243 m_succeededJobs
.clear();
244 m_failedJobs
.clear();
245 m_userAborted
= false;
248 CHANGE_BACKGROUND_COLOR(frame_header
, QColor(Qt::white
));
249 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
250 m_progressIndicator
->start();
252 button_closeDialog
->setEnabled(false);
253 button_AbortProcess
->setEnabled(true);
254 progressBar
->setRange(0, m_pendingJobs
.count());
256 WinSevenTaskbar::initTaskbar();
257 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState
);
258 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs
.count());
259 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
261 lamexp_cpu_t cpuFeatures
= lamexp_detect_cpu_features();
262 int parallelThreadCount
= max(min(min(cpuFeatures
.count
, m_pendingJobs
.count()), 4), 1);
264 if(parallelThreadCount
> 1)
266 m_progressModel
->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(parallelThreadCount
)));
269 for(int i
= 0; i
< parallelThreadCount
; i
++)
275 void ProcessingDialog::abortEncoding(void)
277 m_userAborted
= true;
278 button_AbortProcess
->setEnabled(false);
280 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
282 for(int i
= 0; i
< m_threadList
.count(); i
++)
284 m_threadList
.at(i
)->abort();
288 void ProcessingDialog::doneEncoding(void)
291 progressBar
->setValue(progressBar
->value() + 1);
295 SET_PROGRESS_TEXT(tr("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar
->value()), QString::number(progressBar
->maximum())));
296 WinSevenTaskbar::setTaskbarProgress(this, progressBar
->value(), progressBar
->maximum());
299 int index
= m_threadList
.indexOf(dynamic_cast<ProcessThread
*>(QWidget::sender()));
302 m_threadList
.takeAt(index
)->deleteLater();
305 if(!m_pendingJobs
.isEmpty() && !m_userAborted
)
308 qDebug("Running jobs: %u", m_runningThreads
);
312 if(m_runningThreads
> 0)
314 qDebug("Running jobs: %u", m_runningThreads
);
318 QApplication::setOverrideCursor(Qt::WaitCursor
);
319 qDebug("Running jobs: %u", m_runningThreads
);
321 if(!m_userAborted
&& m_settings
->createPlaylist() && !m_settings
->outputToSourceDir())
323 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
324 QApplication::processEvents();
330 CHANGE_BACKGROUND_COLOR(frame_header
, QColor("#FFF3BA"));
331 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState
);
332 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
333 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!"));
334 m_systemTray
->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning
);
335 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
336 QApplication::processEvents();
337 if(m_settings
->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
341 if(m_failedJobs
.count() > 0)
343 CHANGE_BACKGROUND_COLOR(frame_header
, QColor("#FFBABA"));
344 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState
);
345 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
346 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())));
347 m_systemTray
->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical
);
348 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
349 QApplication::processEvents();
350 if(m_settings
->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
354 CHANGE_BACKGROUND_COLOR(frame_header
, QColor("#E0FFE2"));
355 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState
);
356 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
357 SET_PROGRESS_TEXT(tr("Alle files completed successfully."));
358 m_systemTray
->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information
);
359 m_systemTray
->setIcon(QIcon(":/icons/cd_add.png"));
360 QApplication::processEvents();
361 if(m_settings
->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
365 setCloseButtonEnabled(true);
366 button_closeDialog
->setEnabled(true);
367 button_AbortProcess
->setEnabled(false);
369 view_log
->scrollToBottom();
370 m_progressIndicator
->stop();
371 progressBar
->setValue(progressBar
->maximum());
372 WinSevenTaskbar::setTaskbarProgress(this, progressBar
->value(), progressBar
->maximum());
374 QApplication::restoreOverrideCursor();
377 void ProcessingDialog::processFinished(const QUuid
&jobId
, const QString
&outFileName
, bool success
)
381 m_playList
.insert(jobId
, outFileName
);
382 m_succeededJobs
.append(jobId
);
386 m_failedJobs
.append(jobId
);
390 void ProcessingDialog::progressModelChanged(void)
392 view_log
->scrollToBottom();
395 void ProcessingDialog::logViewDoubleClicked(const QModelIndex
&index
)
397 if(m_runningThreads
== 0)
399 const QStringList
&logFile
= m_progressModel
->getLogFile(index
);
401 if(!logFile
.isEmpty())
403 LogViewDialog
*logView
= new LogViewDialog(this);
404 logView
->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel
->data(index
, Qt::DisplayRole
).toString()));
405 logView
->exec(logFile
);
406 LAMEXP_DELETE(logView
);
410 MessageBeep(MB_ICONWARNING
);
415 MessageBeep(MB_ICONWARNING
);
419 void ProcessingDialog::contextMenuTriggered(const QPoint
&pos
)
421 if(pos
.x() <= view_log
->width() && pos
.y() <= view_log
->height() && pos
.x() >= 0 && pos
.y() >= 0)
423 m_contextMenu
->popup(view_log
->mapToGlobal(pos
));
427 void ProcessingDialog::contextMenuActionTriggered(void)
429 QModelIndex index
= view_log
->indexAt(view_log
->mapFromGlobal(m_contextMenu
->pos()));
430 logViewDoubleClicked(index
.isValid() ? index
: view_log
->currentIndex());
433 ////////////////////////////////////////////////////////////
435 ////////////////////////////////////////////////////////////
437 void ProcessingDialog::startNextJob(void)
439 if(m_pendingJobs
.isEmpty())
445 AudioFileModel currentFile
= updateMetaInfo(m_pendingJobs
.takeFirst());
446 AbstractEncoder
*encoder
= NULL
;
447 bool nativeResampling
= false;
449 switch(m_settings
->compressionEncoder())
451 case SettingsModel::MP3Encoder
:
453 MP3Encoder
*mp3Encoder
= new MP3Encoder();
454 mp3Encoder
->setBitrate(m_settings
->compressionBitrate());
455 mp3Encoder
->setRCMode(m_settings
->compressionRCMode());
456 mp3Encoder
->setAlgoQuality(m_settings
->lameAlgoQuality());
457 if(m_settings
->bitrateManagementEnabled())
459 mp3Encoder
->setBitrateLimits(m_settings
->bitrateManagementMinRate(), m_settings
->bitrateManagementMaxRate());
461 if(m_settings
->samplingRate() > 0)
463 mp3Encoder
->setSamplingRate(SettingsModel::samplingRates
[m_settings
->samplingRate()]);
464 nativeResampling
= true;
466 mp3Encoder
->setChannelMode(m_settings
->lameChannelMode());
467 encoder
= mp3Encoder
;
470 case SettingsModel::VorbisEncoder
:
472 VorbisEncoder
*vorbisEncoder
= new VorbisEncoder();
473 vorbisEncoder
->setBitrate(m_settings
->compressionBitrate());
474 vorbisEncoder
->setRCMode(m_settings
->compressionRCMode());
475 if(m_settings
->bitrateManagementEnabled())
477 vorbisEncoder
->setBitrateLimits(m_settings
->bitrateManagementMinRate(), m_settings
->bitrateManagementMaxRate());
479 if(m_settings
->samplingRate() > 0)
481 vorbisEncoder
->setSamplingRate(SettingsModel::samplingRates
[m_settings
->samplingRate()]);
482 nativeResampling
= true;
484 encoder
= vorbisEncoder
;
487 case SettingsModel::AACEncoder
:
489 AACEncoder
*aacEncoder
= new AACEncoder();
490 aacEncoder
->setBitrate(m_settings
->compressionBitrate());
491 aacEncoder
->setRCMode(m_settings
->compressionRCMode());
492 aacEncoder
->setEnable2Pass(m_settings
->neroAACEnable2Pass());
493 aacEncoder
->setProfile(m_settings
->neroAACProfile());
494 encoder
= aacEncoder
;
497 case SettingsModel::FLACEncoder
:
499 FLACEncoder
*flacEncoder
= new FLACEncoder();
500 flacEncoder
->setBitrate(m_settings
->compressionBitrate());
501 flacEncoder
->setRCMode(m_settings
->compressionRCMode());
502 encoder
= flacEncoder
;
505 case SettingsModel::PCMEncoder
:
507 WaveEncoder
*waveEncoder
= new WaveEncoder();
508 waveEncoder
->setBitrate(m_settings
->compressionBitrate());
509 waveEncoder
->setRCMode(m_settings
->compressionRCMode());
510 encoder
= waveEncoder
;
514 throw "Unsupported encoder!";
517 ProcessThread
*thread
= new ProcessThread
520 (m_settings
->outputToSourceDir() ? QFileInfo(currentFile
.filePath()).absolutePath(): m_settings
->outputDir()),
522 m_settings
->prependRelativeSourcePath()
525 if((m_settings
->samplingRate() > 0) && !nativeResampling
)
527 thread
->addFilter(new ResampleFilter(SettingsModel::samplingRates
[m_settings
->samplingRate()]));
529 if((m_settings
->toneAdjustBass() != 0) || (m_settings
->toneAdjustTreble() != 0))
531 thread
->addFilter(new ToneAdjustFilter(m_settings
->toneAdjustBass(), m_settings
->toneAdjustTreble()));
533 if(m_settings
->normalizationFilterEnabled())
535 thread
->addFilter(new NormalizeFilter(m_settings
->normalizationFilterMaxVolume()));
538 m_threadList
.append(thread
);
539 m_allJobs
.append(thread
->getId());
541 connect(thread
, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection
);
542 connect(thread
, SIGNAL(processStateInitialized(QUuid
,QString
,QString
,int)), m_progressModel
, SLOT(addJob(QUuid
,QString
,QString
,int)), Qt::QueuedConnection
);
543 connect(thread
, SIGNAL(processStateChanged(QUuid
,QString
,int)), m_progressModel
, SLOT(updateJob(QUuid
,QString
,int)), Qt::QueuedConnection
);
544 connect(thread
, SIGNAL(processStateFinished(QUuid
,QString
,bool)), this, SLOT(processFinished(QUuid
,QString
,bool)), Qt::QueuedConnection
);
545 connect(thread
, SIGNAL(processMessageLogged(QUuid
,QString
)), m_progressModel
, SLOT(appendToLog(QUuid
,QString
)), Qt::QueuedConnection
);
551 void ProcessingDialog::writePlayList(void)
553 if(m_succeededJobs
.count() <= 0 || m_allJobs
.count() <= 0)
555 qWarning("WritePlayList: Nothing to do!");
559 QString playListName
= (m_metaInfo
->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo
->fileAlbum());
561 const static char *invalidChars
= "\\/:*?\"<>|";
562 for(int i
= 0; invalidChars
[i
]; i
++)
564 playListName
.replace(invalidChars
[i
], ' ');
565 playListName
= playListName
.simplified();
568 QString playListFile
= QString("%1/%2.m3u").arg(m_settings
->outputDir(), playListName
);
571 while(QFileInfo(playListFile
).exists())
573 playListFile
= QString("%1/%2 (%3).m3u").arg(m_settings
->outputDir(), playListName
, QString::number(++counter
));
576 QFile
playList(playListFile
);
577 if(playList
.open(QIODevice::WriteOnly
))
579 playList
.write("#EXTM3U\r\n");
580 for(int i
= 0; i
< m_allJobs
.count(); i
++)
583 if(!m_succeededJobs
.contains(m_allJobs
.at(i
))) continue;
584 playList
.write(QDir::toNativeSeparators(QDir(m_settings
->outputDir()).relativeFilePath(m_playList
.value(m_allJobs
.at(i
), "N/A"))).toUtf8().constData());
585 playList
.write("\r\n");
591 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile
));
595 AudioFileModel
ProcessingDialog::updateMetaInfo(const AudioFileModel
&audioFile
)
597 if(!m_settings
->writeMetaTags())
599 return AudioFileModel(audioFile
.filePath());
602 AudioFileModel result
= audioFile
;
604 if(!m_metaInfo
->fileArtist().isEmpty()) result
.setFileArtist(m_metaInfo
->fileArtist());
605 if(!m_metaInfo
->fileAlbum().isEmpty()) result
.setFileAlbum(m_metaInfo
->fileAlbum());
606 if(!m_metaInfo
->fileGenre().isEmpty()) result
.setFileGenre(m_metaInfo
->fileGenre());
607 if(m_metaInfo
->fileYear()) result
.setFileYear(m_metaInfo
->fileYear());
608 if(m_metaInfo
->filePosition() == UINT_MAX
) result
.setFilePosition(m_currentFile
);
609 if(!m_metaInfo
->fileComment().isEmpty()) result
.setFileComment(m_metaInfo
->fileComment());
614 void ProcessingDialog::setCloseButtonEnabled(bool enabled
)
616 HMENU hMenu
= GetSystemMenu((HWND
) winId(), FALSE
);
617 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| (enabled
? MF_ENABLED
: MF_GRAYED
));
620 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason
)
622 if(reason
== QSystemTrayIcon::DoubleClick
)
624 SetForegroundWindow(this->winId());