1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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_FileAnalyzer.h"
25 #include "LockedFile.h"
26 #include "Model_AudioFile.h"
27 #include "PlaylistImporter.h"
38 ////////////////////////////////////////////////////////////
40 ////////////////////////////////////////////////////////////
42 FileAnalyzer::FileAnalyzer(const QStringList &inputFiles)
44 m_inputFiles(inputFiles),
45 m_mediaInfoBin(lamexp_lookup_tool("mediainfo.exe"))
49 if(m_mediaInfoBin.isEmpty())
51 qFatal("Invalid path to MediaInfo binary. Tool not initialized properly.");
60 ////////////////////////////////////////////////////////////
62 ////////////////////////////////////////////////////////////
64 void FileAnalyzer::run()
74 GetAsyncKeyState(VK_ESCAPE);
76 while(!m_inputFiles.isEmpty())
78 if(GetAsyncKeyState(VK_ESCAPE) & 0x0001)
80 MessageBeep(MB_ICONERROR);
81 qWarning("Operation cancelled by user!");
85 QString currentFile = QDir::fromNativeSeparators(m_inputFiles.takeFirst());
86 qDebug64("Analyzing: %1", currentFile);
87 emit fileSelected(QFileInfo(currentFile).fileName());
88 AudioFileModel file = analyzeFile(currentFile);
90 if(file.fileName().isEmpty() || file.formatContainerType().isEmpty() || file.formatAudioType().isEmpty())
92 if(!PlaylistImporter::importPlaylist(m_inputFiles, currentFile))
95 qDebug64("Skipped: %1", file.filePath());
101 emit fileAnalyzed(file);
104 qDebug("All files added.\n");
108 ////////////////////////////////////////////////////////////
110 ////////////////////////////////////////////////////////////
112 const AudioFileModel FileAnalyzer::analyzeFile(const QString &filePath)
114 AudioFileModel audioFile(filePath);
115 m_currentSection = sectionOther;
116 m_currentCover = coverNone;
117 m_lineBreakBugWorkaround = false;
119 QFile readTest(filePath);
120 if(!readTest.open(QIODevice::ReadOnly))
122 qWarning("Cannot access file for reading, skipping!");
127 if(checkFile_CDDA(readTest))
129 qWarning("Dummy CDDA file detected, skipping!");
137 process.setProcessChannelMode(QProcess::MergedChannels);
138 process.setReadChannel(QProcess::StandardOutput);
139 process.start(m_mediaInfoBin, QStringList() << QDir::toNativeSeparators(filePath));
141 if(!process.waitForStarted())
143 qWarning("MediaInfo process failed to create!");
144 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
146 process.waitForFinished(-1);
150 while(process.state() != QProcess::NotRunning)
152 if(!process.waitForReadyRead())
154 if(process.state() == QProcess::Running)
156 qWarning("MediaInfo time out. Killing process and skipping file!");
158 process.waitForFinished(-1);
165 while(process.canReadLine())
167 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
170 int index = line.indexOf(':');
173 m_lineBreakBugWorkaround = false;
174 QString key = line.left(index-1).trimmed();
175 QString val = line.mid(index+1).trimmed();
176 if(!key.isEmpty() && !val.isEmpty())
178 updateInfo(audioFile, key, val);
189 if(audioFile.fileName().isEmpty())
191 QString baseName = QFileInfo(filePath).fileName();
192 int index = baseName.lastIndexOf(".");
196 baseName = baseName.left(index);
199 baseName = baseName.replace("_", " ").simplified();
200 index = baseName.lastIndexOf(" - ");
204 baseName = baseName.mid(index + 3).trimmed();
207 audioFile.setFileName(baseName);
210 if(m_currentCover != coverNone)
212 retrieveCover(audioFile, filePath);
218 void FileAnalyzer::updateSection(const QString §ion)
220 if(section.startsWith("General", Qt::CaseInsensitive))
222 m_currentSection = sectionGeneral;
224 else if(!section.compare("Audio", Qt::CaseInsensitive) || section.startsWith("Audio #1", Qt::CaseInsensitive))
226 m_currentSection = sectionAudio;
228 else if(section.startsWith("Audio", Qt::CaseInsensitive) || section.startsWith("Video", Qt::CaseInsensitive) || section.startsWith("Text", Qt::CaseInsensitive) ||
229 section.startsWith("Menu", Qt::CaseInsensitive) || section.startsWith("Image", Qt::CaseInsensitive) || section.startsWith("Chapters", Qt::CaseInsensitive))
231 m_currentSection = sectionOther;
235 if(!m_lineBreakBugWorkaround)
237 m_currentSection = sectionOther;
238 qWarning("Unknown section: %s", section.toUtf8().constData());
243 void FileAnalyzer::updateInfo(AudioFileModel &audioFile, const QString &key, const QString &value)
245 switch(m_currentSection)
248 if(!key.compare("Title", Qt::CaseInsensitive) || !key.compare("Track", Qt::CaseInsensitive) || !key.compare("Track Name", Qt::CaseInsensitive))
250 if(audioFile.fileName().isEmpty()) audioFile.setFileName(value);
252 else if(!key.compare("Duration", Qt::CaseInsensitive))
254 if(!audioFile.fileDuration()) audioFile.setFileDuration(parseDuration(value));
256 else if(!key.compare("Artist", Qt::CaseInsensitive) || !key.compare("Performer", Qt::CaseInsensitive))
258 if(audioFile.fileArtist().isEmpty()) audioFile.setFileArtist(value);
260 else if(!key.compare("Album", Qt::CaseInsensitive))
262 if(audioFile.fileAlbum().isEmpty()) audioFile.setFileAlbum(value);
264 else if(!key.compare("Genre", Qt::CaseInsensitive))
266 if(audioFile.fileGenre().isEmpty()) audioFile.setFileGenre(value);
268 else if(!key.compare("Year", Qt::CaseInsensitive) || !key.compare("Recorded Date", Qt::CaseInsensitive) || !key.compare("Encoded Date", Qt::CaseInsensitive))
270 if(!audioFile.fileYear()) audioFile.setFileYear(parseYear(value));
272 else if(!key.compare("Comment", Qt::CaseInsensitive))
274 if(audioFile.fileComment().isEmpty()) audioFile.setFileComment(value);
276 else if(!key.compare("Track Name/Position", Qt::CaseInsensitive))
278 if(!audioFile.filePosition()) audioFile.setFilePosition(value.toInt());
280 else if(!key.compare("Format", Qt::CaseInsensitive))
282 if(audioFile.formatContainerType().isEmpty()) audioFile.setFormatContainerType(value);
284 else if(!key.compare("Format Profile", Qt::CaseInsensitive))
286 if(audioFile.formatContainerProfile().isEmpty()) audioFile.setFormatContainerProfile(value);
288 else if(!key.compare("Cover", Qt::CaseInsensitive) || !key.compare("Cover type", Qt::CaseInsensitive))
290 if(m_currentCover == coverNone) m_currentCover = coverJpeg;
292 else if(!key.compare("Cover MIME", Qt::CaseInsensitive))
294 QString temp = value.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive).first();
295 if(!temp.compare("image/jpeg", Qt::CaseInsensitive))
297 m_currentCover = coverJpeg;
299 else if(!temp.compare("image/png", Qt::CaseInsensitive))
301 m_currentCover = coverPng;
303 else if(!temp.compare("image/gif", Qt::CaseInsensitive))
305 m_currentCover = coverGif;
308 else if(!key.compare("Complete Name", Qt::CaseInsensitive))
310 m_lineBreakBugWorkaround = true;
315 if(!key.compare("Year", Qt::CaseInsensitive) || !key.compare("Recorded Date", Qt::CaseInsensitive) || !key.compare("Encoded Date", Qt::CaseInsensitive))
317 if(!audioFile.fileYear()) audioFile.setFileYear(parseYear(value));
319 else if(!key.compare("Format", Qt::CaseInsensitive))
321 if(audioFile.formatAudioType().isEmpty()) audioFile.setFormatAudioType(value);
323 else if(!key.compare("Format Profile", Qt::CaseInsensitive))
325 if(audioFile.formatAudioProfile().isEmpty()) audioFile.setFormatAudioProfile(value);
327 else if(!key.compare("Format Version", Qt::CaseInsensitive))
329 if(audioFile.formatAudioVersion().isEmpty()) audioFile.setFormatAudioVersion(value);
331 else if(!key.compare("Channel(s)", Qt::CaseInsensitive))
333 if(!audioFile.formatAudioChannels()) audioFile.setFormatAudioChannels(value.split(" ", QString::SkipEmptyParts).first().toInt());
335 else if(!key.compare("Sampling rate", Qt::CaseInsensitive))
337 if(!audioFile.formatAudioSamplerate()) audioFile.setFormatAudioSamplerate(ceil(value.split(" ", QString::SkipEmptyParts).first().toFloat() * 1000.0f));
339 else if(!key.compare("Bit depth", Qt::CaseInsensitive))
341 if(!audioFile.formatAudioBitdepth()) audioFile.setFormatAudioBitdepth(value.split(" ", QString::SkipEmptyParts).first().toInt());
343 else if(!key.compare("Duration", Qt::CaseInsensitive))
345 if(!audioFile.fileDuration()) audioFile.setFileDuration(parseDuration(value));
351 unsigned int FileAnalyzer::parseYear(const QString &str)
353 if(str.startsWith("UTC", Qt::CaseInsensitive))
355 QDate date = QDate::fromString(str.mid(3).trimmed().left(10), "yyyy-MM-dd");
368 int year = str.toInt(&ok);
380 unsigned int FileAnalyzer::parseDuration(const QString &str)
384 time = QTime::fromString(str, "z'ms'");
387 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
390 time = QTime::fromString(str, "s's 'z'ms'");
393 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
396 time = QTime::fromString(str, "m'mn 's's'");
399 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
402 time = QTime::fromString(str, "h'h 'm'mn'");
405 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
411 bool FileAnalyzer::checkFile_CDDA(QFile &file)
414 QByteArray data = file.read(128);
416 int i = data.indexOf("RIFF");
417 int j = data.indexOf("CDDA");
418 int k = data.indexOf("fmt ");
420 return ((i >= 0) && (j >= 0) && (k >= 0) && (k > j) && (j > i));
423 void FileAnalyzer::retrieveCover(AudioFileModel &audioFile, const QString &filePath)
425 qDebug64("Retrieving cover from: %1", filePath);
428 switch(m_currentCover)
431 extension = QString::fromLatin1("png");
434 extension = QString::fromLatin1("gif");
437 extension = QString::fromLatin1("jpg");
442 process.setProcessChannelMode(QProcess::MergedChannels);
443 process.setReadChannel(QProcess::StandardOutput);
444 process.start(m_mediaInfoBin, QStringList() << "-f" << QDir::toNativeSeparators(filePath));
446 if(!process.waitForStarted())
448 qWarning("MediaInfo process failed to create!");
449 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
451 process.waitForFinished(-1);
455 while(process.state() != QProcess::NotRunning)
457 if(!process.waitForReadyRead())
459 if(process.state() == QProcess::Running)
461 qWarning("MediaInfo time out. Killing process and skipping file!");
463 process.waitForFinished(-1);
468 while(process.canReadLine())
470 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
473 int index = line.indexOf(':');
476 QString key = line.left(index-1).trimmed();
477 QString val = line.mid(index+1).trimmed();
478 if(!key.isEmpty() && !val.isEmpty())
480 if(!key.compare("Cover_Data", Qt::CaseInsensitive))
482 if(val.indexOf(" ") > 0)
484 val = val.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive).first();
486 QByteArray coverData = QByteArray::fromBase64(val.toLatin1());
487 QFile coverFile(QString("%1/%2.%3").arg(lamexp_temp_folder2(), lamexp_rand_str(), extension));
488 if(coverFile.open(QIODevice::WriteOnly))
490 coverFile.write(coverData);
492 audioFile.setFileCover(coverFile.fileName(), true);
503 ////////////////////////////////////////////////////////////
505 ////////////////////////////////////////////////////////////
507 unsigned int FileAnalyzer::filesAccepted(void)
509 return m_filesAccepted;
512 unsigned int FileAnalyzer::filesRejected(void)
514 return max(m_filesRejected - (m_filesDenied + m_filesDummyCDDA), 0);
517 unsigned int FileAnalyzer::filesDenied(void)
519 return m_filesDenied;
522 unsigned int FileAnalyzer::filesDummyCDDA(void)
524 return m_filesDummyCDDA;
527 ////////////////////////////////////////////////////////////
529 ////////////////////////////////////////////////////////////