Updated MediaInfo binary to v0.7.48 (2011-08-17), compiled with MSVC 10.0
[LameXP.git] / src / Thread_FileAnalyzer.cpp
blob21c7aedac02533466f791c231bdc005e09dd86f0
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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 #include "Thread_FileAnalyzer.h"
24 #include "Global.h"
25 #include "LockedFile.h"
26 #include "Model_AudioFile.h"
27 #include "PlaylistImporter.h"
29 #include <QDir>
30 #include <QFileInfo>
31 #include <QProcess>
32 #include <QDate>
33 #include <QTime>
34 #include <QDebug>
36 #include <math.h>
38 ////////////////////////////////////////////////////////////
39 // Constructor
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")),
47 m_abortFlag(false)
49 m_bSuccess = false;
50 m_bAborted = false;
52 if(m_mediaInfoBin.isEmpty())
54 qFatal("Invalid path to MediaInfo binary. Tool not initialized properly.");
57 m_filesAccepted = 0;
58 m_filesRejected = 0;
59 m_filesDenied = 0;
60 m_filesDummyCDDA = 0;
61 m_filesCueSheet = 0;
64 ////////////////////////////////////////////////////////////
65 // Thread Main
66 ////////////////////////////////////////////////////////////
68 void FileAnalyzer::run()
70 m_bSuccess = false;
71 m_bAborted = false;
73 m_filesAccepted = 0;
74 m_filesRejected = 0;
75 m_filesDenied = 0;
76 m_filesDummyCDDA = 0;
77 m_filesCueSheet = 0;
79 m_inputFiles.sort();
80 m_abortFlag = false;
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);
90 if(m_abortFlag)
92 MessageBeep(MB_ICONERROR);
93 m_bAborted = true;
94 qWarning("Operation cancelled by user!");
95 return;
98 if(fileType == fileTypeDenied)
100 m_filesDenied++;
101 qWarning("Cannot access file for reading, skipping!");
102 continue;
104 if(fileType == fileTypeCDDA)
106 m_filesDummyCDDA++;
107 qWarning("Dummy CDDA file detected, skipping!");
108 continue;
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!");
120 m_filesCueSheet++;
122 else if(!QFileInfo(currentFile).suffix().compare("avs", Qt::CaseInsensitive))
124 qDebug("Found a potential Avisynth script, investigating...");
125 if(analyzeAvisynthFile(currentFile, file))
127 m_filesAccepted++;
128 emit fileAnalyzed(file);
130 else
132 qDebug64("Rejected Avisynth file: %1", file.filePath());
133 m_filesRejected++;
136 else
138 qDebug64("Rejected file of unknown type: %1", file.filePath());
139 m_filesRejected++;
141 continue;
144 m_filesAccepted++;
145 emit fileAnalyzed(file);
148 qDebug("All files added.\n");
149 m_bSuccess = true;
152 ////////////////////////////////////////////////////////////
153 // Privtae Functions
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;
168 return audioFile;
171 if(checkFile_CDDA(readTest))
173 *type = fileTypeCDDA;
174 return audioFile;
177 readTest.close();
179 QProcess process;
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());
188 process.kill();
189 process.waitForFinished(-1);
190 return audioFile;
193 while(process.state() != QProcess::NotRunning)
195 if(m_abortFlag)
197 process.kill();
198 qWarning("Process was aborted on user request!");
199 break;
202 if(!process.waitForReadyRead())
204 if(process.state() == QProcess::Running)
206 qWarning("MediaInfo time out. Killing process and skipping file!");
207 process.kill();
208 process.waitForFinished(-1);
209 return audioFile;
213 QByteArray data;
215 while(process.canReadLine())
217 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
218 if(!line.isEmpty())
220 int index = line.indexOf(':');
221 if(index > 0)
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);
230 else
232 updateSection(line);
238 if(audioFile.fileName().isEmpty())
240 QString baseName = QFileInfo(filePath).fileName();
241 int index = baseName.lastIndexOf(".");
243 if(index >= 0)
245 baseName = baseName.left(index);
248 baseName = baseName.replace("_", " ").simplified();
249 index = baseName.lastIndexOf(" - ");
251 if(index >= 0)
253 baseName = baseName.mid(index + 3).trimmed();
256 audioFile.setFileName(baseName);
259 process.waitForFinished();
260 if(process.state() != QProcess::NotRunning)
262 process.kill();
263 process.waitForFinished(-1);
266 if(m_currentCover != coverNone)
268 retrieveCover(audioFile, filePath);
271 return audioFile;
274 void FileAnalyzer::updateSection(const QString &section)
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;
289 else
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)
300 case sectionGeneral:
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;
361 break;
363 case sectionAudio:
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())
388 bool ok = false;
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())
405 bool ok = false;
406 unsigned int uiTemp = value.split(" ", QString::SkipEmptyParts).first().toUInt(&ok);
407 if(ok)
409 audioFile.setFormatAudioBitrate(uiTemp);
411 else
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);
426 break;
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");
435 if(date.isValid())
437 return date.year();
439 else
441 return 0;
444 else
446 bool ok = false;
447 int year = str.toInt(&ok);
448 if(ok && year > 0)
450 return year;
452 else
454 return 0;
459 unsigned int FileAnalyzer::parseDuration(const QString &str)
461 QTime time;
463 time = QTime::fromString(str, "z'ms'");
464 if(time.isValid())
466 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
469 time = QTime::fromString(str, "s's 'z'ms'");
470 if(time.isValid())
472 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
475 time = QTime::fromString(str, "m'mn 's's'");
476 if(time.isValid())
478 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
481 time = QTime::fromString(str, "h'h 'm'mn'");
482 if(time.isValid())
484 return max(1, (time.hour() * 60 * 60) + (time.minute() * 60) + time.second());
487 return 0;
490 bool FileAnalyzer::checkFile_CDDA(QFile &file)
492 file.reset();
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);
505 QString extension;
507 switch(m_currentCover)
509 case coverPng:
510 extension = QString::fromLatin1("png");
511 break;
512 case coverGif:
513 extension = QString::fromLatin1("gif");
514 break;
515 default:
516 extension = QString::fromLatin1("jpg");
517 break;
520 QProcess process;
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());
529 process.kill();
530 process.waitForFinished(-1);
531 return;
534 while(process.state() != QProcess::NotRunning)
536 if(m_abortFlag)
538 process.kill();
539 qWarning("Process was aborted on user request!");
540 break;
543 if(!process.waitForReadyRead())
545 if(process.state() == QProcess::Running)
547 qWarning("MediaInfo time out. Killing process and skipping file!");
548 process.kill();
549 process.waitForFinished(-1);
550 return;
554 while(process.canReadLine())
556 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
557 if(!line.isEmpty())
559 int index = line.indexOf(':');
560 if(index > 0)
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);
577 coverFile.close();
578 audioFile.setFileCover(coverFile.fileName(), true);
580 break;
588 process.waitForFinished();
589 if(process.state() != QProcess::NotRunning)
591 process.kill();
592 process.waitForFinished(-1);
596 bool FileAnalyzer::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
598 QProcess process;
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());
607 process.kill();
608 process.waitForFinished(-1);
609 return false;
612 bool bInfoHeaderFound = false;
614 while(process.state() != QProcess::NotRunning)
616 if(m_abortFlag)
618 process.kill();
619 qWarning("Process was aborted on user request!");
620 break;
623 if(!process.waitForReadyRead())
625 if(process.state() == QProcess::Running)
627 qWarning("AVS2WAV time out. Killing process and skipping file!");
628 process.kill();
629 process.waitForFinished(-1);
630 return false;
634 QByteArray data;
636 while(process.canReadLine())
638 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
639 if(!line.isEmpty())
641 int index = line.indexOf(':');
642 if(index > 0)
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)
651 bool ok = false;
652 unsigned int duration = val.toUInt(&ok);
653 if(ok) info.setFileDuration(duration);
655 if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0)
657 bool ok = false;
658 unsigned int samplerate = val.toUInt(&ok);
659 if(ok) info.setFormatAudioSamplerate (samplerate);
661 if(key.compare("Channels", Qt::CaseInsensitive) == 0)
663 bool ok = false;
664 unsigned int channels = val.toUInt(&ok);
665 if(ok) info.setFormatAudioChannels(channels);
667 if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0)
669 bool ok = false;
670 unsigned int bitdepth = val.toUInt(&ok);
671 if(ok) info.setFormatAudioBitdepth(bitdepth);
675 else
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)
691 process.kill();
692 process.waitForFinished(-1);
695 //Check exit code
696 switch(process.exitCode())
698 case 0:
699 qDebug("Avisynth script was analyzed successfully.");
700 return true;
701 break;
702 case -5:
703 qWarning("It appears that Avisynth is not installed on the system!");
704 return false;
705 break;
706 default:
707 qWarning("Failed to open the Avisynth script, bad AVS file?");
708 return false;
709 break;
713 ////////////////////////////////////////////////////////////
714 // Public Functions
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 ////////////////////////////////////////////////////////////
743 // EVENTS
744 ////////////////////////////////////////////////////////////
746 /*NONE*/