1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Thread_Process.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 "Filter_Resample.h"
32 #include "Tool_WaveProperties.h"
33 #include "Registry_Decoder.h"
34 #include "Model_Settings.h"
40 #include <QMutexLocker>
47 #define DIFF(X,Y) ((X > Y) ? (X-Y) : (Y-X))
48 #define IS_WAVE(X) ((X.formatContainerType().compare("Wave", Qt::CaseInsensitive) == 0) && (X.formatAudioType().compare("PCM", Qt::CaseInsensitive) == 0))
49 #define STRDEF(STR,DEF) ((!STR.isEmpty()) ? STR : DEF)
51 QMutex
*ProcessThread::m_mutex_genFileName
= NULL
;
53 ////////////////////////////////////////////////////////////
55 ////////////////////////////////////////////////////////////
57 ProcessThread::ProcessThread(const AudioFileModel
&audioFile
, const QString
&outputDirectory
, const QString
&tempDirectory
, AbstractEncoder
*encoder
, const bool prependRelativeSourcePath
)
59 m_audioFile(audioFile
),
60 m_outputDirectory(outputDirectory
),
61 m_tempDirectory(tempDirectory
),
63 m_jobId(QUuid::createUuid()),
64 m_prependRelativeSourcePath(prependRelativeSourcePath
),
65 m_renamePattern("<BaseName>"),
67 m_propDetect(new WaveProperties())
69 if(m_mutex_genFileName
)
71 m_mutex_genFileName
= new QMutex
;
74 connect(m_encoder
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
75 connect(m_encoder
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
77 connect(m_propDetect
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
78 connect(m_propDetect
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
80 m_currentStep
= UnknownStep
;
83 ProcessThread::~ProcessThread(void)
85 while(!m_tempFiles
.isEmpty())
87 lamexp_remove_file(m_tempFiles
.takeFirst());
90 while(!m_filters
.isEmpty())
92 delete m_filters
.takeFirst();
95 LAMEXP_DELETE(m_encoder
);
96 LAMEXP_DELETE(m_propDetect
);
99 ////////////////////////////////////////////////////////////
100 // Thread Entry Point
101 ////////////////////////////////////////////////////////////
103 void ProcessThread::run()
113 fprintf(stderr
, "\nGURU MEDITATION !!!\n");
114 FatalAppExit(0, L
"Unhandeled exception error, application will exit!");
115 TerminateProcess(GetCurrentProcess(), -1);
119 void ProcessThread::processFile()
122 bool bSuccess
= true;
124 qDebug("Process thread %s has started.", m_jobId
.toString().toLatin1().constData());
125 emit
processStateInitialized(m_jobId
, QFileInfo(m_audioFile
.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning
);
126 handleMessage(QString().sprintf("LameXP v%u.%02u (Build #%u), compiled on %s at %s", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build(), lamexp_version_date().toString(Qt::ISODate
).toLatin1().constData(), lamexp_version_time()));
127 handleMessage("\n-------------------------------\n");
129 //Generate output file name
130 QString outFileName
= generateOutFileName();
131 if(outFileName
.isEmpty())
133 emit
processStateChanged(m_jobId
, tr("Not found!"), ProgressModel::JobFailed
);
134 emit
processStateFinished(m_jobId
, outFileName
, false);
138 QString sourceFile
= m_audioFile
.filePath();
143 if(!m_filters
.isEmpty() || !m_encoder
->isFormatSupported(m_audioFile
.formatContainerType(), m_audioFile
.formatContainerProfile(), m_audioFile
.formatAudioType(), m_audioFile
.formatAudioProfile(), m_audioFile
.formatAudioVersion()))
145 m_currentStep
= DecodingStep
;
146 AbstractDecoder
*decoder
= DecoderRegistry::lookup(m_audioFile
.formatContainerType(), m_audioFile
.formatContainerProfile(), m_audioFile
.formatAudioType(), m_audioFile
.formatAudioProfile(), m_audioFile
.formatAudioVersion());
150 QString tempFile
= generateTempFileName();
152 connect(decoder
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
153 connect(decoder
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
155 bSuccess
= decoder
->decode(sourceFile
, tempFile
, &m_aborted
);
156 LAMEXP_DELETE(decoder
);
160 sourceFile
= tempFile
;
161 m_audioFile
.setFormatContainerType(QString::fromLatin1("Wave"));
162 m_audioFile
.setFormatAudioType(QString::fromLatin1("PCM"));
164 if(QFileInfo(sourceFile
).size() >= 4294967296i64
)
166 handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
169 handleMessage("\n-------------------------------\n");
174 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()));
175 emit
processStateChanged(m_jobId
, tr("Unsupported!"), ProgressModel::JobFailed
);
176 emit
processStateFinished(m_jobId
, outFileName
, false);
181 //------------------------------------
182 //Update audio properties after decode
183 //------------------------------------
184 if(bSuccess
&& !m_aborted
&& IS_WAVE(m_audioFile
))
186 if(m_encoder
->supportedSamplerates() || m_encoder
->supportedBitdepths() || m_encoder
->supportedChannelCount() || !m_filters
.isEmpty())
188 m_currentStep
= AnalyzeStep
;
189 bSuccess
= m_propDetect
->detect(sourceFile
, &m_audioFile
, &m_aborted
);
193 handleMessage("\n-------------------------------\n");
195 //Do we need to take care if Stereo downmix?
196 if(m_encoder
->supportedChannelCount())
198 insertDownmixFilter();
201 //Do we need to take care of downsampling the input?
202 if(m_encoder
->supportedSamplerates() || m_encoder
->supportedBitdepths())
204 insertDownsampleFilter();
210 //-----------------------
211 //Apply all audio filters
212 //-----------------------
215 while(!m_filters
.isEmpty() && !m_aborted
)
217 QString tempFile
= generateTempFileName();
218 AbstractFilter
*poFilter
= m_filters
.takeFirst();
219 m_currentStep
= FilteringStep
;
221 connect(poFilter
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
222 connect(poFilter
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
224 if(poFilter
->apply(sourceFile
, tempFile
, &m_audioFile
, &m_aborted
))
226 sourceFile
= tempFile
;
229 handleMessage("\n-------------------------------\n");
237 if(bSuccess
&& !m_aborted
)
239 m_currentStep
= EncodingStep
;
240 bSuccess
= m_encoder
->encode(sourceFile
, m_audioFile
, outFileName
, &m_aborted
);
243 //Make sure output file exists
244 if(bSuccess
&& !m_aborted
)
246 QFileInfo
fileInfo(outFileName
);
247 bSuccess
= fileInfo
.exists() && fileInfo
.isFile() && (fileInfo
.size() > 0);
250 QThread::msleep(500);
253 emit
processStateChanged(m_jobId
, (m_aborted
? tr("Aborted!") : (bSuccess
? tr("Done.") : tr("Failed!"))), ((bSuccess
&& !m_aborted
) ? ProgressModel::JobComplete
: ProgressModel::JobFailed
));
254 emit
processStateFinished(m_jobId
, outFileName
, bSuccess
);
256 qDebug("Process thread is done.");
259 ////////////////////////////////////////////////////////////
261 ////////////////////////////////////////////////////////////
263 void ProcessThread::handleUpdate(int progress
)
265 //printf("Progress: %d\n", progress);
267 switch(m_currentStep
)
270 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress
)), ProgressModel::JobRunning
);
273 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress
)), ProgressModel::JobRunning
);
276 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress
)), ProgressModel::JobRunning
);
279 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress
)), ProgressModel::JobRunning
);
284 void ProcessThread::handleMessage(const QString
&line
)
286 emit
processMessageLogged(m_jobId
, line
);
289 ////////////////////////////////////////////////////////////
291 ////////////////////////////////////////////////////////////
293 QString
ProcessThread::generateOutFileName(void)
295 QMutexLocker
lock(m_mutex_genFileName
);
299 QFileInfo
sourceFile(m_audioFile
.filePath());
300 if(!sourceFile
.exists() || !sourceFile
.isFile())
302 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile
.absoluteFilePath()));
306 QFile
readTest(sourceFile
.canonicalFilePath());
307 if(!readTest
.open(QIODevice::ReadOnly
))
309 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest
.fileName()));
317 QString baseName
= sourceFile
.completeBaseName();
318 QDir
targetDir(m_outputDirectory
.isEmpty() ? sourceFile
.canonicalPath() : m_outputDirectory
);
320 if(m_prependRelativeSourcePath
&& !m_outputDirectory
.isEmpty())
322 QDir rootDir
= sourceFile
.dir();
323 while(!rootDir
.isRoot())
325 if(!rootDir
.cdUp()) break;
327 targetDir
.setPath(QString("%1/%2").arg(targetDir
.absolutePath(), QFileInfo(rootDir
.relativeFilePath(sourceFile
.canonicalFilePath())).path()));
330 if(!targetDir
.exists())
332 targetDir
.mkpath(".");
333 if(!targetDir
.exists())
335 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir
.absolutePath()));
340 QFile
writeTest(QString("%1/.%2").arg(targetDir
.canonicalPath(), lamexp_rand_str()));
341 if(!writeTest
.open(QIODevice::ReadWrite
))
343 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir
.absolutePath()));
352 QString fileName
= m_renamePattern
;
353 fileName
.replace("<BaseName>", STRDEF(baseName
, tr("Unknown File Name")), Qt::CaseInsensitive
);
354 fileName
.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile
.filePosition()), Qt::CaseInsensitive
);
355 fileName
.replace("<Title>", STRDEF(m_audioFile
.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive
);
356 fileName
.replace("<Artist>", STRDEF(m_audioFile
.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive
);
357 fileName
.replace("<Album>", STRDEF(m_audioFile
.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive
);
358 fileName
.replace("<Year>", QString().sprintf("%04d", m_audioFile
.fileYear()), Qt::CaseInsensitive
);
359 fileName
.replace("<Comment>", STRDEF(m_audioFile
.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive
);
360 fileName
= lamexp_clean_filename(fileName
).simplified();
362 QString outFileName
= QString("%1/%2.%3").arg(targetDir
.canonicalPath(), fileName
, m_encoder
->extension());
363 while(QFileInfo(outFileName
).exists())
365 outFileName
= QString("%1/%2 (%3).%4").arg(targetDir
.canonicalPath(), fileName
, QString::number(++n
), m_encoder
->extension());
368 QFile
placeholder(outFileName
);
369 if(placeholder
.open(QIODevice::WriteOnly
))
377 QString
ProcessThread::generateTempFileName(void)
379 QMutexLocker
lock(m_mutex_genFileName
);
380 QString tempFileName
= QString("%1/%2.wav").arg(m_tempDirectory
, lamexp_rand_str());
382 while(QFileInfo(tempFileName
).exists())
384 tempFileName
= QString("%1/%2.wav").arg(m_tempDirectory
, lamexp_rand_str());
387 QFile
file(tempFileName
);
388 if(file
.open(QFile::ReadWrite
))
393 m_tempFiles
<< tempFileName
;
397 void ProcessThread::insertDownsampleFilter(void)
399 int targetSampleRate
= 0;
400 int targetBitDepth
= 0;
402 /* Adjust sample rate */
403 if(m_encoder
->supportedSamplerates() && m_audioFile
.formatAudioSamplerate())
405 bool applyDownsampling
= true;
407 //Check if downsampling filter is already in the chain
408 for(int i
= 0; i
< m_filters
.count(); i
++)
410 if(dynamic_cast<ResampleFilter
*>(m_filters
.at(i
)))
412 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
413 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
414 applyDownsampling
= false;
418 //Now determine the target sample rate, if required
419 if(applyDownsampling
)
421 const unsigned int *supportedRates
= m_encoder
->supportedSamplerates();
422 const unsigned int inputRate
= m_audioFile
.formatAudioSamplerate();
423 unsigned int currentDiff
= UINT_MAX
, minimumDiff
= UINT_MAX
, bestRate
= UINT_MAX
;
425 //Find the most suitable supported sampling rate
426 for(int i
= 0; supportedRates
[i
]; i
++)
428 currentDiff
= DIFF(inputRate
, supportedRates
[i
]);
429 if((currentDiff
< minimumDiff
) || ((currentDiff
== minimumDiff
) && (bestRate
< supportedRates
[i
])))
431 bestRate
= supportedRates
[i
];
432 minimumDiff
= currentDiff
;
433 if(!(minimumDiff
> 0)) break;
437 if(bestRate
!= inputRate
)
439 targetSampleRate
= (bestRate
!= UINT_MAX
) ? bestRate
: supportedRates
[0];
444 /* Adjust bit depth (word size) */
445 if(m_encoder
->supportedBitdepths() && m_audioFile
.formatAudioBitdepth())
447 const unsigned int *supportedBPS
= m_encoder
->supportedBitdepths();
448 const unsigned int inputBPS
= m_audioFile
.formatAudioBitdepth();
449 unsigned int currentDiff
= UINT_MAX
, minimumDiff
= UINT_MAX
, bestBPS
= UINT_MAX
;
451 //Find the most suitable supported bit depth
452 for(int i
= 0; supportedBPS
[i
]; i
++)
454 currentDiff
= DIFF(inputBPS
, supportedBPS
[i
]);
455 if((currentDiff
< minimumDiff
) || ((currentDiff
== minimumDiff
) && (bestBPS
< supportedBPS
[i
])))
457 bestBPS
= supportedBPS
[i
];
458 minimumDiff
= currentDiff
;
459 if(!(minimumDiff
> 0)) break;
463 if(bestBPS
!= inputBPS
)
465 targetBitDepth
= (bestBPS
!= UINT_MAX
) ? bestBPS
: supportedBPS
[0];
469 /* Insert the filter */
470 if(targetSampleRate
|| targetBitDepth
)
472 m_filters
.append(new ResampleFilter(targetSampleRate
, targetBitDepth
));
476 void ProcessThread::insertDownmixFilter(void)
478 bool applyDownmixing
= true;
480 //Check if downmixing filter is already in the chain
481 for(int i
= 0; i
< m_filters
.count(); i
++)
483 if(dynamic_cast<DownmixFilter
*>(m_filters
.at(i
)))
485 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
486 handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
487 applyDownmixing
= false;
491 //Now add the downmixing filter, if needed
494 bool requiresDownmix
= true;
495 const unsigned int *supportedChannels
= m_encoder
->supportedChannelCount();
496 unsigned int channels
= m_audioFile
.formatAudioChannels();
498 for(int i
= 0; supportedChannels
[i
]; i
++)
500 if(supportedChannels
[i
] == channels
)
502 requiresDownmix
= false;
509 m_filters
.append(new DownmixFilter());
514 ////////////////////////////////////////////////////////////
516 ////////////////////////////////////////////////////////////
518 void ProcessThread::addFilter(AbstractFilter
*filter
)
520 m_filters
.append(filter
);
523 void ProcessThread::setRenamePattern(const QString
&pattern
)
525 QString newPattern
= pattern
.simplified();
526 if(!newPattern
.isEmpty()) m_renamePattern
= newPattern
;
529 ////////////////////////////////////////////////////////////
531 ////////////////////////////////////////////////////////////