1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 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 // --------------------------------------------------------------------
23 // !!! THIS IS THE OLD SINGLE-THREADED VERSION OF THE FILE ANALYZER !!!
24 // --------------------------------------------------------------------
26 #include "Thread_FileAnalyzer_ST.h"
29 #include "LockedFile.h"
30 #include "Model_AudioFile.h"
31 #include "PlaylistImporter.h"
43 #define IS_KEY(KEY) (key.compare(KEY, Qt::CaseInsensitive) == 0)
44 #define IS_SEC(SEC) (key.startsWith((SEC "_"), Qt::CaseInsensitive))
45 #define FIRST_TOK(STR) (STR.split(" ", QString::SkipEmptyParts).first())
47 ////////////////////////////////////////////////////////////
49 ////////////////////////////////////////////////////////////
51 FileAnalyzer_ST::FileAnalyzer_ST(const QStringList
&inputFiles
)
53 m_inputFiles(inputFiles
),
54 m_mediaInfoBin(lamexp_lookup_tool("mediainfo.exe")),
55 m_avs2wavBin(lamexp_lookup_tool("avs2wav.exe")),
62 if(m_mediaInfoBin
.isEmpty())
64 qFatal("Invalid path to MediaInfo binary. Tool not initialized properly.");
74 FileAnalyzer_ST::~FileAnalyzer_ST(void)
78 QString templatePath
= m_templateFile
->filePath();
79 LAMEXP_DELETE(m_templateFile
);
80 if(QFile::exists(templatePath
)) QFile::remove(templatePath
);
84 ////////////////////////////////////////////////////////////
86 ////////////////////////////////////////////////////////////
88 const char *FileAnalyzer_ST::g_tags_gen
[] =
97 "Artist", "Performer",
100 "Released_Date", "Recorded_Date",
109 const char *FileAnalyzer_ST::g_tags_aud
[] =
124 ////////////////////////////////////////////////////////////
126 ////////////////////////////////////////////////////////////
128 void FileAnalyzer_ST::run()
136 m_filesDummyCDDA
= 0;
139 lamexp_natural_string_sort(m_inputFiles
); // .sort()
141 m_recentlyAdded
.clear();
146 if(!createTemplate())
148 qWarning("Failed to create template file!");
153 while(!m_inputFiles
.isEmpty())
155 int fileType
= fileTypeNormal
;
156 QString currentFile
= QDir::fromNativeSeparators(m_inputFiles
.takeFirst());
157 qDebug("Analyzing: %s", currentFile
.toUtf8().constData());
158 emit
fileSelected(QFileInfo(currentFile
).fileName());
159 AudioFileModel file
= analyzeFile(currentFile
, &fileType
);
163 MessageBeep(MB_ICONERROR
);
165 qWarning("Operation cancelled by user!");
168 if(fileType
== fileTypeSkip
)
170 qWarning("File was recently added, skipping!");
173 if(fileType
== fileTypeDenied
)
176 qWarning("Cannot access file for reading, skipping!");
179 if(fileType
== fileTypeCDDA
)
182 qWarning("Dummy CDDA file detected, skipping!");
186 if(file
.fileName().isEmpty() || file
.formatContainerType().isEmpty() || file
.formatAudioType().isEmpty())
188 if(PlaylistImporter::importPlaylist(m_inputFiles
, currentFile
))
190 qDebug("Imported playlist file.");
192 else if(!QFileInfo(currentFile
).suffix().compare("cue", Qt::CaseInsensitive
))
194 qWarning("Cue Sheet file detected, skipping!");
197 else if(!QFileInfo(currentFile
).suffix().compare("avs", Qt::CaseInsensitive
))
199 qDebug("Found a potential Avisynth script, investigating...");
200 if(analyzeAvisynthFile(currentFile
, file
))
203 emit
fileAnalyzed(file
);
207 qDebug("Rejected Avisynth file: %s", file
.filePath().toUtf8().constData());
213 qDebug("Rejected file of unknown type: %s", file
.filePath().toUtf8().constData());
220 m_recentlyAdded
.append(file
.filePath());
221 emit
fileAnalyzed(file
);
224 qDebug("All files added.\n");
228 ////////////////////////////////////////////////////////////
230 ////////////////////////////////////////////////////////////
232 const AudioFileModel
FileAnalyzer_ST::analyzeFile(const QString
&filePath
, int *type
)
234 *type
= fileTypeNormal
;
236 AudioFileModel
audioFile(filePath
);
238 if(m_recentlyAdded
.contains(filePath
, Qt::CaseInsensitive
))
240 *type
= fileTypeSkip
;
244 QFile
readTest(filePath
);
245 if(!readTest
.open(QIODevice::ReadOnly
))
247 *type
= fileTypeDenied
;
250 if(checkFile_CDDA(readTest
))
252 *type
= fileTypeCDDA
;
257 bool skipNext
= false;
258 unsigned int id_val
[2] = {UINT_MAX
, UINT_MAX
};
259 cover_t coverType
= coverNone
;
260 QByteArray coverData
;
263 params
<< QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile
->filePath()));
264 params
<< QDir::toNativeSeparators(filePath
);
267 process
.setProcessChannelMode(QProcess::MergedChannels
);
268 process
.setReadChannel(QProcess::StandardOutput
);
269 process
.start(m_mediaInfoBin
, params
);
271 if(!process
.waitForStarted())
273 qWarning("MediaInfo process failed to create!");
274 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
276 process
.waitForFinished(-1);
280 while(process
.state() != QProcess::NotRunning
)
285 qWarning("Process was aborted on user request!");
289 if(!process
.waitForReadyRead())
291 if(process
.state() == QProcess::Running
)
293 qWarning("MediaInfo time out. Killing process and skipping file!");
295 process
.waitForFinished(-1);
302 while(process
.canReadLine())
304 QString line
= QString::fromUtf8(process
.readLine().constData()).simplified();
307 //qDebug("Line:%s", line.toUtf8().constData());
309 int index
= line
.indexOf('=');
312 QString key
= line
.left(index
).trimmed();
313 QString val
= line
.mid(index
+1).trimmed();
316 updateInfo(audioFile
, &skipNext
, id_val
, &coverType
, &coverData
, key
, val
);
323 if(audioFile
.fileName().isEmpty())
325 QString baseName
= QFileInfo(filePath
).fileName();
326 int index
= baseName
.lastIndexOf(".");
330 baseName
= baseName
.left(index
);
333 baseName
= baseName
.replace("_", " ").simplified();
334 index
= baseName
.lastIndexOf(" - ");
338 baseName
= baseName
.mid(index
+ 3).trimmed();
341 audioFile
.setFileName(baseName
);
344 process
.waitForFinished();
345 if(process
.state() != QProcess::NotRunning
)
348 process
.waitForFinished(-1);
351 if((coverType
!= coverNone
) && (!coverData
.isEmpty()))
353 retrieveCover(audioFile
, coverType
, coverData
);
359 void FileAnalyzer_ST::updateInfo(AudioFileModel
&audioFile
, bool *skipNext
, unsigned int *id_val
, cover_t
*coverType
, QByteArray
*coverData
, const QString
&key
, const QString
&value
)
361 //qWarning("'%s' -> '%s'", key.toUtf8().constData(), value.toUtf8().constData());
364 if(IS_KEY("Gen_ID") || IS_KEY("Aud_ID"))
372 //We ignore all ID's, except for the lowest one!
374 unsigned int id
= value
.toUInt(&ok
);
377 if(IS_KEY("Gen_ID")) { id_val
[0] = qMin(id_val
[0], id
); *skipNext
= (id
> id_val
[0]); }
378 if(IS_KEY("Aud_ID")) { id_val
[1] = qMin(id_val
[1], id
); *skipNext
= (id
> id_val
[1]); }
387 qWarning("Skipping info for non-primary stream!");
393 if((*skipNext
) || value
.isEmpty())
399 if(IS_KEY("Aud_Source"))
402 audioFile
.setFormatContainerType(QString());
403 audioFile
.setFormatAudioType(QString());
404 qWarning("Skipping info for playlist file!");
411 if(IS_KEY("Gen_Format"))
413 audioFile
.setFormatContainerType(value
);
415 else if(IS_KEY("Gen_Format_Profile"))
417 audioFile
.setFormatContainerProfile(value
);
419 else if(IS_KEY("Gen_Title") || IS_KEY("Gen_Track"))
421 audioFile
.setFileName(value
);
423 else if(IS_KEY("Gen_Duration"))
425 unsigned int tmp
= parseDuration(value
);
426 if(tmp
> 0) audioFile
.setFileDuration(tmp
);
428 else if(IS_KEY("Gen_Artist") || IS_KEY("Gen_Performer"))
430 audioFile
.setFileArtist(value
);
432 else if(IS_KEY("Gen_Album"))
434 audioFile
.setFileAlbum(value
);
436 else if(IS_KEY("Gen_Genre"))
438 audioFile
.setFileGenre(value
);
440 else if(IS_KEY("Gen_Released_Date") || IS_KEY("Gen_Recorded_Date"))
442 unsigned int tmp
= parseYear(value
);
443 if(tmp
> 0) audioFile
.setFileYear(tmp
);
445 else if(IS_KEY("Gen_Comment"))
447 audioFile
.setFileComment(value
);
449 else if(IS_KEY("Gen_Track/Position"))
452 unsigned int tmp
= value
.toUInt(&ok
);
453 if(ok
) audioFile
.setFilePosition(tmp
);
455 else if(IS_KEY("Gen_Cover") || IS_KEY("Gen_Cover_Type"))
457 if(*coverType
== coverNone
)
459 *coverType
= coverJpeg
;
462 else if(IS_KEY("Gen_Cover_Mime"))
464 QString temp
= FIRST_TOK(value
);
465 if(!temp
.compare("image/jpeg", Qt::CaseInsensitive
)) *coverType
= coverJpeg
;
466 else if(!temp
.compare("image/png", Qt::CaseInsensitive
)) *coverType
= coverPng
;
467 else if(!temp
.compare("image/gif", Qt::CaseInsensitive
)) *coverType
= coverGif
;
469 else if(IS_KEY("Gen_Cover_Data"))
471 if(!coverData
->isEmpty()) coverData
->clear();
472 coverData
->append(QByteArray::fromBase64(FIRST_TOK(value
).toLatin1()));
476 qWarning("Unknown key '%s' with value '%s' found!", key
.toUtf8().constData(), value
.toUtf8().constData());
485 if(IS_KEY("Aud_Format"))
487 audioFile
.setFormatAudioType(value
);
489 else if(IS_KEY("Aud_Format_Profile"))
491 audioFile
.setFormatAudioProfile(value
);
493 else if(IS_KEY("Aud_Format_Version"))
495 audioFile
.setFormatAudioVersion(value
);
497 else if(IS_KEY("Aud_Channel(s)"))
500 unsigned int tmp
= value
.toUInt(&ok
);
501 if(ok
) audioFile
.setFormatAudioChannels(tmp
);
503 else if(IS_KEY("Aud_SamplingRate"))
506 unsigned int tmp
= value
.toUInt(&ok
);
507 if(ok
) audioFile
.setFormatAudioSamplerate(tmp
);
509 else if(IS_KEY("Aud_BitDepth"))
512 unsigned int tmp
= value
.toUInt(&ok
);
513 if(ok
) audioFile
.setFormatAudioBitdepth(tmp
);
515 else if(IS_KEY("Aud_Duration"))
517 unsigned int tmp
= parseDuration(value
);
518 if(tmp
> 0) audioFile
.setFileDuration(tmp
);
520 else if(IS_KEY("Aud_BitRate"))
523 unsigned int tmp
= value
.toUInt(&ok
);
524 if(ok
) audioFile
.setFormatAudioBitrate(tmp
/1000);
526 else if(IS_KEY("Aud_BitRate_Mode"))
528 if(!value
.compare("CBR", Qt::CaseInsensitive
)) audioFile
.setFormatAudioBitrateMode(AudioFileModel::BitrateModeConstant
);
529 if(!value
.compare("VBR", Qt::CaseInsensitive
)) audioFile
.setFormatAudioBitrateMode(AudioFileModel::BitrateModeVariable
);
533 qWarning("Unknown key '%s' with value '%s' found!", key
.toUtf8().constData(), value
.toUtf8().constData());
538 /*Section not recognized*/
539 qWarning("Unknown section: %s", key
.toUtf8().constData());
542 bool FileAnalyzer_ST::checkFile_CDDA(QFile
&file
)
545 QByteArray data
= file
.read(128);
547 int i
= data
.indexOf("RIFF");
548 int j
= data
.indexOf("CDDA");
549 int k
= data
.indexOf("fmt ");
551 return ((i
>= 0) && (j
>= 0) && (k
>= 0) && (k
> j
) && (j
> i
));
554 void FileAnalyzer_ST::retrieveCover(AudioFileModel
&audioFile
, cover_t coverType
, const QByteArray
&coverData
)
556 qDebug("Retrieving cover!");
562 extension
= QString::fromLatin1("png");
565 extension
= QString::fromLatin1("gif");
568 extension
= QString::fromLatin1("jpg");
572 if(!(QImage::fromData(coverData
, extension
.toUpper().toLatin1().constData()).isNull()))
574 QFile
coverFile(QString("%1/%2.%3").arg(lamexp_temp_folder2(), lamexp_rand_str(), extension
));
575 if(coverFile
.open(QIODevice::WriteOnly
))
577 coverFile
.write(coverData
);
579 audioFile
.setFileCover(coverFile
.fileName(), true);
584 qWarning("Image data seems to be invalid :-(");
588 bool FileAnalyzer_ST::analyzeAvisynthFile(const QString
&filePath
, AudioFileModel
&info
)
591 process
.setProcessChannelMode(QProcess::MergedChannels
);
592 process
.setReadChannel(QProcess::StandardOutput
);
593 process
.start(m_avs2wavBin
, QStringList() << QDir::toNativeSeparators(filePath
) << "?");
595 if(!process
.waitForStarted())
597 qWarning("AVS2WAV process failed to create!");
598 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
600 process
.waitForFinished(-1);
604 bool bInfoHeaderFound
= false;
606 while(process
.state() != QProcess::NotRunning
)
611 qWarning("Process was aborted on user request!");
615 if(!process
.waitForReadyRead())
617 if(process
.state() == QProcess::Running
)
619 qWarning("AVS2WAV time out. Killing process and skipping file!");
621 process
.waitForFinished(-1);
628 while(process
.canReadLine())
630 QString line
= QString::fromUtf8(process
.readLine().constData()).simplified();
633 int index
= line
.indexOf(':');
636 QString key
= line
.left(index
).trimmed();
637 QString val
= line
.mid(index
+1).trimmed();
639 if(bInfoHeaderFound
&& !key
.isEmpty() && !val
.isEmpty())
641 if(key
.compare("TotalSeconds", Qt::CaseInsensitive
) == 0)
644 unsigned int duration
= val
.toUInt(&ok
);
645 if(ok
) info
.setFileDuration(duration
);
647 if(key
.compare("SamplesPerSec", Qt::CaseInsensitive
) == 0)
650 unsigned int samplerate
= val
.toUInt(&ok
);
651 if(ok
) info
.setFormatAudioSamplerate (samplerate
);
653 if(key
.compare("Channels", Qt::CaseInsensitive
) == 0)
656 unsigned int channels
= val
.toUInt(&ok
);
657 if(ok
) info
.setFormatAudioChannels(channels
);
659 if(key
.compare("BitsPerSample", Qt::CaseInsensitive
) == 0)
662 unsigned int bitdepth
= val
.toUInt(&ok
);
663 if(ok
) info
.setFormatAudioBitdepth(bitdepth
);
669 if(line
.contains("[Audio Info]", Qt::CaseInsensitive
))
671 info
.setFormatAudioType("Avisynth");
672 info
.setFormatContainerType("Avisynth");
673 bInfoHeaderFound
= true;
680 process
.waitForFinished();
681 if(process
.state() != QProcess::NotRunning
)
684 process
.waitForFinished(-1);
688 switch(process
.exitCode())
691 qDebug("Avisynth script was analyzed successfully.");
695 qWarning("It appears that Avisynth is not installed on the system!");
699 qWarning("Failed to open the Avisynth script, bad AVS file?");
705 bool FileAnalyzer_ST::createTemplate(void)
709 qWarning("Template file already exists!");
713 QString templatePath
= QString("%1/%2.txt").arg(lamexp_temp_folder2(), lamexp_rand_str());
715 QFile
templateFile(templatePath
);
716 if(!templateFile
.open(QIODevice::WriteOnly
))
721 templateFile
.write("General;");
722 for(size_t i
= 0; g_tags_gen
[i
]; i
++)
724 templateFile
.write(QString("Gen_%1=%%1%\\n").arg(g_tags_gen
[i
]).toLatin1().constData());
726 templateFile
.write("\\n\r\n");
728 templateFile
.write("Audio;");
729 for(size_t i
= 0; g_tags_aud
[i
]; i
++)
731 templateFile
.write(QString("Aud_%1=%%1%\\n").arg(g_tags_aud
[i
]).toLatin1().constData());
733 templateFile
.write("\\n\r\n");
735 bool success
= (templateFile
.error() == QFile::NoError
);
736 templateFile
.close();
740 QFile::remove(templatePath
);
746 m_templateFile
= new LockedFile(templatePath
);
750 qWarning("Failed to lock template file!");
757 unsigned int FileAnalyzer_ST::parseYear(const QString
&str
)
759 if(str
.startsWith("UTC", Qt::CaseInsensitive
))
761 QDate date
= QDate::fromString(str
.mid(3).trimmed().left(10), "yyyy-MM-dd");
774 int year
= str
.toInt(&ok
);
786 unsigned int FileAnalyzer_ST::parseDuration(const QString
&str
)
789 unsigned int value
= str
.toUInt(&ok
);
790 return ok
? (value
/1000) : 0;
793 ////////////////////////////////////////////////////////////
795 ////////////////////////////////////////////////////////////
797 unsigned int FileAnalyzer_ST::filesAccepted(void)
799 return m_filesAccepted
;
802 unsigned int FileAnalyzer_ST::filesRejected(void)
804 return m_filesRejected
;
807 unsigned int FileAnalyzer_ST::filesDenied(void)
809 return m_filesDenied
;
812 unsigned int FileAnalyzer_ST::filesDummyCDDA(void)
814 return m_filesDummyCDDA
;
817 unsigned int FileAnalyzer_ST::filesCueSheet(void)
819 return m_filesCueSheet
;
822 ////////////////////////////////////////////////////////////
824 ////////////////////////////////////////////////////////////