1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 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;
140 m_recentlyAdded.clear();
145 if(!createTemplate())
147 qWarning("Failed to create template file!");
152 while(!m_inputFiles.isEmpty())
154 int fileType = fileTypeNormal;
155 QString currentFile = QDir::fromNativeSeparators(m_inputFiles.takeFirst());
156 qDebug("Analyzing: %s", currentFile.toUtf8().constData());
157 emit fileSelected(QFileInfo(currentFile).fileName());
158 AudioFileModel file = analyzeFile(currentFile, &fileType);
162 MessageBeep(MB_ICONERROR);
164 qWarning("Operation cancelled by user!");
167 if(fileType == fileTypeSkip)
169 qWarning("File was recently added, skipping!");
172 if(fileType == fileTypeDenied)
175 qWarning("Cannot access file for reading, skipping!");
178 if(fileType == fileTypeCDDA)
181 qWarning("Dummy CDDA file detected, skipping!");
185 if(file.fileName().isEmpty() || file.formatContainerType().isEmpty() || file.formatAudioType().isEmpty())
187 if(PlaylistImporter::importPlaylist(m_inputFiles, currentFile))
189 qDebug("Imported playlist file.");
191 else if(!QFileInfo(currentFile).suffix().compare("cue", Qt::CaseInsensitive))
193 qWarning("Cue Sheet file detected, skipping!");
196 else if(!QFileInfo(currentFile).suffix().compare("avs", Qt::CaseInsensitive))
198 qDebug("Found a potential Avisynth script, investigating...");
199 if(analyzeAvisynthFile(currentFile, file))
202 emit fileAnalyzed(file);
206 qDebug("Rejected Avisynth file: %s", file.filePath().toUtf8().constData());
212 qDebug("Rejected file of unknown type: %s", file.filePath().toUtf8().constData());
219 m_recentlyAdded.append(file.filePath());
220 emit fileAnalyzed(file);
223 qDebug("All files added.\n");
227 ////////////////////////////////////////////////////////////
229 ////////////////////////////////////////////////////////////
231 const AudioFileModel FileAnalyzer_ST::analyzeFile(const QString &filePath, int *type)
233 *type = fileTypeNormal;
235 AudioFileModel audioFile(filePath);
237 if(m_recentlyAdded.contains(filePath, Qt::CaseInsensitive))
239 *type = fileTypeSkip;
243 QFile readTest(filePath);
244 if(!readTest.open(QIODevice::ReadOnly))
246 *type = fileTypeDenied;
249 if(checkFile_CDDA(readTest))
251 *type = fileTypeCDDA;
256 bool skipNext = false;
257 unsigned int id_val[2] = {UINT_MAX, UINT_MAX};
258 cover_t coverType = coverNone;
259 QByteArray coverData;
262 params << QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile->filePath()));
263 params << QDir::toNativeSeparators(filePath);
266 process.setProcessChannelMode(QProcess::MergedChannels);
267 process.setReadChannel(QProcess::StandardOutput);
268 process.start(m_mediaInfoBin, params);
270 if(!process.waitForStarted())
272 qWarning("MediaInfo process failed to create!");
273 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
275 process.waitForFinished(-1);
279 while(process.state() != QProcess::NotRunning)
284 qWarning("Process was aborted on user request!");
288 if(!process.waitForReadyRead())
290 if(process.state() == QProcess::Running)
292 qWarning("MediaInfo time out. Killing process and skipping file!");
294 process.waitForFinished(-1);
301 while(process.canReadLine())
303 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
306 //qDebug("Line:%s", line.toUtf8().constData());
308 int index = line.indexOf('=');
311 QString key = line.left(index).trimmed();
312 QString val = line.mid(index+1).trimmed();
315 updateInfo(audioFile, &skipNext, id_val, &coverType, &coverData, key, val);
322 if(audioFile.fileName().isEmpty())
324 QString baseName = QFileInfo(filePath).fileName();
325 int index = baseName.lastIndexOf(".");
329 baseName = baseName.left(index);
332 baseName = baseName.replace("_", " ").simplified();
333 index = baseName.lastIndexOf(" - ");
337 baseName = baseName.mid(index + 3).trimmed();
340 audioFile.setFileName(baseName);
343 process.waitForFinished();
344 if(process.state() != QProcess::NotRunning)
347 process.waitForFinished(-1);
350 if((coverType != coverNone) && (!coverData.isEmpty()))
352 retrieveCover(audioFile, coverType, coverData);
358 void FileAnalyzer_ST::updateInfo(AudioFileModel &audioFile, bool *skipNext, unsigned int *id_val, cover_t *coverType, QByteArray *coverData, const QString &key, const QString &value)
360 //qWarning("'%s' -> '%s'", key.toUtf8().constData(), value.toUtf8().constData());
363 if(IS_KEY("Gen_ID") || IS_KEY("Aud_ID"))
371 //We ignore all ID's, except for the lowest one!
373 unsigned int id = value.toUInt(&ok);
376 if(IS_KEY("Gen_ID")) { id_val[0] = qMin(id_val[0], id); *skipNext = (id > id_val[0]); }
377 if(IS_KEY("Aud_ID")) { id_val[1] = qMin(id_val[1], id); *skipNext = (id > id_val[1]); }
386 qWarning("Skipping info for non-primary stream!");
392 if((*skipNext) || value.isEmpty())
398 if(IS_KEY("Aud_Source"))
401 audioFile.setFormatContainerType(QString());
402 audioFile.setFormatAudioType(QString());
403 qWarning("Skipping info for playlist file!");
410 if(IS_KEY("Gen_Format"))
412 audioFile.setFormatContainerType(value);
414 else if(IS_KEY("Gen_Format_Profile"))
416 audioFile.setFormatContainerProfile(value);
418 else if(IS_KEY("Gen_Title") || IS_KEY("Gen_Track"))
420 audioFile.setFileName(value);
422 else if(IS_KEY("Gen_Duration"))
424 unsigned int tmp = parseDuration(value);
425 if(tmp > 0) audioFile.setFileDuration(tmp);
427 else if(IS_KEY("Gen_Artist") || IS_KEY("Gen_Performer"))
429 audioFile.setFileArtist(value);
431 else if(IS_KEY("Gen_Album"))
433 audioFile.setFileAlbum(value);
435 else if(IS_KEY("Gen_Genre"))
437 audioFile.setFileGenre(value);
439 else if(IS_KEY("Gen_Released_Date") || IS_KEY("Gen_Recorded_Date"))
441 unsigned int tmp = parseYear(value);
442 if(tmp > 0) audioFile.setFileYear(tmp);
444 else if(IS_KEY("Gen_Comment"))
446 audioFile.setFileComment(value);
448 else if(IS_KEY("Gen_Track/Position"))
451 unsigned int tmp = value.toUInt(&ok);
452 if(ok) audioFile.setFilePosition(tmp);
454 else if(IS_KEY("Gen_Cover") || IS_KEY("Gen_Cover_Type"))
456 if(*coverType == coverNone)
458 *coverType = coverJpeg;
461 else if(IS_KEY("Gen_Cover_Mime"))
463 QString temp = FIRST_TOK(value);
464 if(!temp.compare("image/jpeg", Qt::CaseInsensitive)) *coverType = coverJpeg;
465 else if(!temp.compare("image/png", Qt::CaseInsensitive)) *coverType = coverPng;
466 else if(!temp.compare("image/gif", Qt::CaseInsensitive)) *coverType = coverGif;
468 else if(IS_KEY("Gen_Cover_Data"))
470 if(!coverData->isEmpty()) coverData->clear();
471 coverData->append(QByteArray::fromBase64(FIRST_TOK(value).toLatin1()));
475 qWarning("Unknown key '%s' with value '%s' found!", key.toUtf8().constData(), value.toUtf8().constData());
484 if(IS_KEY("Aud_Format"))
486 audioFile.setFormatAudioType(value);
488 else if(IS_KEY("Aud_Format_Profile"))
490 audioFile.setFormatAudioProfile(value);
492 else if(IS_KEY("Aud_Format_Version"))
494 audioFile.setFormatAudioVersion(value);
496 else if(IS_KEY("Aud_Channel(s)"))
499 unsigned int tmp = value.toUInt(&ok);
500 if(ok) audioFile.setFormatAudioChannels(tmp);
502 else if(IS_KEY("Aud_SamplingRate"))
505 unsigned int tmp = value.toUInt(&ok);
506 if(ok) audioFile.setFormatAudioSamplerate(tmp);
508 else if(IS_KEY("Aud_BitDepth"))
511 unsigned int tmp = value.toUInt(&ok);
512 if(ok) audioFile.setFormatAudioBitdepth(tmp);
514 else if(IS_KEY("Aud_Duration"))
516 unsigned int tmp = parseDuration(value);
517 if(tmp > 0) audioFile.setFileDuration(tmp);
519 else if(IS_KEY("Aud_BitRate"))
522 unsigned int tmp = value.toUInt(&ok);
523 if(ok) audioFile.setFormatAudioBitrate(tmp/1000);
525 else if(IS_KEY("Aud_BitRate_Mode"))
527 if(!value.compare("CBR", Qt::CaseInsensitive)) audioFile.setFormatAudioBitrateMode(AudioFileModel::BitrateModeConstant);
528 if(!value.compare("VBR", Qt::CaseInsensitive)) audioFile.setFormatAudioBitrateMode(AudioFileModel::BitrateModeVariable);
532 qWarning("Unknown key '%s' with value '%s' found!", key.toUtf8().constData(), value.toUtf8().constData());
537 /*Section not recognized*/
538 qWarning("Unknown section: %s", key.toUtf8().constData());
541 bool FileAnalyzer_ST::checkFile_CDDA(QFile &file)
544 QByteArray data = file.read(128);
546 int i = data.indexOf("RIFF");
547 int j = data.indexOf("CDDA");
548 int k = data.indexOf("fmt ");
550 return ((i >= 0) && (j >= 0) && (k >= 0) && (k > j) && (j > i));
553 void FileAnalyzer_ST::retrieveCover(AudioFileModel &audioFile, cover_t coverType, const QByteArray &coverData)
555 qDebug("Retrieving cover!");
561 extension = QString::fromLatin1("png");
564 extension = QString::fromLatin1("gif");
567 extension = QString::fromLatin1("jpg");
571 if(!(QImage::fromData(coverData, extension.toUpper().toLatin1().constData()).isNull()))
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);
583 qWarning("Image data seems to be invalid :-(");
587 bool FileAnalyzer_ST::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
590 process.setProcessChannelMode(QProcess::MergedChannels);
591 process.setReadChannel(QProcess::StandardOutput);
592 process.start(m_avs2wavBin, QStringList() << QDir::toNativeSeparators(filePath) << "?");
594 if(!process.waitForStarted())
596 qWarning("AVS2WAV process failed to create!");
597 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
599 process.waitForFinished(-1);
603 bool bInfoHeaderFound = false;
605 while(process.state() != QProcess::NotRunning)
610 qWarning("Process was aborted on user request!");
614 if(!process.waitForReadyRead())
616 if(process.state() == QProcess::Running)
618 qWarning("AVS2WAV time out. Killing process and skipping file!");
620 process.waitForFinished(-1);
627 while(process.canReadLine())
629 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
632 int index = line.indexOf(':');
635 QString key = line.left(index).trimmed();
636 QString val = line.mid(index+1).trimmed();
638 if(bInfoHeaderFound && !key.isEmpty() && !val.isEmpty())
640 if(key.compare("TotalSeconds", Qt::CaseInsensitive) == 0)
643 unsigned int duration = val.toUInt(&ok);
644 if(ok) info.setFileDuration(duration);
646 if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0)
649 unsigned int samplerate = val.toUInt(&ok);
650 if(ok) info.setFormatAudioSamplerate (samplerate);
652 if(key.compare("Channels", Qt::CaseInsensitive) == 0)
655 unsigned int channels = val.toUInt(&ok);
656 if(ok) info.setFormatAudioChannels(channels);
658 if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0)
661 unsigned int bitdepth = val.toUInt(&ok);
662 if(ok) info.setFormatAudioBitdepth(bitdepth);
668 if(line.contains("[Audio Info]", Qt::CaseInsensitive))
670 info.setFormatAudioType("Avisynth");
671 info.setFormatContainerType("Avisynth");
672 bInfoHeaderFound = true;
679 process.waitForFinished();
680 if(process.state() != QProcess::NotRunning)
683 process.waitForFinished(-1);
687 switch(process.exitCode())
690 qDebug("Avisynth script was analyzed successfully.");
694 qWarning("It appears that Avisynth is not installed on the system!");
698 qWarning("Failed to open the Avisynth script, bad AVS file?");
704 bool FileAnalyzer_ST::createTemplate(void)
708 qWarning("Template file already exists!");
712 QString templatePath = QString("%1/%2.txt").arg(lamexp_temp_folder2(), lamexp_rand_str());
714 QFile templateFile(templatePath);
715 if(!templateFile.open(QIODevice::WriteOnly))
720 templateFile.write("General;");
721 for(size_t i = 0; g_tags_gen[i]; i++)
723 templateFile.write(QString("Gen_%1=%%1%\\n").arg(g_tags_gen[i]).toLatin1().constData());
725 templateFile.write("\\n\r\n");
727 templateFile.write("Audio;");
728 for(size_t i = 0; g_tags_aud[i]; i++)
730 templateFile.write(QString("Aud_%1=%%1%\\n").arg(g_tags_aud[i]).toLatin1().constData());
732 templateFile.write("\\n\r\n");
734 bool success = (templateFile.error() == QFile::NoError);
735 templateFile.close();
739 QFile::remove(templatePath);
745 m_templateFile = new LockedFile(templatePath);
749 qWarning("Failed to lock template file!");
756 unsigned int FileAnalyzer_ST::parseYear(const QString &str)
758 if(str.startsWith("UTC", Qt::CaseInsensitive))
760 QDate date = QDate::fromString(str.mid(3).trimmed().left(10), "yyyy-MM-dd");
773 int year = str.toInt(&ok);
785 unsigned int FileAnalyzer_ST::parseDuration(const QString &str)
788 unsigned int value = str.toUInt(&ok);
789 return ok ? (value/1000) : 0;
792 ////////////////////////////////////////////////////////////
794 ////////////////////////////////////////////////////////////
796 unsigned int FileAnalyzer_ST::filesAccepted(void)
798 return m_filesAccepted;
801 unsigned int FileAnalyzer_ST::filesRejected(void)
803 return m_filesRejected;
806 unsigned int FileAnalyzer_ST::filesDenied(void)
808 return m_filesDenied;
811 unsigned int FileAnalyzer_ST::filesDummyCDDA(void)
813 return m_filesDummyCDDA;
816 unsigned int FileAnalyzer_ST::filesCueSheet(void)
818 return m_filesCueSheet;
821 ////////////////////////////////////////////////////////////
823 ////////////////////////////////////////////////////////////