OSDN Git Service

Added a normalization filter, based on SoX.
[lamexp/LameXP.git] / src / Thread_Process.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
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 "Thread_Process.h"
23
24 #include "Global.h"
25 #include "Model_AudioFile.h"
26 #include "Model_Progress.h"
27 #include "Encoder_Abstract.h"
28 #include "Decoder_Abstract.h"
29 #include "Filter_Abstract.h"
30 #include "Filter_Downmix.h"
31 #include "Registry_Decoder.h"
32 #include "Model_Settings.h"
33
34 #include <QUuid>
35 #include <QFileInfo>
36 #include <QDir>
37 #include <QMutex>
38 #include <QMutexLocker>
39
40 #include <limits.h>
41 #include <time.h>
42
43 QMutex *ProcessThread::m_mutex_genFileName = NULL;
44
45 ////////////////////////////////////////////////////////////
46 // Constructor
47 ////////////////////////////////////////////////////////////
48
49 ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
50 :
51         m_audioFile(audioFile),
52         m_outputDirectory(outputDirectory),
53         m_encoder(encoder),
54         m_jobId(QUuid::createUuid()),
55         m_prependRelativeSourcePath(prependRelativeSourcePath),
56         m_aborted(false)
57 {
58         if(m_mutex_genFileName)
59         {
60                 m_mutex_genFileName = new QMutex;
61         }
62
63         connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
64         connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
65
66         m_currentStep = UnknownStep;
67 }
68
69 ProcessThread::~ProcessThread(void)
70 {
71         while(!m_tempFiles.isEmpty())
72         {
73                 lamexp_remove_file(m_tempFiles.takeFirst());
74         }
75
76         while(!m_filters.isEmpty())
77         {
78                 delete m_filters.takeFirst();
79         }
80
81         LAMEXP_DELETE(m_encoder);
82 }
83
84 void ProcessThread::run()
85 {
86         try
87         {
88                 processFile();
89         }
90         catch(...)
91         {
92                 fflush(stdout);
93                 fflush(stderr);
94                 fprintf(stderr, "\nGURU MEDITATION !!!\n");
95                 FatalAppExit(0, L"Unhandeled exception error, application will exit!");
96                 TerminateProcess(GetCurrentProcess(), -1);
97         }
98 }
99
100 void ProcessThread::processFile()
101 {
102         m_aborted = false;
103         bool bSuccess = true;
104                 
105         qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
106         emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
107
108         //Generate output file name
109         QString outFileName = generateOutFileName();
110         if(outFileName.isEmpty())
111         {
112                 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
113                 emit processStateFinished(m_jobId, outFileName, false);
114                 return;
115         }
116         
117         //Do we need Stereo downmix?
118         if(m_audioFile.formatAudioChannels() > 2 && m_encoder->requiresDownmix())
119         {
120                 m_filters.prepend(new DownmixFilter());
121         }
122
123         QString sourceFile = m_audioFile.filePath();
124
125         //Decode source file
126         if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion()))
127         {
128                 m_currentStep = DecodingStep;
129                 AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
130                 
131                 if(decoder)
132                 {
133                         QString tempFile = generateTempFileName();
134
135                         connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
136                         connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
137
138                         bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
139
140                         if(bSuccess)
141                         {
142                                 sourceFile = tempFile;
143                                 handleMessage("\n-------------------------------\n");
144                         }
145                 }
146                 else
147                 {
148                         handleMessage(QString("%1\n%2\n\n%3\t%4\n%5\t%6").arg(tr("The format of this file is NOT supported:"), m_audioFile.filePath(), tr("Container Format:"), m_audioFile.formatContainerInfo(), tr("Audio Format:"), m_audioFile.formatAudioCompressInfo()));
149                         emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
150                         emit processStateFinished(m_jobId, outFileName, false);
151                         return;
152                 }
153         }
154
155         //Apply all filters
156         while(!m_filters.isEmpty())
157         {
158                 QString tempFile = generateTempFileName();
159                 AbstractFilter *poFilter = m_filters.takeFirst();
160
161                 if(bSuccess)
162                 {
163                         connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
164                         connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
165
166                         m_currentStep = FilteringStep;
167                         bSuccess = poFilter->apply(sourceFile, tempFile, &m_aborted);
168
169                         if(bSuccess)
170                         {
171                                 sourceFile = tempFile;
172                                 handleMessage("\n-------------------------------\n");
173                         }
174                 }
175
176                 delete poFilter;
177         }
178
179         //Encode audio file
180         if(bSuccess)
181         {
182                 m_currentStep = EncodingStep;
183                 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
184         }
185
186         //Make sure output file exists
187         if(bSuccess)
188         {
189                 QFileInfo fileInfo(outFileName);
190                 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
191         }
192
193         //Report result
194         emit processStateChanged(m_jobId, (bSuccess ? tr("Done.") : (m_aborted ? tr("Aborted!") : tr("Failed!"))), (bSuccess ? ProgressModel::JobComplete : ProgressModel::JobFailed));
195         emit processStateFinished(m_jobId, outFileName, bSuccess);
196
197         qDebug("Process thread is done.");
198 }
199
200 ////////////////////////////////////////////////////////////
201 // SLOTS
202 ////////////////////////////////////////////////////////////
203
204 void ProcessThread::handleUpdate(int progress)
205 {
206         switch(m_currentStep)
207         {
208         case EncodingStep:
209                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
210                 break;
211         case FilteringStep:
212                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
213                 break;
214         case DecodingStep:
215                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
216                 break;
217         }
218 }
219
220 void ProcessThread::handleMessage(const QString &line)
221 {
222         emit processMessageLogged(m_jobId, line);
223 }
224
225 ////////////////////////////////////////////////////////////
226 // PRIVAE FUNCTIONS
227 ////////////////////////////////////////////////////////////
228
229 QString ProcessThread::generateOutFileName(void)
230 {
231         QMutexLocker lock(m_mutex_genFileName);
232         
233         int n = 1;
234
235         QFileInfo sourceFile(m_audioFile.filePath());
236         if(!sourceFile.exists() || !sourceFile.isFile())
237         {
238                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
239                 return QString();
240         }
241
242         QFile readTest(sourceFile.canonicalFilePath());
243         if(!readTest.open(QIODevice::ReadOnly))
244         {
245                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
246                 return QString();
247         }
248         else
249         {
250                 readTest.close();
251         }
252
253         QString baseName = sourceFile.completeBaseName();
254         QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
255
256         if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
257         {
258                 QDir rootDir = sourceFile.dir();
259                 while(!rootDir.isRoot())
260                 {
261                         if(!rootDir.cdUp()) break;
262                 }
263                 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
264         }
265         
266         if(!targetDir.exists())
267         {
268                 targetDir.mkpath(".");
269                 if(!targetDir.exists())
270                 {
271                         handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
272                         return QString();
273                 }
274         }
275         
276         QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
277         if(!writeTest.open(QIODevice::ReadWrite))
278         {
279                 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
280                 return QString();
281         }
282         else
283         {
284                 writeTest.close();
285                 writeTest.remove();
286         }
287
288         QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), baseName, m_encoder->extension());
289         while(QFileInfo(outFileName).exists())
290         {
291                 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), baseName, QString::number(++n), m_encoder->extension());
292         }
293
294         QFile placeholder(outFileName);
295         if(placeholder.open(QIODevice::WriteOnly))
296         {
297                 placeholder.close();
298         }
299
300         return outFileName;
301 }
302
303 QString ProcessThread::generateTempFileName(void)
304 {
305         QMutexLocker lock(m_mutex_genFileName);
306         QString tempFileName = QString("%1/%2.wav").arg(lamexp_temp_folder(), lamexp_rand_str());
307
308         while(QFileInfo(tempFileName).exists())
309         {
310                 tempFileName = QString("%1/%2.wav").arg(lamexp_temp_folder(), lamexp_rand_str());
311         }
312
313         QFile file(tempFileName);
314         if(file.open(QFile::ReadWrite))
315         {
316                 file.close();
317         }
318
319         m_tempFiles << tempFileName;
320         return tempFileName;
321 }
322
323 void ProcessThread::addFilter(AbstractFilter *filter)
324 {
325         m_filters.append(filter);
326 }
327
328 ////////////////////////////////////////////////////////////
329 // EVENTS
330 ////////////////////////////////////////////////////////////
331
332 /*NONE*/