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"
37 ////////////////////////////////////////////////////////////
39 ////////////////////////////////////////////////////////////
41 FileAnalyzer::FileAnalyzer(const QStringList &inputFiles)
43 m_inputFiles(inputFiles),
44 m_mediaInfoBin_x86(lamexp_lookup_tool("mediainfo_i386.exe")),
45 m_mediaInfoBin_x64(lamexp_lookup_tool("mediainfo_x64.exe"))
49 if(m_mediaInfoBin_x86.isEmpty() || m_mediaInfoBin_x64.isEmpty())
51 qFatal("Invalid path to MediaInfo binary. Tool not initialized properly.");
59 ////////////////////////////////////////////////////////////
61 ////////////////////////////////////////////////////////////
63 void FileAnalyzer::run()
73 while(!m_inputFiles.isEmpty())
75 QString currentFile = QDir::fromNativeSeparators(m_inputFiles.takeFirst());
76 qDebug("Analyzing: %s", currentFile.toUtf8().constData());
77 emit fileSelected(QFileInfo(currentFile).fileName());
78 AudioFileModel file = analyzeFile(currentFile);
79 if(file.fileName().isEmpty() || file.formatContainerType().isEmpty() || file.formatAudioType().isEmpty())
81 if(!importPlaylist(m_inputFiles, currentFile))
84 qDebug("Skipped: %s", file.filePath().toUtf8().constData());
89 emit fileAnalyzed(file);
92 qDebug("All files added.\n");
96 ////////////////////////////////////////////////////////////
98 ////////////////////////////////////////////////////////////
100 const AudioFileModel FileAnalyzer::analyzeFile(const QString &filePath)
102 lamexp_cpu_t cpuInfo = lamexp_detect_cpu_features();
103 const QString mediaInfoBin = cpuInfo.x64 ? m_mediaInfoBin_x64 : m_mediaInfoBin_x86;
105 AudioFileModel audioFile(filePath);
106 m_currentSection = sectionOther;
108 QFile readTest(filePath);
109 if(!readTest.open(QIODevice::ReadOnly))
111 qWarning("Cannot access file for reading, skipping!");
121 process.setProcessChannelMode(QProcess::MergedChannels);
122 process.setReadChannel(QProcess::StandardOutput);
123 process.start(mediaInfoBin, QStringList() << QDir::toNativeSeparators(filePath));
125 if(!process.waitForStarted())
127 qWarning("MediaInfo process failed to create!");
128 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
130 process.waitForFinished(-1);
134 while(process.state() != QProcess::NotRunning)
136 if(!process.waitForReadyRead())
138 if(process.state() == QProcess::Running)
140 qWarning("MediaInfo time out. Killing process and skipping file!");
142 process.waitForFinished(-1);
149 while(process.canReadLine())
151 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
154 int index = line.indexOf(':');
157 QString key = line.left(index-1).trimmed();
158 QString val = line.mid(index+1).trimmed();
159 if(!key.isEmpty() && !val.isEmpty())
161 updateInfo(audioFile, key, val);
172 if(audioFile.fileName().isEmpty())
174 QString baseName = QFileInfo(filePath).fileName();
175 int index = baseName.lastIndexOf(".");
179 baseName = baseName.left(index);
182 baseName = baseName.replace("_", " ").simplified();
183 index = baseName.lastIndexOf(" - ");
187 baseName = baseName.mid(index + 3).trimmed();
190 audioFile.setFileName(baseName);
196 void FileAnalyzer::updateSection(const QString §ion)
198 if(section.startsWith("General", Qt::CaseInsensitive))
200 m_currentSection = sectionGeneral;
202 else if(!section.compare("Audio", Qt::CaseInsensitive) || section.startsWith("Audio #1", Qt::CaseInsensitive))
204 m_currentSection = sectionAudio;
206 else if(section.startsWith("Audio", Qt::CaseInsensitive) || section.startsWith("Video", Qt::CaseInsensitive) || section.startsWith("Text", Qt::CaseInsensitive) ||
207 section.startsWith("Menu", Qt::CaseInsensitive) || section.startsWith("Image", Qt::CaseInsensitive) || section.startsWith("Chapters", Qt::CaseInsensitive))
209 m_currentSection = sectionOther;
213 qWarning("Unknown section: %s", section.toUtf8().constData());
217 void FileAnalyzer::updateInfo(AudioFileModel &audioFile, const QString &key, const QString &value)
219 switch(m_currentSection)
222 if(!key.compare("Title", Qt::CaseInsensitive) || !key.compare("Track", Qt::CaseInsensitive) || !key.compare("Track Name", Qt::CaseInsensitive))
224 if(audioFile.fileName().isEmpty()) audioFile.setFileName(value);
226 else if(!key.compare("Duration", Qt::CaseInsensitive))
228 if(!audioFile.fileDuration()) audioFile.setFileDuration(parseDuration(value));
230 else if(!key.compare("Artist", Qt::CaseInsensitive) || !key.compare("Performer", Qt::CaseInsensitive))
232 if(audioFile.fileArtist().isEmpty()) audioFile.setFileArtist(value);
234 else if(!key.compare("Album", Qt::CaseInsensitive))
236 if(audioFile.fileAlbum().isEmpty()) audioFile.setFileAlbum(value);
238 else if(!key.compare("Genre", Qt::CaseInsensitive))
240 if(audioFile.fileGenre().isEmpty()) audioFile.setFileGenre(value);
242 else if(!key.compare("Year", Qt::CaseInsensitive) || !key.compare("Recorded Date", Qt::CaseInsensitive) || !key.compare("Encoded Date", Qt::CaseInsensitive))
244 if(!audioFile.fileYear()) audioFile.setFileYear(parseYear(value));
246 else if(!key.compare("Comment", Qt::CaseInsensitive))
248 if(audioFile.fileComment().isEmpty()) audioFile.setFileComment(value);
250 else if(!key.compare("Track Name/Position", Qt::CaseInsensitive))
252 if(!audioFile.filePosition()) audioFile.setFilePosition(value.toInt());
254 else if(!key.compare("Format", Qt::CaseInsensitive))
256 if(audioFile.formatContainerType().isEmpty()) audioFile.setFormatContainerType(value);
258 else if(!key.compare("Format Profile", Qt::CaseInsensitive))
260 if(audioFile.formatContainerProfile().isEmpty()) audioFile.setFormatContainerProfile(value);
265 if(!key.compare("Year", Qt::CaseInsensitive) || !key.compare("Recorded Date", Qt::CaseInsensitive) || !key.compare("Encoded Date", Qt::CaseInsensitive))
267 if(!audioFile.fileYear()) audioFile.setFileYear(parseYear(value));
269 else if(!key.compare("Format", Qt::CaseInsensitive))
271 if(audioFile.formatAudioType().isEmpty()) audioFile.setFormatAudioType(value);
273 else if(!key.compare("Format Profile", Qt::CaseInsensitive))
275 if(audioFile.formatAudioProfile().isEmpty()) audioFile.setFormatAudioProfile(value);
277 else if(!key.compare("Format Version", Qt::CaseInsensitive))
279 if(audioFile.formatAudioVersion().isEmpty()) audioFile.setFormatAudioVersion(value);
281 else if(!key.compare("Channel(s)", Qt::CaseInsensitive))
283 if(!audioFile.formatAudioChannels()) audioFile.setFormatAudioChannels(value.split(" ", QString::SkipEmptyParts).first().toInt());
285 else if(!key.compare("Sampling rate", Qt::CaseInsensitive))
287 if(!audioFile.formatAudioSamplerate()) audioFile.setFormatAudioSamplerate(ceil(value.split(" ", QString::SkipEmptyParts).first().toFloat() * 1000.0f));
289 else if(!key.compare("Bit depth", Qt::CaseInsensitive))
291 if(!audioFile.formatAudioBitdepth()) audioFile.setFormatAudioBitdepth(value.split(" ", QString::SkipEmptyParts).first().toInt());
293 else if(!key.compare("Duration", Qt::CaseInsensitive))
295 if(!audioFile.fileDuration()) audioFile.setFileDuration(parseDuration(value));
301 unsigned int FileAnalyzer::parseYear(const QString &str)
303 if(str.startsWith("UTC", Qt::CaseInsensitive))
305 QDate date = QDate::fromString(str.mid(3).trimmed().left(10), "yyyy-MM-dd");
318 int year = str.toInt(&ok);
330 unsigned int FileAnalyzer::parseDuration(const QString &str)
334 time = QTime::fromString(str, "z'ms'");
337 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
340 time = QTime::fromString(str, "s's 'z'ms'");
343 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
346 time = QTime::fromString(str, "m'mn 's's'");
349 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
352 time = QTime::fromString(str, "h'h 'm'mn'");
355 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
362 bool FileAnalyzer::importPlaylist(QStringList &fileList, const QString &playlistFile)
364 QFileInfo file(playlistFile);
365 QDir baseDir(file.canonicalPath());
367 QDir rootDir(baseDir);
368 while(rootDir.cdUp());
371 if(file.size() < 3 || file.size() > 512000)
376 //Detect playlist type
377 playlist_t playlistType = isPlaylist(file.canonicalFilePath());
379 //Exit if not a playlist
380 if(playlistType == noPlaylist)
385 QFile data(playlistFile);
387 //Open file for reading
388 if(!data.open(QIODevice::ReadOnly))
393 //Parse playlist depending on type
397 return parsePlaylist_m3u(data, fileList, baseDir, rootDir);
400 return parsePlaylist_pls(data, fileList, baseDir, rootDir);
403 return parsePlaylist_wpl(data, fileList, baseDir, rootDir);
411 bool FileAnalyzer::parsePlaylist_m3u(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir)
413 QByteArray line = data.readLine();
415 while(line.size() > 0)
417 QFileInfo filename1(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
418 QFileInfo filename2(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
420 filename1.setCaching(false);
421 filename2.setCaching(false);
423 if(!(filename1.filePath().startsWith("#") || filename2.filePath().startsWith("#")))
425 fixFilePath(filename1, baseDir, rootDir);
426 fixFilePath(filename2, baseDir, rootDir);
428 if(filename1.exists())
430 if(isPlaylist(filename1.canonicalFilePath()) == noPlaylist)
432 fileList << filename1.canonicalFilePath();
435 else if(filename2.exists())
437 if(isPlaylist(filename2.canonicalFilePath()) == noPlaylist)
439 fileList << filename2.canonicalFilePath();
444 line = data.readLine();
450 bool FileAnalyzer::parsePlaylist_pls(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir)
452 QRegExp plsEntry("File(\\d+)=(.+)", Qt::CaseInsensitive);
453 QByteArray line = data.readLine();
455 while(line.size() > 0)
459 QString temp1(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
460 QString temp2(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
462 if(!flag && plsEntry.indexIn(temp1) >= 0)
464 QFileInfo filename(QDir::fromNativeSeparators(plsEntry.cap(2)).trimmed());
465 filename.setCaching(false);
466 fixFilePath(filename, baseDir, rootDir);
468 if(filename.exists())
470 if(isPlaylist(filename.canonicalFilePath()) == noPlaylist)
472 fileList << filename.canonicalFilePath();
478 if(!flag && plsEntry.indexIn(temp2) >= 0)
480 QFileInfo filename(QDir::fromNativeSeparators(plsEntry.cap(2)).trimmed());
481 filename.setCaching(false);
482 fixFilePath(filename, baseDir, rootDir);
484 if(filename.exists())
486 if(isPlaylist(filename.canonicalFilePath()) == noPlaylist)
488 fileList << filename.canonicalFilePath();
494 line = data.readLine();
500 bool FileAnalyzer::parsePlaylist_wpl(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir)
502 QRegExp wplEntry("<(media|ref)[^<>]*(src|href)=\"([^\"]+)\"[^<>]*>", Qt::CaseInsensitive);
503 QByteArray line = data.readLine();
505 while(line.size() > 0)
509 QString temp1(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
510 QString temp2(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
512 if(!flag && wplEntry.indexIn(temp1) >= 0)
514 QFileInfo filename(QDir::fromNativeSeparators(wplEntry.cap(3)).trimmed());
515 filename.setCaching(false);
516 fixFilePath(filename, baseDir, rootDir);
518 if(filename.exists())
520 if(isPlaylist(filename.canonicalFilePath()) == noPlaylist)
522 fileList << filename.canonicalFilePath();
528 if(!flag && wplEntry.indexIn(temp2) >= 0)
530 QFileInfo filename(QDir::fromNativeSeparators(wplEntry.cap(3)).trimmed());
531 filename.setCaching(false);
532 fixFilePath(filename, baseDir, rootDir);
534 if(filename.exists())
536 if(isPlaylist(filename.canonicalFilePath()) == noPlaylist)
538 fileList << filename.canonicalFilePath();
544 line = data.readLine();
550 FileAnalyzer::playlist_t FileAnalyzer::isPlaylist(const QString &fileName)
552 QFileInfo file (fileName);
554 if(file.suffix().compare("m3u", Qt::CaseInsensitive) == 0)
558 else if(file.suffix().compare("m3u8", Qt::CaseInsensitive) == 0)
562 else if(file.suffix().compare("pls", Qt::CaseInsensitive) == 0)
566 else if(file.suffix().compare("asx", Qt::CaseInsensitive) == 0)
570 else if(file.suffix().compare("wpl", Qt::CaseInsensitive) == 0)
580 void FileAnalyzer::fixFilePath(QFileInfo &filename, const QDir &baseDir, const QDir &rootDir)
582 if(filename.filePath().startsWith("/"))
584 while(filename.filePath().startsWith("/"))
586 filename.setFile(filename.filePath().mid(1));
588 filename.setFile(rootDir.filePath(filename.filePath()));
591 if(!filename.isAbsolute())
593 filename.setFile(baseDir.filePath(filename.filePath()));
597 ////////////////////////////////////////////////////////////
599 ////////////////////////////////////////////////////////////
601 unsigned int FileAnalyzer::filesAccepted(void)
603 return m_filesAccepted;
606 unsigned int FileAnalyzer::filesRejected(void)
608 return m_filesRejected - m_filesDenied;
611 unsigned int FileAnalyzer::filesDenied(void)
613 return m_filesDenied;
616 ////////////////////////////////////////////////////////////
618 ////////////////////////////////////////////////////////////