OSDN Git Service

Added AAC encoding support.
[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
35 #include <QApplication>
36 #include <QRect>
37 #include <QDesktopWidget>
38 #include <QMovie>
39 #include <QMessageBox>
40 #include <QTimer>
41 #include <QCloseEvent>
42 #include <QDesktopServices>
43 #include <QUrl>
44 #include <QUuid>
45 #include <QFileInfo>
46 #include <QDir>
47 #include <QMenu>
48
49 #include <Windows.h>
50
51 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
52 { \
53         QPalette palette = WIDGET->palette(); \
54         palette.setColor(QPalette::Background, COLOR); \
55         WIDGET->setPalette(palette); \
56 }
57
58 ////////////////////////////////////////////////////////////
59 // Constructor
60 ////////////////////////////////////////////////////////////
61
62 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
63 :
64         QDialog(parent),
65         m_settings(settings),
66         m_metaInfo(metaInfo)
67 {
68         //Init the dialog, from the .ui file
69         setupUi(this);
70         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
71         
72         //Setup version info
73         label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
74         label_versionInfo->installEventFilter(this);
75
76         //Register meta type
77         qRegisterMetaType<QUuid>("QUuid");
78
79         //Center window in screen
80         QRect desktopRect = QApplication::desktop()->screenGeometry();
81         QRect thisRect = this->geometry();
82         move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
83         setMinimumSize(thisRect.width(), thisRect.height());
84
85         //Enable buttons
86         connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
87         
88         //Init progress indicator
89         m_progressIndicator = new QMovie(":/images/Working.gif");
90         label_headerWorking->setMovie(m_progressIndicator);
91         progressBar->setValue(0);
92
93         //Init progress model
94         m_progressModel = new ProgressModel();
95         view_log->setModel(m_progressModel);
96         view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
97         view_log->verticalHeader()->hide();
98         view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
99         view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
100         connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
101         connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
102         connect(view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
103
104         //Create context menu
105         m_contextMenu = new QMenu();
106         QAction *contextMenuAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), "Show details for selected job");
107         view_log->setContextMenuPolicy(Qt::CustomContextMenu);
108         connect(view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
109         connect(contextMenuAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuActionTriggered()));
110         
111         //Enque jobs
112         if(fileListModel)
113         {
114                 for(int i = 0; i < fileListModel->rowCount(); i++)
115                 {
116                         m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
117                 }
118         }
119
120         //Init other vars
121         m_runningThreads = 0;
122         m_currentFile = 0;
123         m_succeededFiles = 0;
124         m_failedFiles = 0;
125         m_userAborted = false;
126 }
127
128 ////////////////////////////////////////////////////////////
129 // Destructor
130 ////////////////////////////////////////////////////////////
131
132 ProcessingDialog::~ProcessingDialog(void)
133 {
134         view_log->setModel(NULL);
135         if(m_progressIndicator) m_progressIndicator->stop();
136         LAMEXP_DELETE(m_progressIndicator);
137         LAMEXP_DELETE(m_progressModel);
138         LAMEXP_DELETE(m_contextMenu);
139
140         while(!m_threadList.isEmpty())
141         {
142                 ProcessThread *thread = m_threadList.takeFirst();
143                 thread->terminate();
144                 thread->wait(15000);
145                 delete thread;
146         }
147 }
148
149 ////////////////////////////////////////////////////////////
150 // EVENTS
151 ////////////////////////////////////////////////////////////
152
153 void ProcessingDialog::showEvent(QShowEvent *event)
154 {
155         setCloseButtonEnabled(false);
156         button_closeDialog->setEnabled(false);
157         button_AbortProcess->setEnabled(false);
158
159         if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
160         {
161                 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
162         }
163
164         QTimer::singleShot(1000, this, SLOT(initEncoding()));
165 }
166
167 void ProcessingDialog::closeEvent(QCloseEvent *event)
168 {
169         if(!button_closeDialog->isEnabled()) event->ignore();
170 }
171
172 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
173 {
174         static QColor defaultColor = QColor();
175
176         if(obj == label_versionInfo)
177         {
178                 if(event->type() == QEvent::Enter)
179                 {
180                         QPalette palette = label_versionInfo->palette();
181                         defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
182                         palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
183                         label_versionInfo->setPalette(palette);
184                 }
185                 else if(event->type() == QEvent::Leave)
186                 {
187                         QPalette palette = label_versionInfo->palette();
188                         palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
189                         label_versionInfo->setPalette(palette);
190                 }
191                 else if(event->type() == QEvent::MouseButtonPress)
192                 {
193                         QUrl url("http://mulder.dummwiedeutsch.de/");
194                         QDesktopServices::openUrl(url);
195                 }
196         }
197
198         return false;
199 }
200
201 ////////////////////////////////////////////////////////////
202 // SLOTS
203 ////////////////////////////////////////////////////////////
204
205 void ProcessingDialog::initEncoding(void)
206 {
207         m_runningThreads = 0;
208         m_currentFile = 0;
209         m_succeededFiles = 0;
210         m_failedFiles = 0;
211         m_userAborted = false;
212         m_playList.clear();
213         
214         CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
215         label_progress->setText("Encoding files, please wait...");
216         m_progressIndicator->start();
217         
218         button_closeDialog->setEnabled(false);
219         button_AbortProcess->setEnabled(true);
220         progressBar->setRange(0, m_pendingJobs.count());
221
222         lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
223
224         for(int i = 0; i < min(max(cpuFeatures.count, 1), 4); i++)
225         {
226                 startNextJob();
227         }
228 }
229
230 void ProcessingDialog::abortEncoding(void)
231 {
232         m_userAborted = true;
233         button_AbortProcess->setEnabled(false);
234         
235         label_progress->setText("Aborted! Waiting for running jobs to terminate...");
236
237         for(int i = 0; i < m_threadList.count(); i++)
238         {
239                 m_threadList.at(i)->abort();
240         }
241 }
242
243 void ProcessingDialog::doneEncoding(void)
244 {
245         m_runningThreads--;
246         progressBar->setValue(progressBar->value() + 1);
247         
248         if(!m_userAborted)
249         {
250                 label_progress->setText(QString("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
251         }
252         
253         int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
254         if(index >= 0)
255         {
256                 m_threadList.takeAt(index)->deleteLater();
257         }
258
259         if(!m_pendingJobs.isEmpty() && !m_userAborted)
260         {
261                 startNextJob();
262                 qDebug("Running jobs: %u", m_runningThreads);
263                 return;
264         }
265         
266         if(m_runningThreads > 0)
267         {
268                 qDebug("Running jobs: %u", m_runningThreads);
269                 return;
270         }
271
272         QApplication::setOverrideCursor(Qt::WaitCursor);
273         qDebug("Running jobs: %u", m_runningThreads);
274
275         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
276         {
277                 label_progress->setText("Creatig the playlist file, please wait...");
278                 QApplication::processEvents();
279                 writePlayList();
280         }
281         
282         if(m_userAborted)
283         {
284                 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFF3BA"));
285                 label_progress->setText((m_succeededFiles > 0) ? QString("Process was aborted by the user after %1 file(s)!").arg(QString::number(m_succeededFiles)) : "Process was aborted prematurely by the user!");
286                 QApplication::processEvents();
287                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
288         }
289         else
290         {
291                 if(m_failedFiles)
292                 {
293                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFBABA"));
294                         label_progress->setText(QString("Error: %1 of %2 files failed. Double-click failed items for detailed information!").arg(QString::number(m_failedFiles), QString::number(m_failedFiles + m_succeededFiles)));
295                         QApplication::processEvents();
296                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
297                 }
298                 else
299                 {
300                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#D1FFD5"));
301                         label_progress->setText("Alle files completed successfully.");
302                         QApplication::processEvents();
303                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
304                 }
305         }
306         
307         setCloseButtonEnabled(true);
308         button_closeDialog->setEnabled(true);
309         button_AbortProcess->setEnabled(false);
310
311         view_log->scrollToBottom();
312         m_progressIndicator->stop();
313         progressBar->setValue(100);
314
315         QApplication::restoreOverrideCursor();
316 }
317
318 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
319 {
320         if(success)
321         {
322                 m_succeededFiles++;
323                 m_playList.append(outFileName);
324         }
325         else
326         {
327                 m_failedFiles++;
328         }
329 }
330
331 void ProcessingDialog::progressModelChanged(void)
332 {
333         view_log->scrollToBottom();
334 }
335
336 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
337 {
338         if(m_runningThreads == 0)
339         {
340                 const QStringList &logFile = m_progressModel->getLogFile(index);
341                 LogViewDialog *logView = new LogViewDialog(this);
342                 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
343                 logView->exec(logFile);
344                 LAMEXP_DELETE(logView);
345         }
346         else
347         {
348                 MessageBeep(MB_ICONWARNING);
349         }
350 }
351
352 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
353 {
354         m_contextMenu->popup(view_log->mapToGlobal(pos));
355 }
356
357 void ProcessingDialog::contextMenuActionTriggered(void)
358 {
359         QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
360         logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
361 }
362
363 ////////////////////////////////////////////////////////////
364 // Private Functions
365 ////////////////////////////////////////////////////////////
366
367 void ProcessingDialog::startNextJob(void)
368 {
369         if(m_pendingJobs.isEmpty())
370         {
371                 return;
372         }
373         
374         m_currentFile++;
375         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
376         AbstractEncoder *encoder = NULL;
377         
378         switch(m_settings->compressionEncoder())
379         {
380         case SettingsModel::MP3Encoder:
381                 {
382                         MP3Encoder *mp3Encoder = new MP3Encoder();
383                         mp3Encoder->setBitrate(m_settings->compressionBitrate());
384                         mp3Encoder->setRCMode(m_settings->compressionRCMode());
385                         encoder = mp3Encoder;
386                 }
387                 break;
388         case SettingsModel::VorbisEncoder:
389                 {
390                         VorbisEncoder *vorbisEncoder = new VorbisEncoder();
391                         vorbisEncoder->setBitrate(m_settings->compressionBitrate());
392                         vorbisEncoder->setRCMode(m_settings->compressionRCMode());
393                         encoder = vorbisEncoder;
394                 }
395                 break;
396         case SettingsModel::AACEncoder:
397                 {
398                         AACEncoder *aacEncoder = new AACEncoder();
399                         aacEncoder->setBitrate(m_settings->compressionBitrate());
400                         aacEncoder->setRCMode(m_settings->compressionRCMode());
401                         encoder = aacEncoder;
402                 }
403                 break;
404         default:
405                 throw "Unsupported encoder!";
406         }
407
408         ProcessThread *thread = new ProcessThread(currentFile, (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath(): m_settings->outputDir()), encoder);
409         m_threadList.append(thread);
410         
411         connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
412         connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
413         connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
414         connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
415         connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
416         
417         m_runningThreads++;
418         thread->start();
419 }
420
421 void ProcessingDialog::writePlayList(void)
422 {
423         QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
424
425         const static char *invalidChars = "\\/:*?\"<>|";
426         for(int i = 0; invalidChars[i]; i++)
427         {
428                 playListName.replace(invalidChars[i], ' ');
429                 playListName = playListName.simplified();
430         }
431         
432         QString playListFile = QString("%1/%2.m3u").arg(m_settings->outputDir(), playListName);
433
434         int counter = 1;
435         while(QFileInfo(playListFile).exists())
436         {
437                 playListFile = QString("%1/%2 (%3).m3u").arg(m_settings->outputDir(), playListName, QString::number(++counter));
438         }
439         
440         QFile playList(playListFile);
441         if(playList.open(QIODevice::WriteOnly))
442         {
443                 playList.write("#EXTM3U\r\n");
444                 for(int i = 0; i < m_playList.count(); i++)
445                 {
446                         playList.write(QFileInfo(m_playList.at(i)).fileName().toUtf8().constData());
447                         playList.write("\r\n");
448                 }
449                 playList.close();
450         }
451         else
452         {
453                 QMessageBox::warning(this, "Playlist creation failed", QString("The playlist file could not be created:<br><nobr>%1</nobr>").arg(playListFile));
454         }
455 }
456
457 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
458 {
459         if(!m_settings->writeMetaTags())
460         {
461                 return AudioFileModel(audioFile.filePath());
462         }
463         
464         AudioFileModel result = audioFile;
465
466         if(!m_metaInfo->fileArtist().isEmpty()) result.setFileArtist(m_metaInfo->fileArtist());
467         if(!m_metaInfo->fileAlbum().isEmpty()) result.setFileAlbum(m_metaInfo->fileAlbum());
468         if(!m_metaInfo->fileGenre().isEmpty()) result.setFileGenre(m_metaInfo->fileGenre());
469         if(m_metaInfo->fileYear()) result.setFileYear(m_metaInfo->fileYear());
470         if(m_metaInfo->filePosition()) result.setFileYear(m_metaInfo->filePosition() != UINT_MAX ? m_metaInfo->filePosition() : m_currentFile);
471         if(!m_metaInfo->fileComment().isEmpty()) result.setFileComment(m_metaInfo->fileComment());
472
473         return result;
474 }
475
476 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
477 {
478         HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
479         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
480 }