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")),
46 m_avs2wavBin(lamexp_lookup_tool("avs2wav.exe")),
52 if(m_mediaInfoBin
.isEmpty())
54 qFatal("Invalid path to MediaInfo binary. Tool not initialized properly.");
64 ////////////////////////////////////////////////////////////
66 ////////////////////////////////////////////////////////////
68 void FileAnalyzer::run()
80 m_recentlyAdded
.clear();
83 while(!m_inputFiles
.isEmpty())
85 int fileType
= fileTypeNormal
;
86 QString currentFile
= QDir::fromNativeSeparators(m_inputFiles
.takeFirst());
87 qDebug("Analyzing: %s", currentFile
.toUtf8().constData());
88 emit
fileSelected(QFileInfo(currentFile
).fileName());
89 AudioFileModel file
= analyzeFile(currentFile
, &fileType
);
93 MessageBeep(MB_ICONERROR
);
95 qWarning("Operation cancelled by user!");
98 if(fileType
== fileTypeSkip
)
100 qWarning("File was recently added, skipping!");
103 if(fileType
== fileTypeDenied
)
106 qWarning("Cannot access file for reading, skipping!");
109 if(fileType
== fileTypeCDDA
)
112 qWarning("Dummy CDDA file detected, skipping!");
116 if(file
.fileName().isEmpty() || file
.formatContainerType().isEmpty() || file
.formatAudioType().isEmpty())
118 if(PlaylistImporter::importPlaylist(m_inputFiles
, currentFile
))
120 qDebug("Imported playlist file.");
122 else if(!QFileInfo(currentFile
).suffix().compare("cue", Qt::CaseInsensitive
))
124 qWarning("Cue Sheet file detected, skipping!");
127 else if(!QFileInfo(currentFile
).suffix().compare("avs", Qt::CaseInsensitive
))
129 qDebug("Found a potential Avisynth script, investigating...");
130 if(analyzeAvisynthFile(currentFile
, file
))
133 emit
fileAnalyzed(file
);
137 qDebug("Rejected Avisynth file: %s", file
.filePath().toUtf8().constData());
143 qDebug("Rejected file of unknown type: %s", file
.filePath().toUtf8().constData());
150 m_recentlyAdded
.append(file
.filePath());
151 emit
fileAnalyzed(file
);
154 qDebug("All files added.\n");
158 ////////////////////////////////////////////////////////////
160 ////////////////////////////////////////////////////////////
162 const AudioFileModel
FileAnalyzer::analyzeFile(const QString
&filePath
, int *type
)
164 *type
= fileTypeNormal
;
166 AudioFileModel
audioFile(filePath
);
167 m_currentSection
= sectionOther
;
168 m_currentCover
= coverNone
;
170 if(m_recentlyAdded
.contains(filePath
, Qt::CaseInsensitive
))
172 *type
= fileTypeSkip
;
176 QFile
readTest(filePath
);
177 if(!readTest
.open(QIODevice::ReadOnly
))
179 *type
= fileTypeDenied
;
183 if(checkFile_CDDA(readTest
))
185 *type
= fileTypeCDDA
;
192 process
.setProcessChannelMode(QProcess::MergedChannels
);
193 process
.setReadChannel(QProcess::StandardOutput
);
194 process
.start(m_mediaInfoBin
, QStringList() << QDir::toNativeSeparators(filePath
));
196 if(!process
.waitForStarted())
198 qWarning("MediaInfo process failed to create!");
199 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
201 process
.waitForFinished(-1);
205 while(process
.state() != QProcess::NotRunning
)
210 qWarning("Process was aborted on user request!");
214 if(!process
.waitForReadyRead())
216 if(process
.state() == QProcess::Running
)
218 qWarning("MediaInfo time out. Killing process and skipping file!");
220 process
.waitForFinished(-1);
227 while(process
.canReadLine())
229 QString line
= QString::fromUtf8(process
.readLine().constData()).simplified();
232 int index
= line
.indexOf(':');
235 QString key
= line
.left(index
-1).trimmed();
236 QString val
= line
.mid(index
+1).trimmed();
237 if(!key
.isEmpty() && !val
.isEmpty())
239 updateInfo(audioFile
, key
, val
);
250 if(audioFile
.fileName().isEmpty())
252 QString baseName
= QFileInfo(filePath
).fileName();
253 int index
= baseName
.lastIndexOf(".");
257 baseName
= baseName
.left(index
);
260 baseName
= baseName
.replace("_", " ").simplified();
261 index
= baseName
.lastIndexOf(" - ");
265 baseName
= baseName
.mid(index
+ 3).trimmed();
268 audioFile
.setFileName(baseName
);
271 process
.waitForFinished();
272 if(process
.state() != QProcess::NotRunning
)
275 process
.waitForFinished(-1);
278 if(m_currentCover
!= coverNone
)
280 retrieveCover(audioFile
, filePath
);
286 void FileAnalyzer::updateSection(const QString
§ion
)
288 if(section
.startsWith("General", Qt::CaseInsensitive
))
290 m_currentSection
= sectionGeneral
;
292 else if(!section
.compare("Audio", Qt::CaseInsensitive
) || section
.startsWith("Audio #1", Qt::CaseInsensitive
))
294 m_currentSection
= sectionAudio
;
296 else if(section
.startsWith("Audio", Qt::CaseInsensitive
) || section
.startsWith("Video", Qt::CaseInsensitive
) || section
.startsWith("Text", Qt::CaseInsensitive
) ||
297 section
.startsWith("Menu", Qt::CaseInsensitive
) || section
.startsWith("Image", Qt::CaseInsensitive
) || section
.startsWith("Chapters", Qt::CaseInsensitive
))
299 m_currentSection
= sectionOther
;
303 m_currentSection
= sectionOther
;
304 qWarning("Unknown section: %s", section
.toUtf8().constData());
308 void FileAnalyzer::updateInfo(AudioFileModel
&audioFile
, const QString
&key
, const QString
&value
)
310 switch(m_currentSection
)
313 if(!key
.compare("Title", Qt::CaseInsensitive
) || !key
.compare("Track", Qt::CaseInsensitive
) || !key
.compare("Track Name", Qt::CaseInsensitive
))
315 if(audioFile
.fileName().isEmpty()) audioFile
.setFileName(value
);
317 else if(!key
.compare("Duration", Qt::CaseInsensitive
))
319 if(!audioFile
.fileDuration()) audioFile
.setFileDuration(parseDuration(value
));
321 else if(!key
.compare("Artist", Qt::CaseInsensitive
) || !key
.compare("Performer", Qt::CaseInsensitive
))
323 if(audioFile
.fileArtist().isEmpty()) audioFile
.setFileArtist(value
);
325 else if(!key
.compare("Album", Qt::CaseInsensitive
))
327 if(audioFile
.fileAlbum().isEmpty()) audioFile
.setFileAlbum(value
);
329 else if(!key
.compare("Genre", Qt::CaseInsensitive
))
331 if(audioFile
.fileGenre().isEmpty()) audioFile
.setFileGenre(value
);
333 else if(!key
.compare("Year", Qt::CaseInsensitive
) || !key
.compare("Recorded Date", Qt::CaseInsensitive
) || !key
.compare("Encoded Date", Qt::CaseInsensitive
))
335 if(!audioFile
.fileYear()) audioFile
.setFileYear(parseYear(value
));
337 else if(!key
.compare("Comment", Qt::CaseInsensitive
))
339 if(audioFile
.fileComment().isEmpty()) audioFile
.setFileComment(value
);
341 else if(!key
.compare("Track Name/Position", Qt::CaseInsensitive
))
343 if(!audioFile
.filePosition()) audioFile
.setFilePosition(value
.toInt());
345 else if(!key
.compare("Format", Qt::CaseInsensitive
))
347 if(audioFile
.formatContainerType().isEmpty()) audioFile
.setFormatContainerType(value
);
349 else if(!key
.compare("Format Profile", Qt::CaseInsensitive
))
351 if(audioFile
.formatContainerProfile().isEmpty()) audioFile
.setFormatContainerProfile(value
);
353 else if(!key
.compare("Cover", Qt::CaseInsensitive
) || !key
.compare("Cover type", Qt::CaseInsensitive
))
355 if(m_currentCover
== coverNone
) m_currentCover
= coverJpeg
;
357 else if(!key
.compare("Cover MIME", Qt::CaseInsensitive
))
359 QString temp
= value
.split(" ", QString::SkipEmptyParts
, Qt::CaseInsensitive
).first();
360 if(!temp
.compare("image/jpeg", Qt::CaseInsensitive
))
362 m_currentCover
= coverJpeg
;
364 else if(!temp
.compare("image/png", Qt::CaseInsensitive
))
366 m_currentCover
= coverPng
;
368 else if(!temp
.compare("image/gif", Qt::CaseInsensitive
))
370 m_currentCover
= coverGif
;
376 if(!key
.compare("Year", Qt::CaseInsensitive
) || !key
.compare("Recorded Date", Qt::CaseInsensitive
) || !key
.compare("Encoded Date", Qt::CaseInsensitive
))
378 if(!audioFile
.fileYear()) audioFile
.setFileYear(parseYear(value
));
380 else if(!key
.compare("Format", Qt::CaseInsensitive
))
382 if(audioFile
.formatAudioType().isEmpty()) audioFile
.setFormatAudioType(value
);
384 else if(!key
.compare("Format Profile", Qt::CaseInsensitive
))
386 if(audioFile
.formatAudioProfile().isEmpty()) audioFile
.setFormatAudioProfile(value
);
388 else if(!key
.compare("Format Version", Qt::CaseInsensitive
))
390 if(audioFile
.formatAudioVersion().isEmpty()) audioFile
.setFormatAudioVersion(value
);
392 else if(!key
.compare("Channel(s)", Qt::CaseInsensitive
))
394 if(!audioFile
.formatAudioChannels()) audioFile
.setFormatAudioChannels(value
.split(" ", QString::SkipEmptyParts
).first().toUInt());
396 else if(!key
.compare("Sampling rate", Qt::CaseInsensitive
))
398 if(!audioFile
.formatAudioSamplerate())
401 float fTemp
= abs(value
.split(" ", QString::SkipEmptyParts
).first().toFloat(&ok
));
402 if(ok
) audioFile
.setFormatAudioSamplerate(static_cast<unsigned int>(floor(fTemp
* 1000.0f
+ 0.5f
)));
405 else if(!key
.compare("Bit depth", Qt::CaseInsensitive
))
407 if(!audioFile
.formatAudioBitdepth()) audioFile
.setFormatAudioBitdepth(value
.split(" ", QString::SkipEmptyParts
).first().toUInt());
409 else if(!key
.compare("Duration", Qt::CaseInsensitive
))
411 if(!audioFile
.fileDuration()) audioFile
.setFileDuration(parseDuration(value
));
413 else if(!key
.compare("Bit rate", Qt::CaseInsensitive
))
415 if(!audioFile
.formatAudioBitrate())
418 unsigned int uiTemp
= value
.split(" ", QString::SkipEmptyParts
).first().toUInt(&ok
);
421 audioFile
.setFormatAudioBitrate(uiTemp
);
425 float fTemp
= abs(value
.split(" ", QString::SkipEmptyParts
).first().toFloat(&ok
));
426 if(ok
) audioFile
.setFormatAudioBitrate(static_cast<unsigned int>(floor(fTemp
+ 0.5f
)));
430 else if(!key
.compare("Bit rate mode", Qt::CaseInsensitive
))
432 if(audioFile
.formatAudioBitrateMode() == AudioFileModel::BitrateModeUndefined
)
434 if(!value
.compare("Constant", Qt::CaseInsensitive
)) audioFile
.setFormatAudioBitrateMode(AudioFileModel::BitrateModeConstant
);
435 if(!value
.compare("Variable", Qt::CaseInsensitive
)) audioFile
.setFormatAudioBitrateMode(AudioFileModel::BitrateModeVariable
);
442 unsigned int FileAnalyzer::parseYear(const QString
&str
)
444 if(str
.startsWith("UTC", Qt::CaseInsensitive
))
446 QDate date
= QDate::fromString(str
.mid(3).trimmed().left(10), "yyyy-MM-dd");
459 int year
= str
.toInt(&ok
);
471 unsigned int FileAnalyzer::parseDuration(const QString
&str
)
475 time
= QTime::fromString(str
, "z'ms'");
478 return max(1, (time
.hour() * 60 * 60) + (time
.minute() * 60) + time
.second());
481 time
= QTime::fromString(str
, "s's 'z'ms'");
484 return max(1, (time
.hour() * 60 * 60) + (time
.minute() * 60) + time
.second());
487 time
= QTime::fromString(str
, "m'mn 's's'");
490 return max(1, (time
.hour() * 60 * 60) + (time
.minute() * 60) + time
.second());
493 time
= QTime::fromString(str
, "h'h 'm'mn'");
496 return max(1, (time
.hour() * 60 * 60) + (time
.minute() * 60) + time
.second());
502 bool FileAnalyzer::checkFile_CDDA(QFile
&file
)
505 QByteArray data
= file
.read(128);
507 int i
= data
.indexOf("RIFF");
508 int j
= data
.indexOf("CDDA");
509 int k
= data
.indexOf("fmt ");
511 return ((i
>= 0) && (j
>= 0) && (k
>= 0) && (k
> j
) && (j
> i
));
514 void FileAnalyzer::retrieveCover(AudioFileModel
&audioFile
, const QString
&filePath
)
516 qDebug("Retrieving cover from: %s", filePath
.toUtf8().constData());
519 switch(m_currentCover
)
522 extension
= QString::fromLatin1("png");
525 extension
= QString::fromLatin1("gif");
528 extension
= QString::fromLatin1("jpg");
533 process
.setProcessChannelMode(QProcess::MergedChannels
);
534 process
.setReadChannel(QProcess::StandardOutput
);
535 process
.start(m_mediaInfoBin
, QStringList() << "-f" << QDir::toNativeSeparators(filePath
));
537 if(!process
.waitForStarted())
539 qWarning("MediaInfo process failed to create!");
540 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
542 process
.waitForFinished(-1);
546 while(process
.state() != QProcess::NotRunning
)
551 qWarning("Process was aborted on user request!");
555 if(!process
.waitForReadyRead())
557 if(process
.state() == QProcess::Running
)
559 qWarning("MediaInfo time out. Killing process and skipping file!");
561 process
.waitForFinished(-1);
566 while(process
.canReadLine())
568 QString line
= QString::fromUtf8(process
.readLine().constData()).simplified();
571 int index
= line
.indexOf(':');
574 QString key
= line
.left(index
-1).trimmed();
575 QString val
= line
.mid(index
+1).trimmed();
576 if(!key
.isEmpty() && !val
.isEmpty())
578 if(!key
.compare("Cover_Data", Qt::CaseInsensitive
))
580 if(val
.indexOf(" ") > 0)
582 val
= val
.split(" ", QString::SkipEmptyParts
, Qt::CaseInsensitive
).first();
584 QByteArray coverData
= QByteArray::fromBase64(val
.toLatin1());
585 QFile
coverFile(QString("%1/%2.%3").arg(lamexp_temp_folder2(), lamexp_rand_str(), extension
));
586 if(coverFile
.open(QIODevice::WriteOnly
))
588 coverFile
.write(coverData
);
590 audioFile
.setFileCover(coverFile
.fileName(), true);
600 process
.waitForFinished();
601 if(process
.state() != QProcess::NotRunning
)
604 process
.waitForFinished(-1);
608 bool FileAnalyzer::analyzeAvisynthFile(const QString
&filePath
, AudioFileModel
&info
)
611 process
.setProcessChannelMode(QProcess::MergedChannels
);
612 process
.setReadChannel(QProcess::StandardOutput
);
613 process
.start(m_avs2wavBin
, QStringList() << QDir::toNativeSeparators(filePath
) << "?");
615 if(!process
.waitForStarted())
617 qWarning("AVS2WAV process failed to create!");
618 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
620 process
.waitForFinished(-1);
624 bool bInfoHeaderFound
= false;
626 while(process
.state() != QProcess::NotRunning
)
631 qWarning("Process was aborted on user request!");
635 if(!process
.waitForReadyRead())
637 if(process
.state() == QProcess::Running
)
639 qWarning("AVS2WAV time out. Killing process and skipping file!");
641 process
.waitForFinished(-1);
648 while(process
.canReadLine())
650 QString line
= QString::fromUtf8(process
.readLine().constData()).simplified();
653 int index
= line
.indexOf(':');
656 QString key
= line
.left(index
).trimmed();
657 QString val
= line
.mid(index
+1).trimmed();
659 if(bInfoHeaderFound
&& !key
.isEmpty() && !val
.isEmpty())
661 if(key
.compare("TotalSeconds", Qt::CaseInsensitive
) == 0)
664 unsigned int duration
= val
.toUInt(&ok
);
665 if(ok
) info
.setFileDuration(duration
);
667 if(key
.compare("SamplesPerSec", Qt::CaseInsensitive
) == 0)
670 unsigned int samplerate
= val
.toUInt(&ok
);
671 if(ok
) info
.setFormatAudioSamplerate (samplerate
);
673 if(key
.compare("Channels", Qt::CaseInsensitive
) == 0)
676 unsigned int channels
= val
.toUInt(&ok
);
677 if(ok
) info
.setFormatAudioChannels(channels
);
679 if(key
.compare("BitsPerSample", Qt::CaseInsensitive
) == 0)
682 unsigned int bitdepth
= val
.toUInt(&ok
);
683 if(ok
) info
.setFormatAudioBitdepth(bitdepth
);
689 if(line
.contains("[Audio Info]", Qt::CaseInsensitive
))
691 info
.setFormatAudioType("Avisynth");
692 info
.setFormatContainerType("Avisynth");
693 bInfoHeaderFound
= true;
700 process
.waitForFinished();
701 if(process
.state() != QProcess::NotRunning
)
704 process
.waitForFinished(-1);
708 switch(process
.exitCode())
711 qDebug("Avisynth script was analyzed successfully.");
715 qWarning("It appears that Avisynth is not installed on the system!");
719 qWarning("Failed to open the Avisynth script, bad AVS file?");
725 ////////////////////////////////////////////////////////////
727 ////////////////////////////////////////////////////////////
729 unsigned int FileAnalyzer::filesAccepted(void)
731 return m_filesAccepted
;
734 unsigned int FileAnalyzer::filesRejected(void)
736 return m_filesRejected
;
739 unsigned int FileAnalyzer::filesDenied(void)
741 return m_filesDenied
;
744 unsigned int FileAnalyzer::filesDummyCDDA(void)
746 return m_filesDummyCDDA
;
749 unsigned int FileAnalyzer::filesCueSheet(void)
751 return m_filesCueSheet
;
754 ////////////////////////////////////////////////////////////
756 ////////////////////////////////////////////////////////////