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 #include "Thread_FileAnalyzer.h"
25 #include "LockedFile.h"
26 #include "Model_AudioFile.h"
27 #include "PlaylistImporter.h"
39 #define IS_KEY(KEY) (key.compare(KEY, Qt::CaseInsensitive) == 0)
40 #define IS_SEC(SEC) (key.startsWith((SEC "_"), Qt::CaseInsensitive))
41 #define FIRST_TOK(STR) (STR.split(" ", QString::SkipEmptyParts).first())
43 ////////////////////////////////////////////////////////////
45 ////////////////////////////////////////////////////////////
47 FileAnalyzer::FileAnalyzer(const QStringList &inputFiles)
49 m_inputFiles(inputFiles),
50 m_mediaInfoBin(lamexp_lookup_tool("mediainfo.exe")),
51 m_avs2wavBin(lamexp_lookup_tool("avs2wav.exe")),
58 if(m_mediaInfoBin.isEmpty())
60 qFatal("Invalid path to MediaInfo binary. Tool not initialized properly.");
70 FileAnalyzer::~FileAnalyzer(void)
74 QString templatePath = m_templateFile->filePath();
75 LAMEXP_DELETE(m_templateFile);
76 if(QFile::exists(templatePath)) QFile::remove(templatePath);
80 ////////////////////////////////////////////////////////////
82 ////////////////////////////////////////////////////////////
84 const char *FileAnalyzer::g_tags_gen[] =
93 "Artist", "Performer",
96 "Released_Date", "Recorded_Date",
105 const char *FileAnalyzer::g_tags_aud[] =
118 ////////////////////////////////////////////////////////////
120 ////////////////////////////////////////////////////////////
122 void FileAnalyzer::run()
130 m_filesDummyCDDA = 0;
134 m_recentlyAdded.clear();
139 if(!createTemplate())
141 qWarning("Failed to create template file!");
146 while(!m_inputFiles.isEmpty())
148 int fileType = fileTypeNormal;
149 QString currentFile = QDir::fromNativeSeparators(m_inputFiles.takeFirst());
150 qDebug("Analyzing: %s", currentFile.toUtf8().constData());
151 emit fileSelected(QFileInfo(currentFile).fileName());
152 AudioFileModel file = analyzeFile(currentFile, &fileType);
156 MessageBeep(MB_ICONERROR);
158 qWarning("Operation cancelled by user!");
161 if(fileType == fileTypeSkip)
163 qWarning("File was recently added, skipping!");
166 if(fileType == fileTypeDenied)
169 qWarning("Cannot access file for reading, skipping!");
172 if(fileType == fileTypeCDDA)
175 qWarning("Dummy CDDA file detected, skipping!");
179 if(file.fileName().isEmpty() || file.formatContainerType().isEmpty() || file.formatAudioType().isEmpty())
181 if(PlaylistImporter::importPlaylist(m_inputFiles, currentFile))
183 qDebug("Imported playlist file.");
185 else if(!QFileInfo(currentFile).suffix().compare("cue", Qt::CaseInsensitive))
187 qWarning("Cue Sheet file detected, skipping!");
190 else if(!QFileInfo(currentFile).suffix().compare("avs", Qt::CaseInsensitive))
192 qDebug("Found a potential Avisynth script, investigating...");
193 if(analyzeAvisynthFile(currentFile, file))
196 emit fileAnalyzed(file);
200 qDebug("Rejected Avisynth file: %s", file.filePath().toUtf8().constData());
206 qDebug("Rejected file of unknown type: %s", file.filePath().toUtf8().constData());
213 m_recentlyAdded.append(file.filePath());
214 emit fileAnalyzed(file);
217 qDebug("All files added.\n");
221 ////////////////////////////////////////////////////////////
223 ////////////////////////////////////////////////////////////
225 const AudioFileModel FileAnalyzer::analyzeFile(const QString &filePath, int *type)
227 *type = fileTypeNormal;
229 AudioFileModel audioFile(filePath);
231 if(m_recentlyAdded.contains(filePath, Qt::CaseInsensitive))
233 *type = fileTypeSkip;
237 QFile readTest(filePath);
238 if(!readTest.open(QIODevice::ReadOnly))
240 *type = fileTypeDenied;
243 if(checkFile_CDDA(readTest))
245 *type = fileTypeCDDA;
250 bool skipNext = false;
251 unsigned int id_val[2] = {UINT_MAX, UINT_MAX};
252 cover_t coverType = coverNone;
253 QByteArray coverData;
256 params << QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile->filePath()));
257 params << QDir::toNativeSeparators(filePath);
260 process.setProcessChannelMode(QProcess::MergedChannels);
261 process.setReadChannel(QProcess::StandardOutput);
262 process.start(m_mediaInfoBin, params);
264 if(!process.waitForStarted())
266 qWarning("MediaInfo process failed to create!");
267 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
269 process.waitForFinished(-1);
273 while(process.state() != QProcess::NotRunning)
278 qWarning("Process was aborted on user request!");
282 if(!process.waitForReadyRead())
284 if(process.state() == QProcess::Running)
286 qWarning("MediaInfo time out. Killing process and skipping file!");
288 process.waitForFinished(-1);
295 while(process.canReadLine())
297 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
300 //qDebug("Line:%s", line.toUtf8().constData());
302 int index = line.indexOf('=');
305 QString key = line.left(index).trimmed();
306 QString val = line.mid(index+1).trimmed();
309 updateInfo(audioFile, &skipNext, id_val, &coverType, &coverData, key, val);
316 if(audioFile.fileName().isEmpty())
318 QString baseName = QFileInfo(filePath).fileName();
319 int index = baseName.lastIndexOf(".");
323 baseName = baseName.left(index);
326 baseName = baseName.replace("_", " ").simplified();
327 index = baseName.lastIndexOf(" - ");
331 baseName = baseName.mid(index + 3).trimmed();
334 audioFile.setFileName(baseName);
337 process.waitForFinished();
338 if(process.state() != QProcess::NotRunning)
341 process.waitForFinished(-1);
344 if((coverType != coverNone) && (!coverData.isEmpty()))
346 retrieveCover(audioFile, coverType, coverData);
352 void FileAnalyzer::updateInfo(AudioFileModel &audioFile, bool *skipNext, unsigned int *id_val, cover_t *coverType, QByteArray *coverData, const QString &key, const QString &value)
354 //qWarning("'%s' -> '%s'", key.toUtf8().constData(), value.toUtf8().constData());
357 if(IS_KEY("Gen_ID") || IS_KEY("Aud_ID"))
365 //We ignore all ID's, except for the lowest one!
367 unsigned int id = value.toUInt(&ok);
370 if(IS_KEY("Gen_ID")) { id_val[0] = qMin(id_val[0], id); *skipNext = (id > id_val[0]); }
371 if(IS_KEY("Aud_ID")) { id_val[1] = qMin(id_val[1], id); *skipNext = (id > id_val[1]); }
380 qWarning("Skipping info for non-primary stream!");
386 if((*skipNext) || value.isEmpty())
394 if(IS_KEY("Gen_Format"))
396 audioFile.setFormatContainerType(value);
398 else if(IS_KEY("Gen_Format_Profile"))
400 audioFile.setFormatContainerProfile(value);
402 else if(IS_KEY("Gen_Title") || IS_KEY("Gen_Track"))
404 audioFile.setFileName(value);
406 else if(IS_KEY("Gen_Duration"))
408 unsigned int tmp = parseDuration(value);
409 if(tmp > 0) audioFile.setFileDuration(tmp);
411 else if(IS_KEY("Gen_Artist") || IS_KEY("Gen_Performer"))
413 audioFile.setFileArtist(value);
415 else if(IS_KEY("Gen_Album"))
417 audioFile.setFileAlbum(value);
419 else if(IS_KEY("Gen_Genre"))
421 audioFile.setFileGenre(value);
423 else if(IS_KEY("Gen_Released_Date") || IS_KEY("Gen_Recorded_Date"))
425 unsigned int tmp = parseYear(value);
426 if(tmp > 0) audioFile.setFileYear(tmp);
428 else if(IS_KEY("Gen_Comment"))
430 audioFile.setFileComment(value);
432 else if(IS_KEY("Gen_Track/Position"))
435 unsigned int tmp = value.toUInt(&ok);
436 if(ok) audioFile.setFilePosition(tmp);
438 else if(IS_KEY("Gen_Cover") || IS_KEY("Gen_Cover_Type"))
440 if(*coverType == coverNone)
442 *coverType = coverJpeg;
445 else if(IS_KEY("Gen_Cover_Mime"))
447 QString temp = FIRST_TOK(value);
448 if(!temp.compare("image/jpeg", Qt::CaseInsensitive)) *coverType = coverJpeg;
449 else if(!temp.compare("image/png", Qt::CaseInsensitive)) *coverType = coverPng;
450 else if(!temp.compare("image/gif", Qt::CaseInsensitive)) *coverType = coverGif;
452 else if(IS_KEY("Gen_Cover_Data"))
454 if(!coverData->isEmpty()) coverData->clear();
455 coverData->append(QByteArray::fromBase64(FIRST_TOK(value).toLatin1()));
459 qWarning("Unknown key '%s' with value '%s' found!", key.toUtf8().constData(), value.toUtf8().constData());
468 if(IS_KEY("Aud_Format"))
470 audioFile.setFormatAudioType(value);
472 else if(IS_KEY("Aud_Format_Profile"))
474 audioFile.setFormatAudioProfile(value);
476 else if(IS_KEY("Aud_Format_Version"))
478 audioFile.setFormatAudioVersion(value);
480 else if(IS_KEY("Aud_Channel(s)"))
483 unsigned int tmp = value.toUInt(&ok);
484 if(ok) audioFile.setFormatAudioChannels(tmp);
486 else if(IS_KEY("Aud_SamplingRate"))
489 unsigned int tmp = value.toUInt(&ok);
490 if(ok) audioFile.setFormatAudioSamplerate(tmp);
492 else if(IS_KEY("Aud_BitDepth"))
495 unsigned int tmp = value.toUInt(&ok);
496 if(ok) audioFile.setFormatAudioBitdepth(tmp);
498 else if(IS_KEY("Aud_Duration"))
500 unsigned int tmp = parseDuration(value);
501 if(tmp > 0) audioFile.setFileDuration(tmp);
503 else if(IS_KEY("Aud_BitRate"))
506 unsigned int tmp = value.toUInt(&ok);
507 if(ok) audioFile.setFormatAudioBitrate(tmp/1000);
509 else if(IS_KEY("Aud_BitRate_Mode"))
511 if(!value.compare("CBR", Qt::CaseInsensitive)) audioFile.setFormatAudioBitrateMode(AudioFileModel::BitrateModeConstant);
512 if(!value.compare("VBR", Qt::CaseInsensitive)) audioFile.setFormatAudioBitrateMode(AudioFileModel::BitrateModeVariable);
516 qWarning("Unknown key '%s' with value '%s' found!", key.toUtf8().constData(), value.toUtf8().constData());
521 /*Section not recognized*/
522 qWarning("Unknown section: %s", key.toUtf8().constData());
525 bool FileAnalyzer::checkFile_CDDA(QFile &file)
528 QByteArray data = file.read(128);
530 int i = data.indexOf("RIFF");
531 int j = data.indexOf("CDDA");
532 int k = data.indexOf("fmt ");
534 return ((i >= 0) && (j >= 0) && (k >= 0) && (k > j) && (j > i));
537 void FileAnalyzer::retrieveCover(AudioFileModel &audioFile, cover_t coverType, const QByteArray &coverData)
539 qDebug("Retrieving cover!");
545 extension = QString::fromLatin1("png");
548 extension = QString::fromLatin1("gif");
551 extension = QString::fromLatin1("jpg");
555 if(!(QImage::fromData(coverData, extension.toUpper().toLatin1().constData()).isNull()))
557 QFile coverFile(QString("%1/%2.%3").arg(lamexp_temp_folder2(), lamexp_rand_str(), extension));
558 if(coverFile.open(QIODevice::WriteOnly))
560 coverFile.write(coverData);
562 audioFile.setFileCover(coverFile.fileName(), true);
567 qWarning("Image data seems to be invalid :-(");
571 bool FileAnalyzer::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
574 process.setProcessChannelMode(QProcess::MergedChannels);
575 process.setReadChannel(QProcess::StandardOutput);
576 process.start(m_avs2wavBin, QStringList() << QDir::toNativeSeparators(filePath) << "?");
578 if(!process.waitForStarted())
580 qWarning("AVS2WAV process failed to create!");
581 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
583 process.waitForFinished(-1);
587 bool bInfoHeaderFound = false;
589 while(process.state() != QProcess::NotRunning)
594 qWarning("Process was aborted on user request!");
598 if(!process.waitForReadyRead())
600 if(process.state() == QProcess::Running)
602 qWarning("AVS2WAV time out. Killing process and skipping file!");
604 process.waitForFinished(-1);
611 while(process.canReadLine())
613 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
616 int index = line.indexOf(':');
619 QString key = line.left(index).trimmed();
620 QString val = line.mid(index+1).trimmed();
622 if(bInfoHeaderFound && !key.isEmpty() && !val.isEmpty())
624 if(key.compare("TotalSeconds", Qt::CaseInsensitive) == 0)
627 unsigned int duration = val.toUInt(&ok);
628 if(ok) info.setFileDuration(duration);
630 if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0)
633 unsigned int samplerate = val.toUInt(&ok);
634 if(ok) info.setFormatAudioSamplerate (samplerate);
636 if(key.compare("Channels", Qt::CaseInsensitive) == 0)
639 unsigned int channels = val.toUInt(&ok);
640 if(ok) info.setFormatAudioChannels(channels);
642 if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0)
645 unsigned int bitdepth = val.toUInt(&ok);
646 if(ok) info.setFormatAudioBitdepth(bitdepth);
652 if(line.contains("[Audio Info]", Qt::CaseInsensitive))
654 info.setFormatAudioType("Avisynth");
655 info.setFormatContainerType("Avisynth");
656 bInfoHeaderFound = true;
663 process.waitForFinished();
664 if(process.state() != QProcess::NotRunning)
667 process.waitForFinished(-1);
671 switch(process.exitCode())
674 qDebug("Avisynth script was analyzed successfully.");
678 qWarning("It appears that Avisynth is not installed on the system!");
682 qWarning("Failed to open the Avisynth script, bad AVS file?");
688 bool FileAnalyzer::createTemplate(void)
692 qWarning("Template file already exists!");
696 QString templatePath = QString("%1/%2.txt").arg(lamexp_temp_folder2(), lamexp_rand_str());
698 QFile templateFile(templatePath);
699 if(!templateFile.open(QIODevice::WriteOnly))
704 templateFile.write("General;");
705 for(size_t i = 0; g_tags_gen[i]; i++)
707 templateFile.write(QString("Gen_%1=%%1%\\n").arg(g_tags_gen[i]).toLatin1().constData());
709 templateFile.write("\\n\r\n");
711 templateFile.write("Audio;");
712 for(size_t i = 0; g_tags_aud[i]; i++)
714 templateFile.write(QString("Aud_%1=%%1%\\n").arg(g_tags_aud[i]).toLatin1().constData());
716 templateFile.write("\\n\r\n");
718 bool success = (templateFile.error() == QFile::NoError);
719 templateFile.close();
723 QFile::remove(templatePath);
729 m_templateFile = new LockedFile(templatePath);
733 qWarning("Failed to lock template file!");
740 unsigned int FileAnalyzer::parseYear(const QString &str)
742 if(str.startsWith("UTC", Qt::CaseInsensitive))
744 QDate date = QDate::fromString(str.mid(3).trimmed().left(10), "yyyy-MM-dd");
757 int year = str.toInt(&ok);
769 unsigned int FileAnalyzer::parseDuration(const QString &str)
772 unsigned int value = str.toUInt(&ok);
773 return ok ? (value/1000) : 0;
776 ////////////////////////////////////////////////////////////
778 ////////////////////////////////////////////////////////////
780 unsigned int FileAnalyzer::filesAccepted(void)
782 return m_filesAccepted;
785 unsigned int FileAnalyzer::filesRejected(void)
787 return m_filesRejected;
790 unsigned int FileAnalyzer::filesDenied(void)
792 return m_filesDenied;
795 unsigned int FileAnalyzer::filesDummyCDDA(void)
797 return m_filesDummyCDDA;
800 unsigned int FileAnalyzer::filesCueSheet(void)
802 return m_filesCueSheet;
805 ////////////////////////////////////////////////////////////
807 ////////////////////////////////////////////////////////////