Monkey's Audio: Don't call "tag" program, if there is *no* meta-data to be embedded...
[LameXP.git] / src / Thread_FileAnalyzer.cpp
blobe5f123fd54ee4455f30498d47e191110823d9604
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 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, 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 "Thread_FileAnalyzer.h"
25 //Internal
26 #include "Global.h"
27 #include "LockedFile.h"
28 #include "Model_AudioFile.h"
29 #include "Thread_FileAnalyzer_Task.h"
30 #include "PlaylistImporter.h"
32 //MUtils
33 #include <MUtils/Global.h>
34 #include <MUtils/Exception.h>
36 //Qt
37 #include <QDir>
38 #include <QFileInfo>
39 #include <QProcess>
40 #include <QDate>
41 #include <QTime>
42 #include <QDebug>
43 #include <QImage>
44 #include <QThreadPool>
45 #include <QTime>
46 #include <QElapsedTimer>
47 #include <QTimer>
48 #include <QQueue>
50 //Insert into QStringList *without* duplicates
51 static inline void SAFE_APPEND_STRING(QStringList &list, const QString &str)
53 if(!list.contains(str, Qt::CaseInsensitive))
55 list << str;
59 ////////////////////////////////////////////////////////////
60 // Constructor
61 ////////////////////////////////////////////////////////////
63 FileAnalyzer::FileAnalyzer(const QStringList &inputFiles)
65 m_tasksCounterNext(0),
66 m_tasksCounterDone(0),
67 m_inputFiles(inputFiles),
68 m_templateFile(NULL),
69 m_pool(NULL)
71 m_bSuccess = false;
72 m_bAborted = false;
74 m_filesAccepted = 0;
75 m_filesRejected = 0;
76 m_filesDenied = 0;
77 m_filesDummyCDDA = 0;
78 m_filesCueSheet = 0;
80 moveToThread(this); /*makes sure queued slots are executed in the proper thread context*/
82 m_timer = new QElapsedTimer;
85 FileAnalyzer::~FileAnalyzer(void)
87 if(m_pool)
89 if(!m_pool->waitForDone(2500))
91 qWarning("There are still running tasks in the thread pool!");
95 MUTILS_DELETE(m_templateFile);
96 MUTILS_DELETE(m_pool);
97 MUTILS_DELETE(m_timer);
100 ////////////////////////////////////////////////////////////
101 // Static data
102 ////////////////////////////////////////////////////////////
104 const char *FileAnalyzer::g_tags_gen[] =
106 "ID",
107 "Format",
108 "Format_Profile",
109 "Format_Version",
110 "Duration",
111 "Title", "Track",
112 "Track/Position",
113 "Artist", "Performer",
114 "Album",
115 "Genre",
116 "Released_Date", "Recorded_Date",
117 "Comment",
118 "Cover",
119 "Cover_Type",
120 "Cover_Mime",
121 "Cover_Data",
122 NULL
125 const char *FileAnalyzer::g_tags_aud[] =
127 "ID",
128 "Source",
129 "Format",
130 "Format_Profile",
131 "Format_Version",
132 "Channel(s)",
133 "SamplingRate",
134 "BitDepth",
135 "BitRate",
136 "BitRate_Mode",
137 "Encoded_Library",
138 NULL
141 ////////////////////////////////////////////////////////////
142 // Thread Main
143 ////////////////////////////////////////////////////////////
145 void FileAnalyzer::run()
147 m_bSuccess = false;
149 m_tasksCounterNext = 0;
150 m_tasksCounterDone = 0;
151 m_completedCounter = 0;
153 m_completedFiles.clear();
154 m_completedTaskIds.clear();
155 m_runningTaskIds.clear();
157 m_filesAccepted = 0;
158 m_filesRejected = 0;
159 m_filesDenied = 0;
160 m_filesDummyCDDA = 0;
161 m_filesCueSheet = 0;
163 m_timer->invalidate();
165 //Create MediaInfo template file
166 if(!m_templateFile)
168 if(!createTemplate())
170 qWarning("Failed to create template file!");
171 return;
175 //Sort files
176 MUtils::natural_string_sort(m_inputFiles, true);
178 //Handle playlist files first!
179 handlePlaylistFiles();
181 const unsigned int nFiles = m_inputFiles.count();
182 if(nFiles < 1)
184 qWarning("File list is empty, nothing to do!");
185 return;
188 //Update progress
189 emit progressMaxChanged(nFiles);
190 emit progressValChanged(0);
192 //Create thread pool
193 if(!m_pool) m_pool = new QThreadPool();
194 const int idealThreadCount = QThread::idealThreadCount();
195 if(idealThreadCount > 0)
197 m_pool->setMaxThreadCount(qBound(2, ((idealThreadCount * 3) / 2), 12));
200 //Start first N threads
201 QTimer::singleShot(0, this, SLOT(initializeTasks()));
203 //Start event processing
204 this->exec();
206 //Wait for pending tasks to complete
207 m_pool->waitForDone();
209 //Was opertaion aborted?
210 if(m_bAborted)
212 qWarning("Operation cancelled by user!");
213 return;
216 //Update progress
217 emit progressValChanged(nFiles);
219 //Emit pending files (this should not be required though!)
220 if(!m_completedFiles.isEmpty())
222 qWarning("FileAnalyzer: Pending file information found after last thread terminated!");
223 QList<unsigned int> keys = m_completedFiles.keys(); qSort(keys);
224 while(!keys.isEmpty())
226 emit fileAnalyzed(m_completedFiles.take(keys.takeFirst()));
230 qDebug("All files added.\n");
231 m_bSuccess = true;
233 QThread::msleep(333);
236 ////////////////////////////////////////////////////////////
237 // Privtae Functions
238 ////////////////////////////////////////////////////////////
240 bool FileAnalyzer::analyzeNextFile(void)
242 if(!(m_inputFiles.isEmpty() || m_bAborted))
244 const unsigned int taskId = m_tasksCounterNext++;
245 const QString currentFile = QDir::fromNativeSeparators(m_inputFiles.takeFirst());
247 if((!m_timer->isValid()) || (m_timer->elapsed() >= 333))
249 emit fileSelected(QFileInfo(currentFile).fileName());
250 m_timer->restart();
253 AnalyzeTask *task = new AnalyzeTask(taskId, currentFile, m_templateFile->filePath(), &m_bAborted);
254 connect(task, SIGNAL(fileAnalyzed(const unsigned int, const int, AudioFileModel)), this, SLOT(taskFileAnalyzed(unsigned int, const int, AudioFileModel)), Qt::QueuedConnection);
255 connect(task, SIGNAL(taskCompleted(const unsigned int)), this, SLOT(taskThreadFinish(const unsigned int)), Qt::QueuedConnection);
256 m_runningTaskIds.insert(taskId); m_pool->start(task);
258 return true;
261 return false;
264 void FileAnalyzer::handlePlaylistFiles(void)
266 QQueue<QVariant> queue;
267 QStringList importedFromPlaylist;
269 //Import playlist files into "hierarchical" list
270 while(!m_inputFiles.isEmpty())
272 const QString currentFile = m_inputFiles.takeFirst();
273 QStringList importedFiles;
274 if(PlaylistImporter::importPlaylist(importedFiles, currentFile))
276 queue.enqueue(importedFiles);
277 importedFromPlaylist << importedFiles;
279 else
281 queue.enqueue(currentFile);
285 //Reduce temporary list
286 importedFromPlaylist.removeDuplicates();
288 //Now build the complete "flat" file list (files imported from playlist take precedence!)
289 while(!queue.isEmpty())
291 const QVariant current = queue.dequeue();
292 if(current.type() == QVariant::String)
294 const QString temp = current.toString();
295 if(!importedFromPlaylist.contains(temp, Qt::CaseInsensitive))
297 SAFE_APPEND_STRING(m_inputFiles, temp);
300 else if(current.type() == QVariant::StringList)
302 const QStringList temp = current.toStringList();
303 for(QStringList::ConstIterator iter = temp.constBegin(); iter != temp.constEnd(); iter++)
305 SAFE_APPEND_STRING(m_inputFiles, (*iter));
308 else
310 qWarning("Encountered an unexpected variant type!");
315 bool FileAnalyzer::createTemplate(void)
317 if(m_templateFile)
319 qWarning("Template file already exists!");
320 return true;
323 QString templatePath = QString("%1/%2.txt").arg(MUtils::temp_folder(), MUtils::rand_str());
325 QFile templateFile(templatePath);
326 if(!templateFile.open(QIODevice::WriteOnly))
328 return false;
331 templateFile.write("General;");
332 for(size_t i = 0; g_tags_gen[i]; i++)
334 templateFile.write(QString("Gen_%1=%%1%\\n").arg(g_tags_gen[i]).toLatin1().constData());
336 templateFile.write("\\n\r\n");
338 templateFile.write("Audio;");
339 for(size_t i = 0; g_tags_aud[i]; i++)
341 templateFile.write(QString("Aud_%1=%%1%\\n").arg(g_tags_aud[i]).toLatin1().constData());
343 templateFile.write("\\n\r\n");
345 bool success = (templateFile.error() == QFile::NoError);
346 templateFile.close();
348 if(!success)
350 QFile::remove(templatePath);
351 return false;
356 m_templateFile = new LockedFile(templatePath, true);
358 catch(const std::exception &error)
360 qWarning("Failed to lock template file:\n%s\n", error.what());
361 return false;
363 catch(...)
365 qWarning("Failed to lock template file!");
366 return false;
369 return true;
372 ////////////////////////////////////////////////////////////
373 // Slot Functions
374 ////////////////////////////////////////////////////////////
376 void FileAnalyzer::initializeTasks(void)
378 for(int i = 0; i < m_pool->maxThreadCount(); i++)
380 if(!analyzeNextFile()) break;
384 void FileAnalyzer::taskFileAnalyzed(const unsigned int taskId, const int fileType, const AudioFileModel &file)
386 m_completedTaskIds.insert(taskId);
388 switch(fileType)
390 case AnalyzeTask::fileTypeNormal:
391 m_filesAccepted++;
392 if(m_tasksCounterDone == taskId)
394 emit fileAnalyzed(file);
395 m_tasksCounterDone++;
397 else
399 m_completedFiles.insert(taskId, file);
401 break;
402 case AnalyzeTask::fileTypeCDDA:
403 m_filesDummyCDDA++;
404 break;
405 case AnalyzeTask::fileTypeDenied:
406 m_filesDenied++;
407 break;
408 case AnalyzeTask::fileTypeCueSheet:
409 m_filesCueSheet++;
410 break;
411 case AnalyzeTask::fileTypeUnknown:
412 m_filesRejected++;
413 break;
414 default:
415 MUTILS_THROW("Unknown file type identifier!");
418 //Emit all pending files
419 while(m_completedTaskIds.contains(m_tasksCounterDone))
421 if(m_completedFiles.contains(m_tasksCounterDone))
423 emit fileAnalyzed(m_completedFiles.take(m_tasksCounterDone));
425 m_completedTaskIds.remove(m_tasksCounterDone);
426 m_tasksCounterDone++;
430 void FileAnalyzer::taskThreadFinish(const unsigned int taskId)
432 m_runningTaskIds.remove(taskId);
433 emit progressValChanged(++m_completedCounter);
435 if(!analyzeNextFile())
437 if(m_runningTaskIds.empty())
439 QTimer::singleShot(0, this, SLOT(quit())); //Stop event processing, if all threads have completed!
444 ////////////////////////////////////////////////////////////
445 // Public Functions
446 ////////////////////////////////////////////////////////////
448 unsigned int FileAnalyzer::filesAccepted(void)
450 return m_filesAccepted;
453 unsigned int FileAnalyzer::filesRejected(void)
455 return m_filesRejected;
458 unsigned int FileAnalyzer::filesDenied(void)
460 return m_filesDenied;
463 unsigned int FileAnalyzer::filesDummyCDDA(void)
465 return m_filesDummyCDDA;
468 unsigned int FileAnalyzer::filesCueSheet(void)
470 return m_filesCueSheet;
473 ////////////////////////////////////////////////////////////
474 // EVENTS
475 ////////////////////////////////////////////////////////////
477 /*NONE*/