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()
82 while(!m_inputFiles
.isEmpty())
84 int fileType
= fileTypeNormal
;
85 QString currentFile
= QDir::fromNativeSeparators(m_inputFiles
.takeFirst());
86 qDebug64("Analyzing: %1", currentFile
);
87 emit
fileSelected(QFileInfo(currentFile
).fileName());
88 AudioFileModel file
= analyzeFile(currentFile
, &fileType
);
92 MessageBeep(MB_ICONERROR
);
94 qWarning("Operation cancelled by user!");
98 if(fileType
== fileTypeDenied
)
101 qWarning("Cannot access file for reading, skipping!");
104 if(fileType
== fileTypeCDDA
)
107 qWarning("Dummy CDDA file detected, skipping!");
111 if(file
.fileName().isEmpty() || file
.formatContainerType().isEmpty() || file
.formatAudioType().isEmpty())
113 if(PlaylistImporter::importPlaylist(m_inputFiles
, currentFile
))
115 qDebug("Imported playlist file.");
117 else if(!QFileInfo(currentFile
).suffix().compare("cue", Qt::CaseInsensitive
))
119 qWarning("Cue Sheet file detected, skipping!");
122 else if(!QFileInfo(currentFile
).suffix().compare("avs", Qt::CaseInsensitive
))
124 qDebug("Found a potential Avisynth script, investigating...");
125 if(analyzeAvisynthFile(currentFile
, file
))
128 emit
fileAnalyzed(file
);
132 qDebug64("Rejected Avisynth file: %1", file
.filePath());
138 qDebug64("Rejected file of unknown type: %1", file
.filePath());
145 emit
fileAnalyzed(file
);
148 qDebug("All files added.\n");
152 ////////////////////////////////////////////////////////////
154 ////////////////////////////////////////////////////////////
156 const AudioFileModel
FileAnalyzer::analyzeFile(const QString
&filePath
, int *type
)
158 *type
= fileTypeNormal
;
160 AudioFileModel
audioFile(filePath
);
161 m_currentSection
= sectionOther
;
162 m_currentCover
= coverNone
;
164 QFile
readTest(filePath
);
165 if(!readTest
.open(QIODevice::ReadOnly
))
167 *type
= fileTypeDenied
;
171 if(checkFile_CDDA(readTest
))
173 *type
= fileTypeCDDA
;
180 process
.setProcessChannelMode(QProcess::MergedChannels
);
181 process
.setReadChannel(QProcess::StandardOutput
);
182 process
.start(m_mediaInfoBin
, QStringList() << QDir::toNativeSeparators(filePath
));
184 if(!process
.waitForStarted())
186 qWarning("MediaInfo process failed to create!");
187 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
189 process
.waitForFinished(-1);
193 while(process
.state() != QProcess::NotRunning
)
198 qWarning("Process was aborted on user request!");
202 if(!process
.waitForReadyRead())
204 if(process
.state() == QProcess::Running
)
206 qWarning("MediaInfo time out. Killing process and skipping file!");
208 process
.waitForFinished(-1);
215 while(process
.canReadLine())
217 QString line
= QString::fromUtf8(process
.readLine().constData()).simplified();
220 int index
= line
.indexOf(':');
223 QString key
= line
.left(index
-1).trimmed();
224 QString val
= line
.mid(index
+1).trimmed();
225 if(!key
.isEmpty() && !val
.isEmpty())
227 updateInfo(audioFile
, key
, val
);
238 if(audioFile
.fileName().isEmpty())
240 QString baseName
= QFileInfo(filePath
).fileName();
241 int index
= baseName
.lastIndexOf(".");
245 baseName
= baseName
.left(index
);
248 baseName
= baseName
.replace("_", " ").simplified();
249 index
= baseName
.lastIndexOf(" - ");
253 baseName
= baseName
.mid(index
+ 3).trimmed();
256 audioFile
.setFileName(baseName
);
259 process
.waitForFinished();
260 if(process
.state() != QProcess::NotRunning
)
263 process
.waitForFinished(-1);
266 if(m_currentCover
!= coverNone
)
268 retrieveCover(audioFile
, filePath
);
274 void FileAnalyzer::updateSection(const QString
§ion
)
276 if(section
.startsWith("General", Qt::CaseInsensitive
))
278 m_currentSection
= sectionGeneral
;
280 else if(!section
.compare("Audio", Qt::CaseInsensitive
) || section
.startsWith("Audio #1", Qt::CaseInsensitive
))
282 m_currentSection
= sectionAudio
;
284 else if(section
.startsWith("Audio", Qt::CaseInsensitive
) || section
.startsWith("Video", Qt::CaseInsensitive
) || section
.startsWith("Text", Qt::CaseInsensitive
) ||
285 section
.startsWith("Menu", Qt::CaseInsensitive
) || section
.startsWith("Image", Qt::CaseInsensitive
) || section
.startsWith("Chapters", Qt::CaseInsensitive
))
287 m_currentSection
= sectionOther
;
291 m_currentSection
= sectionOther
;
292 qWarning("Unknown section: %s", section
.toUtf8().constData());
296 void FileAnalyzer::updateInfo(AudioFileModel
&audioFile
, const QString
&key
, const QString
&value
)
298 switch(m_currentSection
)
301 if(!key
.compare("Title", Qt::CaseInsensitive
) || !key
.compare("Track", Qt::CaseInsensitive
) || !key
.compare("Track Name", Qt::CaseInsensitive
))
303 if(audioFile
.fileName().isEmpty()) audioFile
.setFileName(value
);
305 else if(!key
.compare("Duration", Qt::CaseInsensitive
))
307 if(!audioFile
.fileDuration()) audioFile
.setFileDuration(parseDuration(value
));
309 else if(!key
.compare("Artist", Qt::CaseInsensitive
) || !key
.compare("Performer", Qt::CaseInsensitive
))
311 if(audioFile
.fileArtist().isEmpty()) audioFile
.setFileArtist(value
);
313 else if(!key
.compare("Album", Qt::CaseInsensitive
))
315 if(audioFile
.fileAlbum().isEmpty()) audioFile
.setFileAlbum(value
);
317 else if(!key
.compare("Genre", Qt::CaseInsensitive
))
319 if(audioFile
.fileGenre().isEmpty()) audioFile
.setFileGenre(value
);
321 else if(!key
.compare("Year", Qt::CaseInsensitive
) || !key
.compare("Recorded Date", Qt::CaseInsensitive
) || !key
.compare("Encoded Date", Qt::CaseInsensitive
))
323 if(!audioFile
.fileYear()) audioFile
.setFileYear(parseYear(value
));
325 else if(!key
.compare("Comment", Qt::CaseInsensitive
))
327 if(audioFile
.fileComment().isEmpty()) audioFile
.setFileComment(value
);
329 else if(!key
.compare("Track Name/Position", Qt::CaseInsensitive
))
331 if(!audioFile
.filePosition()) audioFile
.setFilePosition(value
.toInt());
333 else if(!key
.compare("Format", Qt::CaseInsensitive
))
335 if(audioFile
.formatContainerType().isEmpty()) audioFile
.setFormatContainerType(value
);
337 else if(!key
.compare("Format Profile", Qt::CaseInsensitive
))
339 if(audioFile
.formatContainerProfile().isEmpty()) audioFile
.setFormatContainerProfile(value
);
341 else if(!key
.compare("Cover", Qt::CaseInsensitive
) || !key
.compare("Cover type", Qt::CaseInsensitive
))
343 if(m_currentCover
== coverNone
) m_currentCover
= coverJpeg
;
345 else if(!key
.compare("Cover MIME", Qt::CaseInsensitive
))
347 QString temp
= value
.split(" ", QString::SkipEmptyParts
, Qt::CaseInsensitive
).first();
348 if(!temp
.compare("image/jpeg", Qt::CaseInsensitive
))
350 m_currentCover
= coverJpeg
;
352 else if(!temp
.compare("image/png", Qt::CaseInsensitive
))
354 m_currentCover
= coverPng
;
356 else if(!temp
.compare("image/gif", Qt::CaseInsensitive
))
358 m_currentCover
= coverGif
;
364 if(!key
.compare("Year", Qt::CaseInsensitive
) || !key
.compare("Recorded Date", Qt::CaseInsensitive
) || !key
.compare("Encoded Date", Qt::CaseInsensitive
))
366 if(!audioFile
.fileYear()) audioFile
.setFileYear(parseYear(value
));
368 else if(!key
.compare("Format", Qt::CaseInsensitive
))
370 if(audioFile
.formatAudioType().isEmpty()) audioFile
.setFormatAudioType(value
);
372 else if(!key
.compare("Format Profile", Qt::CaseInsensitive
))
374 if(audioFile
.formatAudioProfile().isEmpty()) audioFile
.setFormatAudioProfile(value
);
376 else if(!key
.compare("Format Version", Qt::CaseInsensitive
))
378 if(audioFile
.formatAudioVersion().isEmpty()) audioFile
.setFormatAudioVersion(value
);
380 else if(!key
.compare("Channel(s)", Qt::CaseInsensitive
))
382 if(!audioFile
.formatAudioChannels()) audioFile
.setFormatAudioChannels(value
.split(" ", QString::SkipEmptyParts
).first().toUInt());
384 else if(!key
.compare("Sampling rate", Qt::CaseInsensitive
))
386 if(!audioFile
.formatAudioSamplerate())
389 float fTemp
= abs(value
.split(" ", QString::SkipEmptyParts
).first().toFloat(&ok
));
390 if(ok
) audioFile
.setFormatAudioSamplerate(static_cast<unsigned int>(floor(fTemp
* 1000.0f
+ 0.5f
)));
393 else if(!key
.compare("Bit depth", Qt::CaseInsensitive
))
395 if(!audioFile
.formatAudioBitdepth()) audioFile
.setFormatAudioBitdepth(value
.split(" ", QString::SkipEmptyParts
).first().toUInt());
397 else if(!key
.compare("Duration", Qt::CaseInsensitive
))
399 if(!audioFile
.fileDuration()) audioFile
.setFileDuration(parseDuration(value
));
401 else if(!key
.compare("Bit rate", Qt::CaseInsensitive
))
403 if(!audioFile
.formatAudioBitrate())
406 unsigned int uiTemp
= value
.split(" ", QString::SkipEmptyParts
).first().toUInt(&ok
);
409 audioFile
.setFormatAudioBitrate(uiTemp
);
413 float fTemp
= abs(value
.split(" ", QString::SkipEmptyParts
).first().toFloat(&ok
));
414 if(ok
) audioFile
.setFormatAudioBitrate(static_cast<unsigned int>(floor(fTemp
+ 0.5f
)));
418 else if(!key
.compare("Bit rate mode", Qt::CaseInsensitive
))
420 if(audioFile
.formatAudioBitrateMode() == AudioFileModel::BitrateModeUndefined
)
422 if(!value
.compare("Constant", Qt::CaseInsensitive
)) audioFile
.setFormatAudioBitrateMode(AudioFileModel::BitrateModeConstant
);
423 if(!value
.compare("Variable", Qt::CaseInsensitive
)) audioFile
.setFormatAudioBitrateMode(AudioFileModel::BitrateModeVariable
);
430 unsigned int FileAnalyzer::parseYear(const QString
&str
)
432 if(str
.startsWith("UTC", Qt::CaseInsensitive
))
434 QDate date
= QDate::fromString(str
.mid(3).trimmed().left(10), "yyyy-MM-dd");
447 int year
= str
.toInt(&ok
);
459 unsigned int FileAnalyzer::parseDuration(const QString
&str
)
463 time
= QTime::fromString(str
, "z'ms'");
466 return max(1, (time
.hour() * 60 * 60) + (time
.minute() * 60) + time
.second());
469 time
= QTime::fromString(str
, "s's 'z'ms'");
472 return max(1, (time
.hour() * 60 * 60) + (time
.minute() * 60) + time
.second());
475 time
= QTime::fromString(str
, "m'mn 's's'");
478 return max(1, (time
.hour() * 60 * 60) + (time
.minute() * 60) + time
.second());
481 time
= QTime::fromString(str
, "h'h 'm'mn'");
484 return max(1, (time
.hour() * 60 * 60) + (time
.minute() * 60) + time
.second());
490 bool FileAnalyzer::checkFile_CDDA(QFile
&file
)
493 QByteArray data
= file
.read(128);
495 int i
= data
.indexOf("RIFF");
496 int j
= data
.indexOf("CDDA");
497 int k
= data
.indexOf("fmt ");
499 return ((i
>= 0) && (j
>= 0) && (k
>= 0) && (k
> j
) && (j
> i
));
502 void FileAnalyzer::retrieveCover(AudioFileModel
&audioFile
, const QString
&filePath
)
504 qDebug64("Retrieving cover from: %1", filePath
);
507 switch(m_currentCover
)
510 extension
= QString::fromLatin1("png");
513 extension
= QString::fromLatin1("gif");
516 extension
= QString::fromLatin1("jpg");
521 process
.setProcessChannelMode(QProcess::MergedChannels
);
522 process
.setReadChannel(QProcess::StandardOutput
);
523 process
.start(m_mediaInfoBin
, QStringList() << "-f" << QDir::toNativeSeparators(filePath
));
525 if(!process
.waitForStarted())
527 qWarning("MediaInfo process failed to create!");
528 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
530 process
.waitForFinished(-1);
534 while(process
.state() != QProcess::NotRunning
)
539 qWarning("Process was aborted on user request!");
543 if(!process
.waitForReadyRead())
545 if(process
.state() == QProcess::Running
)
547 qWarning("MediaInfo time out. Killing process and skipping file!");
549 process
.waitForFinished(-1);
554 while(process
.canReadLine())
556 QString line
= QString::fromUtf8(process
.readLine().constData()).simplified();
559 int index
= line
.indexOf(':');
562 QString key
= line
.left(index
-1).trimmed();
563 QString val
= line
.mid(index
+1).trimmed();
564 if(!key
.isEmpty() && !val
.isEmpty())
566 if(!key
.compare("Cover_Data", Qt::CaseInsensitive
))
568 if(val
.indexOf(" ") > 0)
570 val
= val
.split(" ", QString::SkipEmptyParts
, Qt::CaseInsensitive
).first();
572 QByteArray coverData
= QByteArray::fromBase64(val
.toLatin1());
573 QFile
coverFile(QString("%1/%2.%3").arg(lamexp_temp_folder2(), lamexp_rand_str(), extension
));
574 if(coverFile
.open(QIODevice::WriteOnly
))
576 coverFile
.write(coverData
);
578 audioFile
.setFileCover(coverFile
.fileName(), true);
588 process
.waitForFinished();
589 if(process
.state() != QProcess::NotRunning
)
592 process
.waitForFinished(-1);
596 bool FileAnalyzer::analyzeAvisynthFile(const QString
&filePath
, AudioFileModel
&info
)
599 process
.setProcessChannelMode(QProcess::MergedChannels
);
600 process
.setReadChannel(QProcess::StandardOutput
);
601 process
.start(m_avs2wavBin
, QStringList() << QDir::toNativeSeparators(filePath
) << "?");
603 if(!process
.waitForStarted())
605 qWarning("AVS2WAV process failed to create!");
606 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
608 process
.waitForFinished(-1);
612 bool bInfoHeaderFound
= false;
614 while(process
.state() != QProcess::NotRunning
)
619 qWarning("Process was aborted on user request!");
623 if(!process
.waitForReadyRead())
625 if(process
.state() == QProcess::Running
)
627 qWarning("AVS2WAV time out. Killing process and skipping file!");
629 process
.waitForFinished(-1);
636 while(process
.canReadLine())
638 QString line
= QString::fromUtf8(process
.readLine().constData()).simplified();
641 int index
= line
.indexOf(':');
644 QString key
= line
.left(index
).trimmed();
645 QString val
= line
.mid(index
+1).trimmed();
647 if(bInfoHeaderFound
&& !key
.isEmpty() && !val
.isEmpty())
649 if(key
.compare("TotalSeconds", Qt::CaseInsensitive
) == 0)
652 unsigned int duration
= val
.toUInt(&ok
);
653 if(ok
) info
.setFileDuration(duration
);
655 if(key
.compare("SamplesPerSec", Qt::CaseInsensitive
) == 0)
658 unsigned int samplerate
= val
.toUInt(&ok
);
659 if(ok
) info
.setFormatAudioSamplerate (samplerate
);
661 if(key
.compare("Channels", Qt::CaseInsensitive
) == 0)
664 unsigned int channels
= val
.toUInt(&ok
);
665 if(ok
) info
.setFormatAudioChannels(channels
);
667 if(key
.compare("BitsPerSample", Qt::CaseInsensitive
) == 0)
670 unsigned int bitdepth
= val
.toUInt(&ok
);
671 if(ok
) info
.setFormatAudioBitdepth(bitdepth
);
677 if(line
.contains("[Audio Info]", Qt::CaseInsensitive
))
679 info
.setFormatAudioType("Avisynth");
680 info
.setFormatContainerType("Avisynth");
681 bInfoHeaderFound
= true;
688 process
.waitForFinished();
689 if(process
.state() != QProcess::NotRunning
)
692 process
.waitForFinished(-1);
696 switch(process
.exitCode())
699 qDebug("Avisynth script was analyzed successfully.");
703 qWarning("It appears that Avisynth is not installed on the system!");
707 qWarning("Failed to open the Avisynth script, bad AVS file?");
713 ////////////////////////////////////////////////////////////
715 ////////////////////////////////////////////////////////////
717 unsigned int FileAnalyzer::filesAccepted(void)
719 return m_filesAccepted
;
722 unsigned int FileAnalyzer::filesRejected(void)
724 return m_filesRejected
;
727 unsigned int FileAnalyzer::filesDenied(void)
729 return m_filesDenied
;
732 unsigned int FileAnalyzer::filesDummyCDDA(void)
734 return m_filesDummyCDDA
;
737 unsigned int FileAnalyzer::filesCueSheet(void)
739 return m_filesCueSheet
;
742 ////////////////////////////////////////////////////////////
744 ////////////////////////////////////////////////////////////