Updated Simplified Chinese translation, thanks to <kidneybean@sohu.com>.
[LameXP.git] / src / Thread_FileAnalyzer_ST.cpp
blob60e5600eee3ba11c233533f7f4c60d4de9480c03
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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.
9 //
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"
28 #include "Global.h"
29 #include "LockedFile.h"
30 #include "Model_AudioFile.h"
31 #include "PlaylistImporter.h"
33 #include <QDir>
34 #include <QFileInfo>
35 #include <QProcess>
36 #include <QDate>
37 #include <QTime>
38 #include <QDebug>
39 #include <QImage>
41 #include <math.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 ////////////////////////////////////////////////////////////
48 // Constructor
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")),
56 m_templateFile(NULL),
57 m_abortFlag(false)
59 m_bSuccess = false;
60 m_bAborted = false;
62 if(m_mediaInfoBin.isEmpty())
64 qFatal("Invalid path to MediaInfo binary. Tool not initialized properly.");
67 m_filesAccepted = 0;
68 m_filesRejected = 0;
69 m_filesDenied = 0;
70 m_filesDummyCDDA = 0;
71 m_filesCueSheet = 0;
74 FileAnalyzer_ST::~FileAnalyzer_ST(void)
76 if(m_templateFile)
78 QString templatePath = m_templateFile->filePath();
79 LAMEXP_DELETE(m_templateFile);
80 if(QFile::exists(templatePath)) QFile::remove(templatePath);
84 ////////////////////////////////////////////////////////////
85 // Static data
86 ////////////////////////////////////////////////////////////
88 const char *FileAnalyzer_ST::g_tags_gen[] =
90 "ID",
91 "Format",
92 "Format_Profile",
93 "Format_Version",
94 "Duration",
95 "Title", "Track",
96 "Track/Position",
97 "Artist", "Performer",
98 "Album",
99 "Genre",
100 "Released_Date", "Recorded_Date",
101 "Comment",
102 "Cover",
103 "Cover_Type",
104 "Cover_Mime",
105 "Cover_Data",
106 NULL
109 const char *FileAnalyzer_ST::g_tags_aud[] =
111 "ID",
112 "Source",
113 "Format",
114 "Format_Profile",
115 "Format_Version",
116 "Channel(s)",
117 "SamplingRate",
118 "BitDepth",
119 "BitRate",
120 "BitRate_Mode",
121 NULL
124 ////////////////////////////////////////////////////////////
125 // Thread Main
126 ////////////////////////////////////////////////////////////
128 void FileAnalyzer_ST::run()
130 m_bSuccess = false;
131 m_bAborted = false;
133 m_filesAccepted = 0;
134 m_filesRejected = 0;
135 m_filesDenied = 0;
136 m_filesDummyCDDA = 0;
137 m_filesCueSheet = 0;
139 lamexp_natural_string_sort(m_inputFiles); // .sort()
141 m_recentlyAdded.clear();
142 m_abortFlag = false;
144 if(!m_templateFile)
146 if(!createTemplate())
148 qWarning("Failed to create template file!");
149 return;
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);
161 if(m_abortFlag)
163 MessageBeep(MB_ICONERROR);
164 m_bAborted = true;
165 qWarning("Operation cancelled by user!");
166 return;
168 if(fileType == fileTypeSkip)
170 qWarning("File was recently added, skipping!");
171 continue;
173 if(fileType == fileTypeDenied)
175 m_filesDenied++;
176 qWarning("Cannot access file for reading, skipping!");
177 continue;
179 if(fileType == fileTypeCDDA)
181 m_filesDummyCDDA++;
182 qWarning("Dummy CDDA file detected, skipping!");
183 continue;
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!");
195 m_filesCueSheet++;
197 else if(!QFileInfo(currentFile).suffix().compare("avs", Qt::CaseInsensitive))
199 qDebug("Found a potential Avisynth script, investigating...");
200 if(analyzeAvisynthFile(currentFile, file))
202 m_filesAccepted++;
203 emit fileAnalyzed(file);
205 else
207 qDebug("Rejected Avisynth file: %s", file.filePath().toUtf8().constData());
208 m_filesRejected++;
211 else
213 qDebug("Rejected file of unknown type: %s", file.filePath().toUtf8().constData());
214 m_filesRejected++;
216 continue;
219 m_filesAccepted++;
220 m_recentlyAdded.append(file.filePath());
221 emit fileAnalyzed(file);
224 qDebug("All files added.\n");
225 m_bSuccess = true;
228 ////////////////////////////////////////////////////////////
229 // Privtae Functions
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;
241 return audioFile;
244 QFile readTest(filePath);
245 if(!readTest.open(QIODevice::ReadOnly))
247 *type = fileTypeDenied;
248 return audioFile;
250 if(checkFile_CDDA(readTest))
252 *type = fileTypeCDDA;
253 return audioFile;
255 readTest.close();
257 bool skipNext = false;
258 unsigned int id_val[2] = {UINT_MAX, UINT_MAX};
259 cover_t coverType = coverNone;
260 QByteArray coverData;
262 QStringList params;
263 params << QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile->filePath()));
264 params << QDir::toNativeSeparators(filePath);
266 QProcess process;
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());
275 process.kill();
276 process.waitForFinished(-1);
277 return audioFile;
280 while(process.state() != QProcess::NotRunning)
282 if(m_abortFlag)
284 process.kill();
285 qWarning("Process was aborted on user request!");
286 break;
289 if(!process.waitForReadyRead())
291 if(process.state() == QProcess::Running)
293 qWarning("MediaInfo time out. Killing process and skipping file!");
294 process.kill();
295 process.waitForFinished(-1);
296 return audioFile;
300 QByteArray data;
302 while(process.canReadLine())
304 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
305 if(!line.isEmpty())
307 //qDebug("Line:%s", line.toUtf8().constData());
309 int index = line.indexOf('=');
310 if(index > 0)
312 QString key = line.left(index).trimmed();
313 QString val = line.mid(index+1).trimmed();
314 if(!key.isEmpty())
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(".");
328 if(index >= 0)
330 baseName = baseName.left(index);
333 baseName = baseName.replace("_", " ").simplified();
334 index = baseName.lastIndexOf(" - ");
336 if(index >= 0)
338 baseName = baseName.mid(index + 3).trimmed();
341 audioFile.setFileName(baseName);
344 process.waitForFinished();
345 if(process.state() != QProcess::NotRunning)
347 process.kill();
348 process.waitForFinished(-1);
351 if((coverType != coverNone) && (!coverData.isEmpty()))
353 retrieveCover(audioFile, coverType, coverData);
356 return audioFile;
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());
363 /*New Stream*/
364 if(IS_KEY("Gen_ID") || IS_KEY("Aud_ID"))
366 if(value.isEmpty())
368 *skipNext = false;
370 else
372 //We ignore all ID's, except for the lowest one!
373 bool ok = false;
374 unsigned int id = value.toUInt(&ok);
375 if(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]); }
380 else
382 *skipNext = true;
385 if(*skipNext)
387 qWarning("Skipping info for non-primary stream!");
389 return;
392 /*Skip or empty?*/
393 if((*skipNext) || value.isEmpty())
395 return;
398 /*Playlist file?*/
399 if(IS_KEY("Aud_Source"))
401 *skipNext = true;
402 audioFile.setFormatContainerType(QString());
403 audioFile.setFormatAudioType(QString());
404 qWarning("Skipping info for playlist file!");
405 return;
408 /*General Section*/
409 if(IS_SEC("Gen"))
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"))
451 bool ok = false;
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()));
474 else
476 qWarning("Unknown key '%s' with value '%s' found!", key.toUtf8().constData(), value.toUtf8().constData());
478 return;
481 /*Audio Section*/
482 if(IS_SEC("Aud"))
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)"))
499 bool ok = false;
500 unsigned int tmp = value.toUInt(&ok);
501 if(ok) audioFile.setFormatAudioChannels(tmp);
503 else if(IS_KEY("Aud_SamplingRate"))
505 bool ok = false;
506 unsigned int tmp = value.toUInt(&ok);
507 if(ok) audioFile.setFormatAudioSamplerate(tmp);
509 else if(IS_KEY("Aud_BitDepth"))
511 bool ok = false;
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"))
522 bool ok = false;
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);
531 else
533 qWarning("Unknown key '%s' with value '%s' found!", key.toUtf8().constData(), value.toUtf8().constData());
535 return;
538 /*Section not recognized*/
539 qWarning("Unknown section: %s", key.toUtf8().constData());
542 bool FileAnalyzer_ST::checkFile_CDDA(QFile &file)
544 file.reset();
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!");
557 QString extension;
559 switch(coverType)
561 case coverPng:
562 extension = QString::fromLatin1("png");
563 break;
564 case coverGif:
565 extension = QString::fromLatin1("gif");
566 break;
567 default:
568 extension = QString::fromLatin1("jpg");
569 break;
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);
578 coverFile.close();
579 audioFile.setFileCover(coverFile.fileName(), true);
582 else
584 qWarning("Image data seems to be invalid :-(");
588 bool FileAnalyzer_ST::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
590 QProcess process;
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());
599 process.kill();
600 process.waitForFinished(-1);
601 return false;
604 bool bInfoHeaderFound = false;
606 while(process.state() != QProcess::NotRunning)
608 if(m_abortFlag)
610 process.kill();
611 qWarning("Process was aborted on user request!");
612 break;
615 if(!process.waitForReadyRead())
617 if(process.state() == QProcess::Running)
619 qWarning("AVS2WAV time out. Killing process and skipping file!");
620 process.kill();
621 process.waitForFinished(-1);
622 return false;
626 QByteArray data;
628 while(process.canReadLine())
630 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
631 if(!line.isEmpty())
633 int index = line.indexOf(':');
634 if(index > 0)
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)
643 bool ok = false;
644 unsigned int duration = val.toUInt(&ok);
645 if(ok) info.setFileDuration(duration);
647 if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0)
649 bool ok = false;
650 unsigned int samplerate = val.toUInt(&ok);
651 if(ok) info.setFormatAudioSamplerate (samplerate);
653 if(key.compare("Channels", Qt::CaseInsensitive) == 0)
655 bool ok = false;
656 unsigned int channels = val.toUInt(&ok);
657 if(ok) info.setFormatAudioChannels(channels);
659 if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0)
661 bool ok = false;
662 unsigned int bitdepth = val.toUInt(&ok);
663 if(ok) info.setFormatAudioBitdepth(bitdepth);
667 else
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)
683 process.kill();
684 process.waitForFinished(-1);
687 //Check exit code
688 switch(process.exitCode())
690 case 0:
691 qDebug("Avisynth script was analyzed successfully.");
692 return true;
693 break;
694 case -5:
695 qWarning("It appears that Avisynth is not installed on the system!");
696 return false;
697 break;
698 default:
699 qWarning("Failed to open the Avisynth script, bad AVS file?");
700 return false;
701 break;
705 bool FileAnalyzer_ST::createTemplate(void)
707 if(m_templateFile)
709 qWarning("Template file already exists!");
710 return true;
713 QString templatePath = QString("%1/%2.txt").arg(lamexp_temp_folder2(), lamexp_rand_str());
715 QFile templateFile(templatePath);
716 if(!templateFile.open(QIODevice::WriteOnly))
718 return false;
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();
738 if(!success)
740 QFile::remove(templatePath);
741 return false;
746 m_templateFile = new LockedFile(templatePath);
748 catch(...)
750 qWarning("Failed to lock template file!");
751 return false;
754 return true;
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");
762 if(date.isValid())
764 return date.year();
766 else
768 return 0;
771 else
773 bool ok = false;
774 int year = str.toInt(&ok);
775 if(ok && year > 0)
777 return year;
779 else
781 return 0;
786 unsigned int FileAnalyzer_ST::parseDuration(const QString &str)
788 bool ok = false;
789 unsigned int value = str.toUInt(&ok);
790 return ok ? (value/1000) : 0;
793 ////////////////////////////////////////////////////////////
794 // Public Functions
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 ////////////////////////////////////////////////////////////
823 // EVENTS
824 ////////////////////////////////////////////////////////////
826 /*NONE*/