OSDN Git Service

Support for Wave (PCM) output.
[lamexp/LameXP.git] / src / Dialog_Processing.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2010 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.
14 //
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.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Dialog_Processing.h"
23
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"
37
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>
52
53 #include <Windows.h>
54
55 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
56 { \
57         QPalette palette = WIDGET->palette(); \
58         palette.setColor(QPalette::Background, COLOR); \
59         WIDGET->setPalette(palette); \
60 }
61
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())); \
66 }
67
68 ////////////////////////////////////////////////////////////
69 // Constructor
70 ////////////////////////////////////////////////////////////
71
72 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
73 :
74         QDialog(parent),
75         m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
76         m_settings(settings),
77         m_metaInfo(metaInfo)
78 {
79         //Init the dialog, from the .ui file
80         setupUi(this);
81         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
82         
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);
86
87         //Register meta type
88         qRegisterMetaType<QUuid>("QUuid");
89
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());
95
96         //Enable buttons
97         connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
98         
99         //Init progress indicator
100         m_progressIndicator = new QMovie(":/images/Working.gif");
101         label_headerWorking->setMovie(m_progressIndicator);
102         progressBar->setValue(0);
103
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)));
114
115         //Create context menu
116         m_contextMenu = new QMenu();
117         QAction *contextMenuAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), "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()));
121         
122         //Enque jobs
123         if(fileListModel)
124         {
125                 for(int i = 0; i < fileListModel->rowCount(); i++)
126                 {
127                         m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
128                 }
129         }
130
131         //Enable system tray icon
132         connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
133
134         //Init other vars
135         m_runningThreads = 0;
136         m_currentFile = 0;
137         m_allJobs.clear();
138         m_succeededJobs.clear();
139         m_failedJobs.clear();
140         m_userAborted = false;
141 }
142
143 ////////////////////////////////////////////////////////////
144 // Destructor
145 ////////////////////////////////////////////////////////////
146
147 ProcessingDialog::~ProcessingDialog(void)
148 {
149         view_log->setModel(NULL);
150         if(m_progressIndicator) m_progressIndicator->stop();
151         LAMEXP_DELETE(m_progressIndicator);
152         LAMEXP_DELETE(m_progressModel);
153         LAMEXP_DELETE(m_contextMenu);
154         LAMEXP_DELETE(m_systemTray);
155
156         WinSevenTaskbar::setOverlayIcon(this, NULL);
157         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
158
159         while(!m_threadList.isEmpty())
160         {
161                 ProcessThread *thread = m_threadList.takeFirst();
162                 thread->terminate();
163                 thread->wait(15000);
164                 delete thread;
165         }
166 }
167
168 ////////////////////////////////////////////////////////////
169 // EVENTS
170 ////////////////////////////////////////////////////////////
171
172 void ProcessingDialog::showEvent(QShowEvent *event)
173 {
174         setCloseButtonEnabled(false);
175         button_closeDialog->setEnabled(false);
176         button_AbortProcess->setEnabled(false);
177         m_systemTray->setVisible(true);
178         
179         if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
180         {
181                 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
182         }
183
184         QTimer::singleShot(1000, this, SLOT(initEncoding()));
185 }
186
187 void ProcessingDialog::closeEvent(QCloseEvent *event)
188 {
189         if(!button_closeDialog->isEnabled())
190         {
191                 event->ignore();
192         }
193         else
194         {
195                 m_systemTray->setVisible(false);
196         }
197 }
198
199 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
200 {
201         static QColor defaultColor = QColor();
202
203         if(obj == label_versionInfo)
204         {
205                 if(event->type() == QEvent::Enter)
206                 {
207                         QPalette palette = label_versionInfo->palette();
208                         defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
209                         palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
210                         label_versionInfo->setPalette(palette);
211                 }
212                 else if(event->type() == QEvent::Leave)
213                 {
214                         QPalette palette = label_versionInfo->palette();
215                         palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
216                         label_versionInfo->setPalette(palette);
217                 }
218                 else if(event->type() == QEvent::MouseButtonPress)
219                 {
220                         QUrl url("http://mulder.dummwiedeutsch.de/");
221                         QDesktopServices::openUrl(url);
222                 }
223         }
224
225         return false;
226 }
227
228 ////////////////////////////////////////////////////////////
229 // SLOTS
230 ////////////////////////////////////////////////////////////
231
232 void ProcessingDialog::initEncoding(void)
233 {
234         m_runningThreads = 0;
235         m_currentFile = 0;
236         m_allJobs.clear();
237         m_succeededJobs.clear();
238         m_failedJobs.clear();
239         m_userAborted = false;
240         m_playList.clear();
241         
242         CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
243         SET_PROGRESS_TEXT("Encoding files, please wait...");
244         m_progressIndicator->start();
245         
246         button_closeDialog->setEnabled(false);
247         button_AbortProcess->setEnabled(true);
248         progressBar->setRange(0, m_pendingJobs.count());
249
250         WinSevenTaskbar::initTaskbar();
251         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
252         WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
253         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
254
255         lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
256
257         for(int i = 0; i < min(max(cpuFeatures.count, 1), 4); i++)
258         {
259                 startNextJob();
260         }
261 }
262
263 void ProcessingDialog::abortEncoding(void)
264 {
265         m_userAborted = true;
266         button_AbortProcess->setEnabled(false);
267         
268         SET_PROGRESS_TEXT("Aborted! Waiting for running jobs to terminate...");
269
270         for(int i = 0; i < m_threadList.count(); i++)
271         {
272                 m_threadList.at(i)->abort();
273         }
274 }
275
276 void ProcessingDialog::doneEncoding(void)
277 {
278         m_runningThreads--;
279         progressBar->setValue(progressBar->value() + 1);
280         
281         if(!m_userAborted)
282         {
283                 SET_PROGRESS_TEXT(QString("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
284                 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
285         }
286         
287         int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
288         if(index >= 0)
289         {
290                 m_threadList.takeAt(index)->deleteLater();
291         }
292
293         if(!m_pendingJobs.isEmpty() && !m_userAborted)
294         {
295                 startNextJob();
296                 qDebug("Running jobs: %u", m_runningThreads);
297                 return;
298         }
299         
300         if(m_runningThreads > 0)
301         {
302                 qDebug("Running jobs: %u", m_runningThreads);
303                 return;
304         }
305
306         QApplication::setOverrideCursor(Qt::WaitCursor);
307         qDebug("Running jobs: %u", m_runningThreads);
308
309         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
310         {
311                 SET_PROGRESS_TEXT("Creatig the playlist file, please wait...");
312                 QApplication::processEvents();
313                 writePlayList();
314         }
315         
316         if(m_userAborted)
317         {
318                 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFF3BA"));
319                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
320                 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
321                 SET_PROGRESS_TEXT((m_succeededJobs.count() > 0) ? QString("Process was aborted by the user after %1 file(s)!").arg(QString::number(m_succeededJobs.count())) : "Process was aborted prematurely by the user!");
322                 m_systemTray->showMessage("LameXP - Aborted", "Process was aborted by the user.", QSystemTrayIcon::Warning);
323                 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
324                 QApplication::processEvents();
325                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
326         }
327         else
328         {
329                 if(m_failedJobs.count() > 0)
330                 {
331                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFBABA"));
332                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
333                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
334                         SET_PROGRESS_TEXT(QString("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())));
335                         m_systemTray->showMessage("LameXP - Error", "At least one file has failed!", QSystemTrayIcon::Critical);
336                         m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
337                         QApplication::processEvents();
338                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
339                 }
340                 else
341                 {
342                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#D1FFD5"));
343                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
344                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
345                         SET_PROGRESS_TEXT("Alle files completed successfully.");
346                         m_systemTray->showMessage("LameXP - Done", "All files completed successfully.", QSystemTrayIcon::Information);
347                         m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
348                         QApplication::processEvents();
349                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
350                 }
351         }
352         
353         setCloseButtonEnabled(true);
354         button_closeDialog->setEnabled(true);
355         button_AbortProcess->setEnabled(false);
356
357         view_log->scrollToBottom();
358         m_progressIndicator->stop();
359         progressBar->setValue(progressBar->maximum());
360         WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
361
362         QApplication::restoreOverrideCursor();
363 }
364
365 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
366 {
367         if(success)
368         {
369                 m_playList.insert(jobId, outFileName);
370                 m_succeededJobs.append(jobId);
371         }
372         else
373         {
374                 m_failedJobs.append(jobId);
375         }
376 }
377
378 void ProcessingDialog::progressModelChanged(void)
379 {
380         view_log->scrollToBottom();
381 }
382
383 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
384 {
385         if(m_runningThreads == 0)
386         {
387                 const QStringList &logFile = m_progressModel->getLogFile(index);
388                 LogViewDialog *logView = new LogViewDialog(this);
389                 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
390                 logView->exec(logFile);
391                 LAMEXP_DELETE(logView);
392         }
393         else
394         {
395                 MessageBeep(MB_ICONWARNING);
396         }
397 }
398
399 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
400 {
401         m_contextMenu->popup(view_log->mapToGlobal(pos));
402 }
403
404 void ProcessingDialog::contextMenuActionTriggered(void)
405 {
406         QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
407         logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
408 }
409
410 ////////////////////////////////////////////////////////////
411 // Private Functions
412 ////////////////////////////////////////////////////////////
413
414 void ProcessingDialog::startNextJob(void)
415 {
416         if(m_pendingJobs.isEmpty())
417         {
418                 return;
419         }
420         
421         m_currentFile++;
422         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
423         AbstractEncoder *encoder = NULL;
424
425         switch(m_settings->compressionEncoder())
426         {
427         case SettingsModel::MP3Encoder:
428                 {
429                         MP3Encoder *mp3Encoder = new MP3Encoder();
430                         mp3Encoder->setBitrate(m_settings->compressionBitrate());
431                         mp3Encoder->setRCMode(m_settings->compressionRCMode());
432                         encoder = mp3Encoder;
433                 }
434                 break;
435         case SettingsModel::VorbisEncoder:
436                 {
437                         VorbisEncoder *vorbisEncoder = new VorbisEncoder();
438                         vorbisEncoder->setBitrate(m_settings->compressionBitrate());
439                         vorbisEncoder->setRCMode(m_settings->compressionRCMode());
440                         encoder = vorbisEncoder;
441                 }
442                 break;
443         case SettingsModel::AACEncoder:
444                 {
445                         AACEncoder *aacEncoder = new AACEncoder();
446                         aacEncoder->setBitrate(m_settings->compressionBitrate());
447                         aacEncoder->setRCMode(m_settings->compressionRCMode());
448                         encoder = aacEncoder;
449                 }
450                 break;
451         case SettingsModel::FLACEncoder:
452                 {
453                         FLACEncoder *flacEncoder = new FLACEncoder();
454                         flacEncoder->setBitrate(m_settings->compressionBitrate());
455                         flacEncoder->setRCMode(m_settings->compressionRCMode());
456                         encoder = flacEncoder;
457                 }
458                 break;
459         case SettingsModel::PCMEncoder:
460                 {
461                         WaveEncoder *waveEncoder = new WaveEncoder();
462                         waveEncoder->setBitrate(m_settings->compressionBitrate());
463                         waveEncoder->setRCMode(m_settings->compressionRCMode());
464                         encoder = waveEncoder;
465                 }
466                 break;
467         default:
468                 throw "Unsupported encoder!";
469         }
470
471         ProcessThread *thread = new ProcessThread
472         (
473                 currentFile,
474                 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath(): m_settings->outputDir()),
475                 encoder,
476                 m_settings->prependRelativeSourcePath()
477         );
478         
479         m_threadList.append(thread);
480         m_allJobs.append(thread->getId());
481         
482         connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
483         connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
484         connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
485         connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
486         connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
487         
488         m_runningThreads++;
489         thread->start();
490 }
491
492 void ProcessingDialog::writePlayList(void)
493 {
494         if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
495         {
496                 qWarning("WritePlayList: Nothing to do!");
497                 return;
498         }
499         
500         QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
501
502         const static char *invalidChars = "\\/:*?\"<>|";
503         for(int i = 0; invalidChars[i]; i++)
504         {
505                 playListName.replace(invalidChars[i], ' ');
506                 playListName = playListName.simplified();
507         }
508         
509         QString playListFile = QString("%1/%2.m3u").arg(m_settings->outputDir(), playListName);
510
511         int counter = 1;
512         while(QFileInfo(playListFile).exists())
513         {
514                 playListFile = QString("%1/%2 (%3).m3u").arg(m_settings->outputDir(), playListName, QString::number(++counter));
515         }
516
517         QFile playList(playListFile);
518         if(playList.open(QIODevice::WriteOnly))
519         {
520                 playList.write("#EXTM3U\r\n");
521                 for(int i = 0; i < m_allJobs.count(); i++)
522                 {
523                         
524                         if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
525                         playList.write(QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A"))).toUtf8().constData());
526                         playList.write("\r\n");
527                 }
528                 playList.close();
529         }
530         else
531         {
532                 QMessageBox::warning(this, "Playlist creation failed", QString("The playlist file could not be created:<br><nobr>%1</nobr>").arg(playListFile));
533         }
534 }
535
536 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
537 {
538         if(!m_settings->writeMetaTags())
539         {
540                 return AudioFileModel(audioFile.filePath());
541         }
542         
543         AudioFileModel result = audioFile;
544
545         if(!m_metaInfo->fileArtist().isEmpty()) result.setFileArtist(m_metaInfo->fileArtist());
546         if(!m_metaInfo->fileAlbum().isEmpty()) result.setFileAlbum(m_metaInfo->fileAlbum());
547         if(!m_metaInfo->fileGenre().isEmpty()) result.setFileGenre(m_metaInfo->fileGenre());
548         if(m_metaInfo->fileYear()) result.setFileYear(m_metaInfo->fileYear());
549         if(m_metaInfo->filePosition() == UINT_MAX) result.setFilePosition(m_currentFile);
550         if(!m_metaInfo->fileComment().isEmpty()) result.setFileComment(m_metaInfo->fileComment());
551
552         return result;
553 }
554
555 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
556 {
557         HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
558         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
559 }
560
561 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
562 {
563         if(reason == QSystemTrayIcon::DoubleClick)
564         {
565                 SetForegroundWindow(this->winId());
566         }
567 }