1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Dialog_Processing.h"
26 #include "../tmp/UIC_ProcessingDialog.h"
29 #include "Model_FileList.h"
30 #include "Model_Progress.h"
31 #include "Model_Settings.h"
32 #include "Thread_Process.h"
33 #include "Thread_CPUObserver.h"
34 #include "Thread_RAMObserver.h"
35 #include "Thread_DiskObserver.h"
36 #include "Dialog_LogView.h"
37 #include "Registry_Decoder.h"
38 #include "Registry_Encoder.h"
39 #include "Filter_Downmix.h"
40 #include "Filter_Normalize.h"
41 #include "Filter_Resample.h"
42 #include "Filter_ToneAdjust.h"
43 #include "WinSevenTaskbar.h"
45 #include <QApplication>
47 #include <QDesktopWidget>
49 #include <QMessageBox>
51 #include <QCloseEvent>
52 #include <QDesktopServices>
58 #include <QSystemTrayIcon>
60 #include <QProgressDialog>
61 #include <QResizeEvent>
63 #include <QThreadPool>
68 ////////////////////////////////////////////////////////////
70 //Maximum number of parallel instances
71 #define MAX_INSTANCES 16U
73 //Function to calculate the number of instances
74 static int cores2instances(int cores
);
76 ////////////////////////////////////////////////////////////
78 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
80 QPalette palette = WIDGET->palette(); \
81 palette.setColor(QPalette::Background, COLOR); \
82 WIDGET->setPalette(palette); \
86 #define SET_PROGRESS_TEXT(TXT) do \
88 ui->label_progress->setText(TXT); \
89 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
93 #define SET_FONT_BOLD(WIDGET,BOLD) do \
95 QFont _font = WIDGET->font(); \
96 _font.setBold(BOLD); WIDGET->setFont(_font); \
100 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
102 QPalette _palette = WIDGET->palette(); \
103 _palette.setColor(QPalette::WindowText, (COLOR)); \
104 _palette.setColor(QPalette::Text, (COLOR)); \
105 WIDGET->setPalette(_palette); \
109 #define UPDATE_MIN_WIDTH(WIDGET) do \
111 if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
115 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
117 if(m_settings->soundsEnabled()) lamexp_play_sound((NAME), (ASYNC)); \
121 #define IS_VBR(RC_MODE) ((RC_MODE) == SettingsModel::VBRMode)
123 ////////////////////////////////////////////////////////////
125 //Dummy class for UserData
126 class IntUserData
: public QObjectUserData
129 IntUserData(int value
) : m_value(value
) {/*NOP*/}
130 int value(void) { return m_value
; }
131 void setValue(int value
) { m_value
= value
; }
136 ////////////////////////////////////////////////////////////
138 ////////////////////////////////////////////////////////////
140 ProcessingDialog::ProcessingDialog(FileListModel
*fileListModel
, const AudioFileModel_MetaInfo
*metaInfo
, SettingsModel
*settings
, QWidget
*parent
)
143 ui(new Ui::ProcessingDialog
),
145 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
146 m_settings(settings
),
147 m_metaInfo(metaInfo
),
148 m_shutdownFlag(shutdownFlag_None
),
150 m_diskObserver(NULL
),
153 m_progressViewFilter(-1),
155 m_defaultColor(new QColor()),
158 //Init the dialog, from the .ui file
160 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint
);
162 //Update the window icon
163 m_windowIcon
= lamexp_set_window_icon(this, lamexp_app_icon(), true);
166 ui
->label_headerIcon
->setPixmap(lamexp_app_icon().pixmap(ui
->label_headerIcon
->size()));
169 ui
->label_versionInfo
->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
170 ui
->label_versionInfo
->installEventFilter(this);
173 qRegisterMetaType
<QUuid
>("QUuid");
175 //Center window in screen
176 QRect desktopRect
= QApplication::desktop()->screenGeometry();
177 QRect thisRect
= this->geometry();
178 move((desktopRect
.width() - thisRect
.width()) / 2, (desktopRect
.height() - thisRect
.height()) / 2);
179 setMinimumSize(thisRect
.width(), thisRect
.height());
182 connect(ui
->button_AbortProcess
, SIGNAL(clicked()), this, SLOT(abortEncoding()));
184 //Init progress indicator
185 m_progressIndicator
= new QMovie(":/images/Working.gif");
186 m_progressIndicator
->setCacheMode(QMovie::CacheAll
);
187 ui
->label_headerWorking
->setMovie(m_progressIndicator
);
188 ui
->progressBar
->setValue(0);
190 //Init progress model
191 m_progressModel
= new ProgressModel();
192 ui
->view_log
->setModel(m_progressModel
);
193 ui
->view_log
->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
194 ui
->view_log
->verticalHeader()->hide();
195 ui
->view_log
->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
196 ui
->view_log
->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch
);
197 ui
->view_log
->viewport()->installEventFilter(this);
198 connect(m_progressModel
, SIGNAL(rowsInserted(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
199 connect(m_progressModel
, SIGNAL(rowsMoved(QModelIndex
,int,int,QModelIndex
,int)), this, SLOT(progressModelChanged()));
200 connect(m_progressModel
, SIGNAL(rowsRemoved(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
201 connect(m_progressModel
, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
202 connect(ui
->view_log
, SIGNAL(activated(QModelIndex
)), this, SLOT(logViewDoubleClicked(QModelIndex
)));
203 connect(ui
->view_log
->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
205 //Create context menu
206 m_contextMenu
= new QMenu();
207 QAction
*contextMenuDetailsAction
= m_contextMenu
->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
208 QAction
*contextMenuShowFileAction
= m_contextMenu
->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
209 m_contextMenu
->addSeparator();
211 //Create "filter" context menu
212 m_progressViewFilterGroup
= new QActionGroup(this);
213 QAction
*contextMenuFilterAction
[5] = {NULL
, NULL
, NULL
, NULL
, NULL
};
214 if(QMenu
*filterMenu
= m_contextMenu
->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
216 contextMenuFilterAction
[0] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobRunning
), tr("Show Running Only"));
217 contextMenuFilterAction
[1] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobComplete
), tr("Show Succeeded Only"));
218 contextMenuFilterAction
[2] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobFailed
), tr("Show Failed Only"));
219 contextMenuFilterAction
[3] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobSkipped
), tr("Show Skipped Only"));
220 contextMenuFilterAction
[4] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
221 if(QAction
*act
= contextMenuFilterAction
[0]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobRunning
); }
222 if(QAction
*act
= contextMenuFilterAction
[1]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobComplete
); }
223 if(QAction
*act
= contextMenuFilterAction
[2]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobFailed
); }
224 if(QAction
*act
= contextMenuFilterAction
[3]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobSkipped
); }
225 if(QAction
*act
= contextMenuFilterAction
[4]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(-1); act
->setChecked(true); }
229 if(m_filterInfoLabel
= new QLabel(ui
->view_log
))
231 m_filterInfoLabel
->setFrameShape(QFrame::NoFrame
);
232 m_filterInfoLabel
->setAlignment(Qt::AlignHCenter
| Qt::AlignVCenter
);
233 m_filterInfoLabel
->setUserData(0, new IntUserData(-1));
234 SET_FONT_BOLD(m_filterInfoLabel
, true);
235 SET_TEXT_COLOR(m_filterInfoLabel
, Qt::darkGray
);
236 m_filterInfoLabel
->setContextMenuPolicy(Qt::CustomContextMenu
);
237 connect(m_filterInfoLabel
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
238 m_filterInfoLabel
->hide();
240 if(m_filterInfoLabelIcon
= new QLabel(ui
->view_log
))
242 m_filterInfoLabelIcon
->setFrameShape(QFrame::NoFrame
);
243 m_filterInfoLabelIcon
->setAlignment(Qt::AlignHCenter
| Qt::AlignTop
);
244 m_filterInfoLabelIcon
->setContextMenuPolicy(Qt::CustomContextMenu
);
245 const QIcon
&ico
= m_progressModel
->getIcon(ProgressModel::JobState(-1));
246 m_filterInfoLabelIcon
->setPixmap(ico
.pixmap(16, 16));
247 connect(m_filterInfoLabelIcon
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
248 m_filterInfoLabelIcon
->hide();
251 //Connect context menu
252 ui
->view_log
->setContextMenuPolicy(Qt::CustomContextMenu
);
253 connect(ui
->view_log
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
254 connect(contextMenuDetailsAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
255 connect(contextMenuShowFileAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
256 for(size_t i
= 0; i
< 5; i
++)
258 if(contextMenuFilterAction
[i
]) connect(contextMenuFilterAction
[i
], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
260 SET_FONT_BOLD(contextMenuDetailsAction
, true);
265 for(int i
= 0; i
< fileListModel
->rowCount(); i
++)
267 m_pendingJobs
.append(fileListModel
->getFile(fileListModel
->index(i
,0)));
272 ui
->label_headerStatus
->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
274 //Enable system tray icon
275 connect(m_systemTray
, SIGNAL(activated(QSystemTrayIcon::ActivationReason
)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason
)));
278 m_runningThreads
= 0;
281 m_succeededJobs
.clear();
282 m_failedJobs
.clear();
283 m_skippedJobs
.clear();
284 m_userAborted
= false;
285 m_forcedAbort
= false;
289 ////////////////////////////////////////////////////////////
291 ////////////////////////////////////////////////////////////
293 ProcessingDialog::~ProcessingDialog(void)
295 ui
->view_log
->setModel(NULL
);
297 if(m_progressIndicator
)
299 m_progressIndicator
->stop();
304 m_diskObserver
->stop();
305 if(!m_diskObserver
->wait(15000))
307 m_diskObserver
->terminate();
308 m_diskObserver
->wait();
314 m_cpuObserver
->stop();
315 if(!m_cpuObserver
->wait(15000))
317 m_cpuObserver
->terminate();
318 m_cpuObserver
->wait();
324 m_ramObserver
->stop();
325 if(!m_ramObserver
->wait(15000))
327 m_ramObserver
->terminate();
328 m_ramObserver
->wait();
334 if(!m_threadPool
->waitForDone(100))
336 emit
abortRunningTasks();
337 m_threadPool
->waitForDone();
341 LAMEXP_DELETE(m_progressIndicator
);
342 LAMEXP_DELETE(m_systemTray
);
343 LAMEXP_DELETE(m_diskObserver
);
344 LAMEXP_DELETE(m_cpuObserver
);
345 LAMEXP_DELETE(m_ramObserver
);
346 LAMEXP_DELETE(m_progressViewFilterGroup
);
347 LAMEXP_DELETE(m_filterInfoLabel
);
348 LAMEXP_DELETE(m_filterInfoLabelIcon
);
349 LAMEXP_DELETE(m_contextMenu
);
350 LAMEXP_DELETE(m_progressModel
);
351 LAMEXP_DELETE(m_threadPool
);
352 LAMEXP_DELETE(m_defaultColor
);
354 WinSevenTaskbar::setOverlayIcon(this, NULL
);
355 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState
);
359 lamexp_free_window_icon(m_windowIcon
);
366 ////////////////////////////////////////////////////////////
368 ////////////////////////////////////////////////////////////
370 void ProcessingDialog::showEvent(QShowEvent
*event
)
372 QDialog::showEvent(event
);
376 static const char *NA
= " N/A";
378 lamexp_enable_close_button(this, false);
379 ui
->button_closeDialog
->setEnabled(false);
380 ui
->button_AbortProcess
->setEnabled(false);
381 m_progressIndicator
->start();
382 m_systemTray
->setVisible(true);
384 lamexp_change_process_priority(1);
386 ui
->label_cpu
->setText(NA
);
387 ui
->label_disk
->setText(NA
);
388 ui
->label_ram
->setText(NA
);
390 QTimer::singleShot(500, this, SLOT(initEncoding()));
394 //Force update geometry
398 void ProcessingDialog::closeEvent(QCloseEvent
*event
)
400 if(!ui
->button_closeDialog
->isEnabled())
406 m_systemTray
->setVisible(false);
410 bool ProcessingDialog::eventFilter(QObject
*obj
, QEvent
*event
)
412 if(obj
== ui
->label_versionInfo
)
414 if(event
->type() == QEvent::Enter
)
416 QPalette palette
= ui
->label_versionInfo
->palette();
417 *m_defaultColor
= palette
.color(QPalette::Normal
, QPalette::WindowText
);
418 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, Qt::red
);
419 ui
->label_versionInfo
->setPalette(palette
);
421 else if(event
->type() == QEvent::Leave
)
423 QPalette palette
= ui
->label_versionInfo
->palette();
424 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, *m_defaultColor
);
425 ui
->label_versionInfo
->setPalette(palette
);
427 else if(event
->type() == QEvent::MouseButtonPress
)
429 QUrl
url(lamexp_website_url());
430 QDesktopServices::openUrl(url
);
437 bool ProcessingDialog::event(QEvent
*e
)
441 case lamexp_event_queryendsession
:
442 qWarning("System is shutting down, preparing to abort...");
443 if(!m_userAborted
) abortEncoding(true);
445 case lamexp_event_endsession
:
446 qWarning("System is shutting down, encoding will be aborted now...");
451 if(!m_userAborted
) abortEncoding(true);
452 qApp
->processEvents(QEventLoop::WaitForMoreEvents
| QEventLoop::ExcludeUserInputEvents
);
455 m_pendingJobs
.clear();
458 return QDialog::event(e
);
465 void ProcessingDialog::resizeEvent(QResizeEvent
*event
)
467 if(event
) QDialog::resizeEvent(event
);
469 if(QWidget
*port
= ui
->view_log
->viewport())
471 QRect geom
= port
->geometry();
472 m_filterInfoLabel
->setGeometry(geom
.left() + 16, geom
.top() + 16, geom
.width() - 32, 48);
473 m_filterInfoLabelIcon
->setGeometry(geom
.left() + 16, geom
.top() + 64, geom
.width() - 32, geom
.height() - 80);
477 bool ProcessingDialog::winEvent(MSG
*message
, long *result
)
479 return WinSevenTaskbar::handleWinEvent(message
, result
);
482 ////////////////////////////////////////////////////////////
484 ////////////////////////////////////////////////////////////
486 void ProcessingDialog::initEncoding(void)
488 qDebug("Initializing encoding process...");
490 m_runningThreads
= 0;
493 m_succeededJobs
.clear();
494 m_failedJobs
.clear();
495 m_skippedJobs
.clear();
496 m_userAborted
= false;
497 m_forcedAbort
= false;
500 DecoderRegistry::configureDecoders(m_settings
);
502 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor(Qt::white
));
503 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
505 ui
->button_closeDialog
->setEnabled(false);
506 ui
->button_AbortProcess
->setEnabled(true);
507 ui
->progressBar
->setRange(0, m_pendingJobs
.count());
508 ui
->checkBox_shutdownComputer
->setEnabled(true);
509 ui
->checkBox_shutdownComputer
->setChecked(false);
511 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState
);
512 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs
.count());
513 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
517 m_diskObserver
= new DiskObserverThread(m_settings
->customTempPathEnabled() ? m_settings
->customTempPath() : lamexp_temp_folder2());
518 connect(m_diskObserver
, SIGNAL(messageLogged(QString
,int)), m_progressModel
, SLOT(addSystemMessage(QString
,int)), Qt::QueuedConnection
);
519 connect(m_diskObserver
, SIGNAL(freeSpaceChanged(quint64
)), this, SLOT(diskUsageHasChanged(quint64
)), Qt::QueuedConnection
);
520 m_diskObserver
->start();
524 m_cpuObserver
= new CPUObserverThread();
525 connect(m_cpuObserver
, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection
);
526 m_cpuObserver
->start();
530 m_ramObserver
= new RAMObserverThread();
531 connect(m_ramObserver
, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection
);
532 m_ramObserver
->start();
537 unsigned int maximumInstances
= qBound(0U, m_settings
->maximumInstances(), MAX_INSTANCES
);
538 if(maximumInstances
< 1)
540 lamexp_cpu_t cpuFeatures
= lamexp_detect_cpu_features(lamexp_arguments());
541 maximumInstances
= cores2instances(qBound(1, cpuFeatures
.count
, 64));
544 maximumInstances
= qBound(1U, maximumInstances
, static_cast<unsigned int>(m_pendingJobs
.count()));
545 if(maximumInstances
> 1)
547 m_progressModel
->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances
)));
550 m_threadPool
= new QThreadPool();
551 m_threadPool
->setMaxThreadCount(maximumInstances
);
554 //for(int i = 0; i < m_threadPool->maxThreadCount(); i++)
557 // qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
558 // QThread::yieldCurrentThread();
561 m_initThreads
= m_threadPool
->maxThreadCount();
562 QTimer::singleShot(100, this, SLOT(initNextJob()));
563 m_timerStart
= lamexp_perfcounter_value();
566 void ProcessingDialog::initNextJob(void)
568 if((m_initThreads
> 0) && (!m_userAborted
))
571 if(--m_initThreads
> 0)
573 QTimer::singleShot(100, this, SLOT(initNextJob()));
578 void ProcessingDialog::startNextJob(void)
580 if(m_pendingJobs
.isEmpty())
582 qWarning("No more files left, unable to start another job!");
589 AudioFileModel currentFile
= updateMetaInfo(m_pendingJobs
.takeFirst());
590 bool nativeResampling
= false;
592 //Create encoder instance
593 AbstractEncoder
*encoder
= EncoderRegistry::createInstance(m_settings
->compressionEncoder(), m_settings
, &nativeResampling
);
595 //Create processing thread
596 ProcessThread
*thread
= new ProcessThread
599 (m_settings
->outputToSourceDir() ? QFileInfo(currentFile
.filePath()).absolutePath() : m_settings
->outputDir()),
600 (m_settings
->customTempPathEnabled() ? m_settings
->customTempPath() : lamexp_temp_folder2()),
602 m_settings
->prependRelativeSourcePath() && (!m_settings
->outputToSourceDir())
606 if(m_settings
->forceStereoDownmix())
608 thread
->addFilter(new DownmixFilter());
610 if((m_settings
->samplingRate() > 0) && !nativeResampling
)
612 if(SettingsModel::samplingRates
[m_settings
->samplingRate()] != currentFile
.techInfo().audioSamplerate() || currentFile
.techInfo().audioSamplerate() == 0)
614 thread
->addFilter(new ResampleFilter(SettingsModel::samplingRates
[m_settings
->samplingRate()]));
617 if((m_settings
->toneAdjustBass() != 0) || (m_settings
->toneAdjustTreble() != 0))
619 thread
->addFilter(new ToneAdjustFilter(m_settings
->toneAdjustBass(), m_settings
->toneAdjustTreble()));
621 if(m_settings
->normalizationFilterEnabled())
623 thread
->addFilter(new NormalizeFilter(m_settings
->normalizationFilterMaxVolume(), m_settings
->normalizationFilterEQMode()));
625 if(m_settings
->renameOutputFilesEnabled() && (!m_settings
->renameOutputFilesPattern().simplified().isEmpty()))
627 thread
->setRenamePattern(m_settings
->renameOutputFilesPattern());
629 if(m_settings
->overwriteMode() != SettingsModel::Overwrite_KeepBoth
)
631 thread
->setOverwriteMode((m_settings
->overwriteMode() == SettingsModel::Overwrite_SkipFile
), (m_settings
->overwriteMode() == SettingsModel::Overwrite_Replaces
));
634 m_allJobs
.append(thread
->getId());
636 //Connect thread signals
637 connect(thread
, SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection
);
638 connect(thread
, SIGNAL(processStateInitialized(QUuid
,QString
,QString
,int)), m_progressModel
, SLOT(addJob(QUuid
,QString
,QString
,int)), Qt::QueuedConnection
);
639 connect(thread
, SIGNAL(processStateChanged(QUuid
,QString
,int)), m_progressModel
, SLOT(updateJob(QUuid
,QString
,int)), Qt::QueuedConnection
);
640 connect(thread
, SIGNAL(processStateFinished(QUuid
,QString
,int)), this, SLOT(processFinished(QUuid
,QString
,int)), Qt::QueuedConnection
);
641 connect(thread
, SIGNAL(processMessageLogged(QUuid
,QString
)), m_progressModel
, SLOT(appendToLog(QUuid
,QString
)), Qt::QueuedConnection
);
642 connect(this, SIGNAL(abortRunningTasks()), thread
, SLOT(abort()), Qt::DirectConnection
);
644 //Initialize thread object
647 qFatal("Fatal Error: Thread initialization has failed!");
651 if(!thread
->start(m_threadPool
))
653 qWarning("Job failed to start or file was skipped!");
657 void ProcessingDialog::abortEncoding(bool force
)
659 m_userAborted
= true;
660 if(force
) m_forcedAbort
= true;
661 ui
->button_AbortProcess
->setEnabled(false);
662 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
663 emit
abortRunningTasks();
666 void ProcessingDialog::doneEncoding(void)
669 ui
->progressBar
->setValue(ui
->progressBar
->value() + 1);
673 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui
->progressBar
->value()).arg(QString::number(ui
->progressBar
->maximum())));
674 WinSevenTaskbar::setTaskbarProgress(this, ui
->progressBar
->value(), ui
->progressBar
->maximum());
677 if((!m_pendingJobs
.isEmpty()) && (!m_userAborted
))
679 QTimer::singleShot(0, this, SLOT(startNextJob()));
680 qDebug("%d files left, starting next job...", m_pendingJobs
.count());
684 if(m_runningThreads
> 0)
686 qDebug("No files left, but still have %u running jobs.", m_runningThreads
);
690 QApplication::setOverrideCursor(Qt::WaitCursor
);
691 qDebug("Running jobs: %u", m_runningThreads
);
693 if(!m_userAborted
&& m_settings
->createPlaylist() && !m_settings
->outputToSourceDir())
695 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
696 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
702 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#FFFFE0"));
703 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState
);
704 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
705 SET_PROGRESS_TEXT((m_succeededJobs
.count() > 0) ? tr("Process was aborted by the user after %n file(s)!", "", m_succeededJobs
.count()) : tr("Process was aborted prematurely by the user!"));
706 m_systemTray
->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning
);
707 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
708 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
709 if(!m_forcedAbort
) PLAY_SOUND_OPTIONAL("aborted", false);
713 const __int64 counter
= lamexp_perfcounter_value();
714 const __int64 frequency
= lamexp_perfcounter_frequ();
715 if((counter
>= 0I64
) && (frequency
>= 0))
717 if((m_timerStart
>= 0I64
) && (m_timerStart
< counter
))
719 double timeElapsed
= static_cast<double>(counter
- m_timerStart
) / static_cast<double>(frequency
);
720 m_progressModel
->addSystemMessage(tr("Process finished after %1.").arg(time2text(timeElapsed
)), ProgressModel::SysMsg_Performance
);
724 if(m_failedJobs
.count() > 0)
726 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#FFF0F0"));
727 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState
);
728 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
729 if(m_skippedJobs
.count() > 0)
731 SET_PROGRESS_TEXT(tr("Error: %1 of %n file(s) failed (%2). Double-click failed items for detailed information!", "", m_failedJobs
.count() + m_succeededJobs
.count() + m_skippedJobs
.count()).arg(QString::number(m_failedJobs
.count()), tr("%n file(s) skipped", "", m_skippedJobs
.count())));
735 SET_PROGRESS_TEXT(tr("Error: %1 of %n file(s) failed. Double-click failed items for detailed information!", "", m_failedJobs
.count() + m_succeededJobs
.count()).arg(QString::number(m_failedJobs
.count())));
737 m_systemTray
->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical
);
738 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
739 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
740 PLAY_SOUND_OPTIONAL("error", false);
744 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#F0FFF0"));
745 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState
);
746 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
747 if(m_skippedJobs
.count() > 0)
749 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs
.count()));
753 SET_PROGRESS_TEXT(tr("All files completed successfully."));
755 m_systemTray
->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information
);
756 m_systemTray
->setIcon(QIcon(":/icons/cd_add.png"));
757 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
758 PLAY_SOUND_OPTIONAL("success", false);
762 lamexp_enable_close_button(this, true);
763 ui
->button_closeDialog
->setEnabled(true);
764 ui
->button_AbortProcess
->setEnabled(false);
765 ui
->checkBox_shutdownComputer
->setEnabled(false);
767 m_progressModel
->restoreHiddenItems();
768 ui
->view_log
->scrollToBottom();
769 m_progressIndicator
->stop();
770 ui
->progressBar
->setValue(ui
->progressBar
->maximum());
771 WinSevenTaskbar::setTaskbarProgress(this, ui
->progressBar
->value(), ui
->progressBar
->maximum());
773 QApplication::restoreOverrideCursor();
775 if(!m_userAborted
&& ui
->checkBox_shutdownComputer
->isChecked())
777 if(shutdownComputer())
779 m_shutdownFlag
= m_settings
->hibernateComputer() ? shutdownFlag_Hibernate
: shutdownFlag_TurnPowerOff
;
785 void ProcessingDialog::processFinished(const QUuid
&jobId
, const QString
&outFileName
, int success
)
789 m_playList
.insert(jobId
, outFileName
);
790 m_succeededJobs
.append(jobId
);
794 m_playList
.insert(jobId
, outFileName
);
795 m_skippedJobs
.append(jobId
);
799 m_failedJobs
.append(jobId
);
802 //Update filter as soon as a job finished!
803 if(m_progressViewFilter
>= 0)
805 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
809 void ProcessingDialog::progressModelChanged(void)
811 //Update filter as soon as the model changes!
812 if(m_progressViewFilter
>= 0)
814 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
817 QTimer::singleShot(0, ui
->view_log
, SLOT(scrollToBottom()));
820 void ProcessingDialog::logViewDoubleClicked(const QModelIndex
&index
)
822 if(m_runningThreads
== 0)
824 const QStringList
&logFile
= m_progressModel
->getLogFile(index
);
826 if(!logFile
.isEmpty())
828 LogViewDialog
*logView
= new LogViewDialog(this);
829 logView
->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel
->data(index
, Qt::DisplayRole
).toString()));
830 logView
->exec(logFile
);
831 LAMEXP_DELETE(logView
);
835 QMessageBox::information(this, windowTitle(), m_progressModel
->data(m_progressModel
->index(index
.row(), 0)).toString());
840 lamexp_beep(lamexp_beep_warning
);
844 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex
, int oldSize
, int newSize
)
846 if(logicalIndex
== 1)
848 if(QHeaderView
*hdr
= ui
->view_log
->horizontalHeader())
850 hdr
->setMinimumSectionSize(qMax(hdr
->minimumSectionSize(), hdr
->sectionSize(1)));
855 void ProcessingDialog::contextMenuTriggered(const QPoint
&pos
)
857 QAbstractScrollArea
*scrollArea
= dynamic_cast<QAbstractScrollArea
*>(QObject::sender());
858 QWidget
*sender
= scrollArea
? scrollArea
->viewport() : dynamic_cast<QWidget
*>(QObject::sender());
860 if(pos
.x() <= sender
->width() && pos
.y() <= sender
->height() && pos
.x() >= 0 && pos
.y() >= 0)
862 m_contextMenu
->popup(sender
->mapToGlobal(pos
));
866 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
868 QModelIndex index
= ui
->view_log
->indexAt(ui
->view_log
->viewport()->mapFromGlobal(m_contextMenu
->pos()));
869 logViewDoubleClicked(index
.isValid() ? index
: ui
->view_log
->currentIndex());
872 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
874 QModelIndex index
= ui
->view_log
->indexAt(ui
->view_log
->viewport()->mapFromGlobal(m_contextMenu
->pos()));
875 const QUuid
&jobId
= m_progressModel
->getJobId(index
.isValid() ? index
: ui
->view_log
->currentIndex());
876 QString filePath
= m_playList
.value(jobId
, QString());
878 if(filePath
.isEmpty())
880 lamexp_beep(lamexp_beep_warning
);
884 if(QFileInfo(filePath
).exists())
886 QString systemRootPath
;
888 QDir
systemRoot(lamexp_known_folder(lamexp_folder_systemfolder
));
889 if(systemRoot
.exists() && systemRoot
.cdUp())
891 systemRootPath
= systemRoot
.canonicalPath();
894 if(!systemRootPath
.isEmpty())
896 QFileInfo
explorer(QString("%1/explorer.exe").arg(systemRootPath
));
897 if(explorer
.exists() && explorer
.isFile())
899 QProcess::execute(explorer
.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath
).canonicalFilePath()));
905 qWarning("SystemRoot directory could not be detected!");
910 qWarning("File not found: %s", filePath
.toLatin1().constData());
911 lamexp_beep(lamexp_beep_error
);
915 void ProcessingDialog::contextMenuFilterActionTriggered(void)
917 if(QAction
*action
= dynamic_cast<QAction
*>(QObject::sender()))
919 if(action
->data().type() == QVariant::Int
)
921 m_progressViewFilter
= action
->data().toInt();
922 progressViewFilterChanged();
923 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
924 QTimer::singleShot(0, ui
->view_log
, SLOT(scrollToBottom()));
925 action
->setChecked(true);
931 * Filter progress items
933 void ProcessingDialog::progressViewFilterChanged(void)
935 bool matchFound
= false;
937 for(int i
= 0; i
< ui
->view_log
->model()->rowCount(); i
++)
939 QModelIndex index
= (m_progressViewFilter
>= 0) ? m_progressModel
->index(i
, 0) : QModelIndex();
940 const bool bHide
= index
.isValid() ? (m_progressModel
->getJobState(index
) != m_progressViewFilter
) : false;
941 ui
->view_log
->setRowHidden(i
, bHide
); matchFound
= matchFound
|| (!bHide
);
944 if((m_progressViewFilter
>= 0) && (!matchFound
))
946 if(m_filterInfoLabel
->isHidden() || (dynamic_cast<IntUserData
*>(m_filterInfoLabel
->userData(0))->value() != m_progressViewFilter
))
948 dynamic_cast<IntUserData
*>(m_filterInfoLabel
->userData(0))->setValue(m_progressViewFilter
);
949 m_filterInfoLabel
->setText(QString("<p>» %1 «</p>").arg(tr("None of the items matches the current filtering rules")));
950 m_filterInfoLabel
->show();
951 m_filterInfoLabelIcon
->setPixmap(m_progressModel
->getIcon(static_cast<ProgressModel::JobState
>(m_progressViewFilter
)).pixmap(16, 16, QIcon::Disabled
));
952 m_filterInfoLabelIcon
->show();
956 else if(!m_filterInfoLabel
->isHidden())
958 m_filterInfoLabel
->hide();
959 m_filterInfoLabelIcon
->hide();
963 ////////////////////////////////////////////////////////////
965 ////////////////////////////////////////////////////////////
967 void ProcessingDialog::writePlayList(void)
969 if(m_succeededJobs
.count() <= 0 || m_allJobs
.count() <= 0)
971 qWarning("WritePlayList: Nothing to do!");
975 //Init local variables
977 QRegExp
regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive
);
978 QRegExp
regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive
);
979 QRegExp
regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive
);
980 bool usePrefix
[3] = {true, true, true};
981 bool useUtf8
= false;
984 //Generate playlist name
985 QString playListName
= (m_metaInfo
->album().isEmpty() ? "Playlist" : m_metaInfo
->album());
986 if(!m_metaInfo
->artist().isEmpty())
988 playListName
= QString("%1 - %2").arg(m_metaInfo
->artist(), playListName
);
991 //Clean playlist name
992 playListName
= lamexp_clean_filename(playListName
);
994 //Create list of audio files
995 for(int i
= 0; i
< m_allJobs
.count(); i
++)
997 if(!m_succeededJobs
.contains(m_allJobs
.at(i
))) continue;
998 list
<< QDir::toNativeSeparators(QDir(m_settings
->outputDir()).relativeFilePath(m_playList
.value(m_allJobs
.at(i
), "N/A")));
1002 for(int i
= 0; i
< list
.count(); i
++)
1004 if(regExp1
.indexIn(list
.at(i
)) < 0) usePrefix
[0] = false;
1005 if(regExp2
.indexIn(list
.at(i
)) < 0) usePrefix
[1] = false;
1006 if(regExp3
.indexIn(list
.at(i
)) < 0) usePrefix
[2] = false;
1008 if(usePrefix
[0] || usePrefix
[1] || usePrefix
[2])
1010 playListName
.prepend(usePrefix
[0] ? "[00] " : (usePrefix
[1] ? "(00) " : "00 "));
1013 //Do we need an UTF-8 playlist?
1014 for(int i
= 0; i
< list
.count(); i
++)
1016 if(wcscmp(QWCHAR(QString::fromLatin1(list
.at(i
).toLatin1().constData())), QWCHAR(list
.at(i
))))
1023 //Generate playlist output file
1024 QString playListFile
= QString("%1/%2.%3").arg(m_settings
->outputDir(), playListName
, (useUtf8
? "m3u8" : "m3u"));
1025 while(QFileInfo(playListFile
).exists())
1027 playListFile
= QString("%1/%2 (%3).%4").arg(m_settings
->outputDir(), playListName
, QString::number(++counter
), (useUtf8
? "m3u8" : "m3u"));
1030 //Now write playlist to output file
1031 QFile
playList(playListFile
);
1032 if(playList
.open(QIODevice::WriteOnly
))
1036 playList
.write("\xef\xbb\xbf");
1038 playList
.write("#EXTM3U\r\n");
1039 while(!list
.isEmpty())
1041 playList
.write(useUtf8
? QUTF8(list
.takeFirst()) : list
.takeFirst().toLatin1().constData());
1042 playList
.write("\r\n");
1048 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile
));
1052 AudioFileModel
ProcessingDialog::updateMetaInfo(AudioFileModel
&audioFile
)
1054 if(!m_settings
->writeMetaTags())
1056 audioFile
.metaInfo().reset();
1060 audioFile
.metaInfo().update(*m_metaInfo
, true);
1062 if(audioFile
.metaInfo().position() == UINT_MAX
)
1064 audioFile
.metaInfo().setPosition(m_currentFile
);
1070 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason
)
1072 if(reason
== QSystemTrayIcon::DoubleClick
)
1074 lamexp_bring_to_front(this);
1078 void ProcessingDialog::cpuUsageHasChanged(const double val
)
1081 ui
->label_cpu
->setText(QString().sprintf(" %d%%", qRound(val
* 100.0)));
1082 UPDATE_MIN_WIDTH(ui
->label_cpu
);
1085 void ProcessingDialog::ramUsageHasChanged(const double val
)
1088 ui
->label_ram
->setText(QString().sprintf(" %d%%", qRound(val
* 100.0)));
1089 UPDATE_MIN_WIDTH(ui
->label_ram
);
1092 void ProcessingDialog::diskUsageHasChanged(const quint64 val
)
1095 const char *postfixStr
[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1096 double space
= static_cast<double>(val
);
1098 while((space
>= 1000.0) && (postfix
< 5))
1100 space
= space
/ 1024.0;
1104 ui
->label_disk
->setText(QString().sprintf(" %3.1f %s", space
, postfixStr
[postfix
]));
1105 UPDATE_MIN_WIDTH(ui
->label_disk
);
1108 bool ProcessingDialog::shutdownComputer(void)
1110 const int iTimeout
= m_settings
->hibernateComputer() ? 10 : 30;
1111 const Qt::WindowFlags flags
= Qt::WindowStaysOnTopHint
| Qt::CustomizeWindowHint
| Qt::WindowTitleHint
| Qt::MSWindowsFixedSizeDialogHint
| Qt::WindowSystemMenuHint
;
1112 const QString text
= QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1114 qWarning("Initiating shutdown sequence!");
1116 QProgressDialog
progressDialog(text
.arg(iTimeout
), tr("Cancel Shutdown"), 0, iTimeout
+ 1, this, flags
);
1117 QPushButton
*cancelButton
= new QPushButton(tr("Cancel Shutdown"), &progressDialog
);
1118 cancelButton
->setIcon(QIcon(":/icons/power_on.png"));
1119 progressDialog
.setModal(true);
1120 progressDialog
.setAutoClose(false);
1121 progressDialog
.setAutoReset(false);
1122 progressDialog
.setWindowIcon(QIcon(":/icons/power_off.png"));
1123 progressDialog
.setCancelButton(cancelButton
);
1124 progressDialog
.show();
1126 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
1128 QApplication::setOverrideCursor(Qt::WaitCursor
);
1129 PLAY_SOUND_OPTIONAL("shutdown", false);
1130 QApplication::restoreOverrideCursor();
1133 timer
.setInterval(1000);
1136 QEventLoop
eventLoop(this);
1137 connect(&timer
, SIGNAL(timeout()), &eventLoop
, SLOT(quit()));
1138 connect(&progressDialog
, SIGNAL(canceled()), &eventLoop
, SLOT(quit()));
1140 for(int i
= 1; i
<= iTimeout
; i
++)
1143 if(progressDialog
.wasCanceled())
1145 progressDialog
.close();
1148 progressDialog
.setValue(i
+1);
1149 progressDialog
.setLabelText(text
.arg(iTimeout
-i
));
1150 if(iTimeout
-i
== 3) progressDialog
.setCancelButton(NULL
);
1151 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
1152 PLAY_SOUND_OPTIONAL(((i
< iTimeout
) ? "beep" : "beep2"), false);
1155 progressDialog
.close();
1159 QString
ProcessingDialog::time2text(const double timeVal
) const
1162 double frcPart
= modf(timeVal
, &intPart
);
1164 QTime time
= QTime().addSecs(qRound(intPart
)).addMSecs(qRound(frcPart
* 1000.0));
1170 a
= tr("%n hour(s)", "", time
.hour());
1171 b
= tr("%n minute(s)", "", time
.minute());
1173 else if(time
.minute() > 0)
1175 a
= tr("%n minute(s)", "", time
.minute());
1176 b
= tr("%n second(s)", "", time
.second());
1180 a
= tr("%n second(s)", "", time
.second());
1181 b
= tr("%n millisecond(s)", "", time
.msec());
1184 return QString("%1, %2").arg(a
, b
);
1187 ////////////////////////////////////////////////////////////
1189 ////////////////////////////////////////////////////////////
1191 static int cores2instances(int cores
)
1193 //This function is a "cubic spline" with sampling points at:
1194 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1195 static const double LUT
[8][5] =
1197 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1198 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1199 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1200 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1201 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1202 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1203 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1204 {DBL_MAX
, 0.0, 0.0, 0.0, 0.0}
1207 double x
= abs(static_cast<double>(cores
)), y
= 1.0;
1209 for(size_t i
= 0; i
< 7; i
++)
1211 if((x
>= LUT
[i
][0]) && (x
< LUT
[i
+1][0]))
1213 y
= (((((LUT
[i
][1] * x
) + LUT
[i
][2]) * x
) + LUT
[i
][3]) * x
) + LUT
[i
][4];