Fixed handling of MediaInfo "point" releases in FileAnalyzer_Task.
[LameXP.git] / src / Thread_FileAnalyzer_Task.cpp
blobfd69a24af86031f61c3f8579a06fc896df43c82b
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2018 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Thread_FileAnalyzer_Task.h"
25 //Internal
26 #include "Global.h"
27 #include "LockedFile.h"
28 #include "Model_AudioFile.h"
29 #include "MimeTypes.h"
31 //MUtils
32 #include <MUtils/Global.h>
33 #include <MUtils/OSSupport.h>
34 #include <MUtils/Lazy.h>
35 #include <MUtils/Exception.h>
37 //Qt
38 #include <QDir>
39 #include <QFileInfo>
40 #include <QProcess>
41 #include <QDate>
42 #include <QTime>
43 #include <QDebug>
44 #include <QImage>
45 #include <QReadLocker>
46 #include <QWriteLocker>
47 #include <QThread>
48 #include <QXmlSimpleReader>
49 #include <QXmlInputSource>
50 #include <QXmlStreamReader>
51 #include <QStack>
53 //CRT
54 #include <math.h>
55 #include <time.h>
56 #include <assert.h>
58 ////////////////////////////////////////////////////////////
59 // Helper Macros
60 ////////////////////////////////////////////////////////////
62 #define ADD_PROPTERY_MAPPING_1(TYPE, NAME) do \
63 { \
64 ADD_PROPTERY_MAPPING_2(TYPE, NAME, NAME); \
65 } \
66 while(0)
68 #define ADD_PROPTERY_MAPPING_2(TYPE, MI_NAME, LX_NAME) do \
69 { \
70 builder->insert(qMakePair(AnalyzeTask::trackType_##TYPE, QString::fromLatin1(#MI_NAME)), AnalyzeTask::propertyId_##LX_NAME); \
71 } \
72 while(0)
74 #define SET_OPTIONAL(TYPE, IF_CMD, THEN_CMD) do \
75 { \
76 TYPE _tmp;\
77 if((IF_CMD)) { THEN_CMD; } \
78 } \
79 while(0)
81 #define DIV_RND(A,B) (((A) + ((B) / 2U)) / (B))
82 #define STRICMP(A,B) ((A).compare((B), Qt::CaseInsensitive) == 0)
84 ////////////////////////////////////////////////////////////
85 // Static initialization
86 ////////////////////////////////////////////////////////////
88 static MUtils::Lazy<const QMap<QPair<AnalyzeTask::MI_trackType_t, QString>, AnalyzeTask::MI_propertyId_t>> s_mediaInfoIdx([]
90 QMap<QPair<AnalyzeTask::MI_trackType_t, QString>, AnalyzeTask::MI_propertyId_t> *const builder = new QMap<QPair<AnalyzeTask::MI_trackType_t, QString>, AnalyzeTask::MI_propertyId_t>();
91 ADD_PROPTERY_MAPPING_2(gen, format, container);
92 ADD_PROPTERY_MAPPING_2(gen, format_profile, container_profile);
93 ADD_PROPTERY_MAPPING_1(gen, duration);
94 ADD_PROPTERY_MAPPING_1(gen, title);
95 ADD_PROPTERY_MAPPING_2(gen, track, title);
96 ADD_PROPTERY_MAPPING_1(gen, artist);
97 ADD_PROPTERY_MAPPING_2(gen, performer, artist);
98 ADD_PROPTERY_MAPPING_1(gen, album);
99 ADD_PROPTERY_MAPPING_1(gen, genre);
100 ADD_PROPTERY_MAPPING_1(gen, released_date);
101 ADD_PROPTERY_MAPPING_2(gen, recorded_date, released_date);
102 ADD_PROPTERY_MAPPING_1(gen, track_position);
103 ADD_PROPTERY_MAPPING_1(gen, comment);
104 ADD_PROPTERY_MAPPING_1(aud, format);
105 ADD_PROPTERY_MAPPING_1(aud, format_version);
106 ADD_PROPTERY_MAPPING_1(aud, format_profile);
107 ADD_PROPTERY_MAPPING_1(aud, duration);
108 ADD_PROPTERY_MAPPING_1(aud, channel_s_);
109 ADD_PROPTERY_MAPPING_1(aud, samplingrate);
110 ADD_PROPTERY_MAPPING_1(aud, bitdepth);
111 ADD_PROPTERY_MAPPING_1(aud, bitrate);
112 ADD_PROPTERY_MAPPING_1(aud, bitrate_mode);
113 ADD_PROPTERY_MAPPING_1(aud, encoded_library);
114 ADD_PROPTERY_MAPPING_2(gen, cover_mime, cover_mime);
115 ADD_PROPTERY_MAPPING_2(gen, cover_data, cover_data);
116 return builder;
119 static MUtils::Lazy<const QMap<QString, AnalyzeTask::MI_propertyId_t>> s_avisynthIdx([]
121 QMap<QString, AnalyzeTask::MI_propertyId_t> *const builder = new QMap<QString, AnalyzeTask::MI_propertyId_t>();
122 builder->insert(QLatin1String("totalseconds"), AnalyzeTask::propertyId_duration);
123 builder->insert(QLatin1String("samplespersec"), AnalyzeTask::propertyId_samplingrate);
124 builder->insert(QLatin1String("channels"), AnalyzeTask::propertyId_channel_s_);
125 builder->insert(QLatin1String("bitspersample"), AnalyzeTask::propertyId_bitdepth);
126 return builder;
129 static MUtils::Lazy<const QMap<QString, QString>> s_mimeTypes([]
131 QMap<QString, QString> *const builder = new QMap<QString, QString>();
132 for (size_t i = 0U; MIME_TYPES[i].type; ++i)
134 builder->insert(QString::fromLatin1(MIME_TYPES[i].type), QString::fromLatin1(MIME_TYPES[i].ext[0]));
136 return builder;
139 static MUtils::Lazy<const QMap<QString, AnalyzeTask::MI_trackType_t>> s_trackTypes([]
141 QMap<QString, AnalyzeTask::MI_trackType_t> *const builder = new QMap<QString, AnalyzeTask::MI_trackType_t>();
142 builder->insert("general", AnalyzeTask::trackType_gen);
143 builder->insert("audio", AnalyzeTask::trackType_aud);
144 return builder;
147 ////////////////////////////////////////////////////////////
148 // Constructor
149 ////////////////////////////////////////////////////////////
151 AnalyzeTask::AnalyzeTask(const int taskId, const QString &inputFile, QAtomicInt &abortFlag)
153 m_taskId(taskId),
154 m_inputFile(inputFile),
155 m_mediaInfoBin(lamexp_tools_lookup("mediainfo.exe")),
156 m_mediaInfoVer(lamexp_tools_version("mediainfo.exe")),
157 m_avs2wavBin(lamexp_tools_lookup("avs2wav.exe")),
158 m_abortFlag(abortFlag),
159 m_mediaInfoIdx(*s_mediaInfoIdx),
160 m_avisynthIdx(*s_avisynthIdx),
161 m_mimeTypes(*s_mimeTypes),
162 m_trackTypes(*s_trackTypes)
164 if(m_mediaInfoBin.isEmpty() || m_avs2wavBin.isEmpty())
166 qFatal("Invalid path to MediaInfo binary. Tool not initialized properly.");
170 AnalyzeTask::~AnalyzeTask(void)
172 emit taskCompleted(m_taskId);
175 ////////////////////////////////////////////////////////////
176 // Thread Main
177 ////////////////////////////////////////////////////////////
179 void AnalyzeTask::run()
183 run_ex();
185 catch(const std::exception &error)
187 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
188 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
190 catch(...)
192 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
193 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
197 void AnalyzeTask::run_ex(void)
199 int fileType = fileTypeNormal;
200 QString currentFile = QDir::fromNativeSeparators(m_inputFile);
201 qDebug("Analyzing: %s", MUTILS_UTF8(currentFile));
203 AudioFileModel fileInfo(currentFile);
204 analyzeFile(currentFile, fileInfo, &fileType);
206 if(MUTILS_BOOLIFY(m_abortFlag))
208 qWarning("Operation cancelled by user!");
209 return;
212 switch(fileType)
214 case fileTypeDenied:
215 qWarning("Cannot access file for reading, skipping!");
216 break;
217 case fileTypeCDDA:
218 qWarning("Dummy CDDA file detected, skipping!");
219 break;
220 default:
221 if(fileInfo.metaInfo().title().isEmpty() || fileInfo.techInfo().containerType().isEmpty() || fileInfo.techInfo().audioType().isEmpty())
223 fileType = fileTypeUnknown;
224 if(!QFileInfo(currentFile).suffix().compare("cue", Qt::CaseInsensitive))
226 qWarning("Cue Sheet file detected, skipping!");
227 fileType = fileTypeCueSheet;
229 else if(!QFileInfo(currentFile).suffix().compare("avs", Qt::CaseInsensitive))
231 qDebug("Found a potential Avisynth script, investigating...");
232 if(analyzeAvisynthFile(currentFile, fileInfo))
234 fileType = fileTypeNormal;
236 else
238 qDebug("Rejected Avisynth file: %s", MUTILS_UTF8(fileInfo.filePath()));
241 else
243 qDebug("Rejected file of unknown type: %s", MUTILS_UTF8(fileInfo.filePath()));
246 break;
249 //Emit the file now!
250 emit fileAnalyzed(m_taskId, fileType, fileInfo);
253 ////////////////////////////////////////////////////////////
254 // Privtae Functions
255 ////////////////////////////////////////////////////////////
257 const AudioFileModel& AnalyzeTask::analyzeFile(const QString &filePath, AudioFileModel &audioFile, int *const type)
259 *type = fileTypeNormal;
260 QFile readTest(filePath);
262 if (!readTest.open(QIODevice::ReadOnly))
264 *type = fileTypeDenied;
265 return audioFile;
268 if (checkFile_CDDA(readTest))
270 *type = fileTypeCDDA;
271 return audioFile;
274 readTest.close();
275 return analyzeMediaFile(filePath, audioFile);
278 const AudioFileModel& AnalyzeTask::analyzeMediaFile(const QString &filePath, AudioFileModel &audioFile)
280 //bool skipNext = false;
281 QPair<quint32, quint32> id_val(UINT_MAX, UINT_MAX);
282 quint32 coverType = UINT_MAX;
283 QByteArray coverData;
285 QStringList params;
286 params << QString("--Language=raw");
287 params << QString("-f");
288 params << QString("--Output=XML");
289 params << QDir::toNativeSeparators(filePath);
291 QProcess process;
292 MUtils::init_process(process, QFileInfo(m_mediaInfoBin).absolutePath());
293 process.start(m_mediaInfoBin, params);
295 QByteArray data;
296 data.reserve(16384);
298 if(!process.waitForStarted())
300 qWarning("MediaInfo process failed to create!");
301 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
302 process.kill();
303 process.waitForFinished(-1);
304 return audioFile;
307 while(process.state() != QProcess::NotRunning)
309 if(MUTILS_BOOLIFY(m_abortFlag))
311 process.kill();
312 qWarning("Process was aborted on user request!");
313 break;
316 if(!process.waitForReadyRead())
318 if(process.state() == QProcess::Running)
320 qWarning("MediaInfo time out. Killing the process now!");
321 process.kill();
322 process.waitForFinished(-1);
323 break;
327 forever
329 const QByteArray dataNext = process.readAll();
330 if (dataNext.isEmpty()) {
331 break; /*no more input data*/
333 data += dataNext;
337 process.waitForFinished();
338 if (process.state() != QProcess::NotRunning)
340 process.kill();
341 process.waitForFinished(-1);
344 while (!process.atEnd())
346 const QByteArray dataNext = process.readAll();
347 if (dataNext.isEmpty()) {
348 break; /*no more input data*/
350 data += dataNext;
353 #if MUTILS_DEBUG
354 qDebug("!!!--MEDIA_INFO-->>>\n%s\n<<<--MEDIA_INFO--!!!", data.constData());
355 #endif //MUTILS_DEBUG
357 return parseMediaInfo(data, audioFile);
360 const AudioFileModel& AnalyzeTask::parseMediaInfo(const QByteArray &data, AudioFileModel &audioFile)
362 QXmlStreamReader xmlStream(data);
363 bool firstMediaFile = true;
365 if (findNextElement(QLatin1String("MediaInfo"), xmlStream))
367 const QString versionXml = findAttribute(QLatin1String("Version"), xmlStream.attributes());
368 if (versionXml.isEmpty() || (!checkVersionStr(versionXml, 2U, 0U)))
370 qWarning("Invalid file format version property: \"%s\"", MUTILS_UTF8(versionXml));
371 return audioFile;
373 if (findNextElement(QLatin1String("CreatingLibrary"), xmlStream))
375 const QString versionLib = findAttribute(QLatin1String("Version"), xmlStream.attributes());
376 const QString identifier = xmlStream.readElementText(QXmlStreamReader::SkipChildElements).simplified();
377 if (!STRICMP(identifier, QLatin1String("MediaInfoLib")))
379 qWarning("Invalid library identiofier property: \"%s\"", MUTILS_UTF8(identifier));
380 return audioFile;
382 const quint32 mediaInfoVer = (m_mediaInfoVer > 9999U) ? m_mediaInfoVer / 10U : m_mediaInfoVer;
383 if (versionLib.isEmpty() || (!checkVersionStr(versionLib, mediaInfoVer / 100U, mediaInfoVer % 100U)))
385 qWarning("Invalid library version property: \"%s\"", MUTILS_UTF8(versionLib));
386 return audioFile;
388 while (findNextElement(QLatin1String("Media"), xmlStream))
390 if (firstMediaFile || audioFile.techInfo().containerType().isEmpty() || audioFile.techInfo().audioType().isEmpty())
392 firstMediaFile = false;
393 parseFileInfo(xmlStream, audioFile);
395 else
397 qWarning("Skipping non-primary file!");
398 xmlStream.skipCurrentElement();
404 if (!(audioFile.techInfo().containerType().isEmpty() || audioFile.techInfo().audioType().isEmpty()))
406 if (audioFile.metaInfo().title().isEmpty())
408 QString baseName = QFileInfo(audioFile.filePath()).fileName();
409 int index;
410 if ((index = baseName.lastIndexOf(".")) >= 0)
412 baseName = baseName.left(index);
414 baseName = baseName.replace("_", " ").simplified();
415 if ((index = baseName.lastIndexOf(" - ")) >= 0)
417 baseName = baseName.mid(index + 3).trimmed();
419 audioFile.metaInfo().setTitle(baseName);
421 if ((audioFile.techInfo().audioType().compare("PCM", Qt::CaseInsensitive) == 0) && (audioFile.techInfo().audioProfile().compare("Float", Qt::CaseInsensitive) == 0))
423 if (audioFile.techInfo().audioBitdepth() == 32) audioFile.techInfo().setAudioBitdepth(AudioFileModel::BITDEPTH_IEEE_FLOAT32);
426 else
428 qWarning("Audio file format could *not* be recognized!");
431 return audioFile;
434 void AnalyzeTask::parseFileInfo(QXmlStreamReader &xmlStream, AudioFileModel &audioFile)
436 QSet<MI_trackType_t> tracksProcessed;
437 MI_trackType_t trackType;
438 while (findNextElement(QLatin1String("Track"), xmlStream))
440 const QString typeString = findAttribute(QLatin1String("Type"), xmlStream.attributes());
441 if ((trackType = m_trackTypes.value(typeString.toLower(), MI_trackType_t(-1))) != MI_trackType_t(-1))
443 if (!tracksProcessed.contains(trackType))
445 tracksProcessed << trackType;
446 parseTrackInfo(xmlStream, trackType, audioFile);
448 else
450 qWarning("Skipping non-primary '%s' track!", MUTILS_UTF8(typeString));
451 xmlStream.skipCurrentElement();
454 else
456 qWarning("Skipping unsupported '%s' track!", MUTILS_UTF8(typeString));
457 xmlStream.skipCurrentElement();
462 void AnalyzeTask::parseTrackInfo(QXmlStreamReader &xmlStream, const MI_trackType_t trackType, AudioFileModel &audioFile)
464 QString coverMimeType;
465 while (xmlStream.readNextStartElement())
467 const MI_propertyId_t idx = m_mediaInfoIdx.value(qMakePair(trackType, xmlStream.name().toString().simplified().toLower()), MI_propertyId_t(-1));
468 if (idx != MI_propertyId_t(-1))
470 const QString encoding = findAttribute(QLatin1String("dt"), xmlStream.attributes());
471 const QString value = xmlStream.readElementText(QXmlStreamReader::SkipChildElements).simplified();
472 if (!value.isEmpty())
474 parseProperty(encoding.isEmpty() ? value : decodeStr(value, encoding), idx, audioFile, coverMimeType);
477 else
479 xmlStream.skipCurrentElement();
484 void AnalyzeTask::parseProperty(const QString &value, const MI_propertyId_t propertyIdx, AudioFileModel &audioFile, QString &coverMimeType)
486 #if MUTILS_DEBUG
487 qDebug("Property #%d = \"%s\"", propertyIdx, MUTILS_UTF8(value.left(24)));
488 #endif
489 switch (propertyIdx)
491 case propertyId_container: audioFile.techInfo().setContainerType(value); return;
492 case propertyId_container_profile: audioFile.techInfo().setContainerProfile(value); return;
493 case propertyId_duration: SET_OPTIONAL(double, parseFloat(value, _tmp), audioFile.techInfo().setDuration(qRound(_tmp))); return;
494 case propertyId_title: audioFile.metaInfo().setTitle(value); return;
495 case propertyId_artist: audioFile.metaInfo().setArtist(value); return;
496 case propertyId_album: audioFile.metaInfo().setAlbum(value); return;
497 case propertyId_genre: audioFile.metaInfo().setGenre(value); return;
498 case propertyId_released_date: SET_OPTIONAL(quint32, parseYear(value, _tmp), audioFile.metaInfo().setYear(_tmp)); return;
499 case propertyId_track_position: SET_OPTIONAL(quint32, parseUnsigned(value, _tmp), audioFile.metaInfo().setPosition(_tmp)); return;
500 case propertyId_comment: audioFile.metaInfo().setComment(value); return;
501 case propertyId_format: audioFile.techInfo().setAudioType(value); return;
502 case propertyId_format_version: audioFile.techInfo().setAudioVersion(value); return;
503 case propertyId_format_profile: audioFile.techInfo().setAudioProfile(value); return;
504 case propertyId_channel_s_: SET_OPTIONAL(quint32, parseUnsigned(value, _tmp), audioFile.techInfo().setAudioChannels(_tmp)); return;
505 case propertyId_samplingrate: SET_OPTIONAL(quint32, parseUnsigned(value, _tmp), audioFile.techInfo().setAudioSamplerate(_tmp)); return;
506 case propertyId_bitdepth: SET_OPTIONAL(quint32, parseUnsigned(value, _tmp), audioFile.techInfo().setAudioBitdepth(_tmp)); return;
507 case propertyId_bitrate: SET_OPTIONAL(quint32, parseUnsigned(value, _tmp), audioFile.techInfo().setAudioBitrate(DIV_RND(_tmp, 1000U))); return;
508 case propertyId_bitrate_mode: SET_OPTIONAL(quint32, parseRCMode(value, _tmp), audioFile.techInfo().setAudioBitrateMode(_tmp)); return;
509 case propertyId_encoded_library: audioFile.techInfo().setAudioEncodeLib(cleanAsciiStr(value)); return;
510 case propertyId_cover_mime: coverMimeType = value; return;
511 case propertyId_cover_data: retrieveCover(audioFile, coverMimeType, value); return;
512 default: MUTILS_THROW_FMT("Invalid property ID: %d", propertyIdx);
516 bool AnalyzeTask::checkFile_CDDA(QFile &file)
518 file.reset();
519 QByteArray data = file.read(128);
521 int i = data.indexOf("RIFF");
522 int j = data.indexOf("CDDA");
523 int k = data.indexOf("fmt ");
525 return ((i >= 0) && (j >= 0) && (k >= 0) && (k > j) && (j > i));
528 void AnalyzeTask::retrieveCover(AudioFileModel &audioFile, const QString &coverType, const QString &coverData)
530 const QByteArray content = QByteArray::fromBase64(coverData.toLatin1());
531 const QString type = m_mimeTypes.value(coverType.toLower());
532 qDebug("Retrieving cover! (mime=\"%s\", type=\"%s\", len=%d)", MUTILS_L1STR(coverType), MUTILS_L1STR(type), content.size());
533 if(!QImage::fromData(content, type.isEmpty() ? NULL : MUTILS_L1STR(type.toUpper())).isNull())
535 QFile coverFile(QString("%1/%2.%3").arg(MUtils::temp_folder(), MUtils::next_rand_str(), type.isEmpty() ? QLatin1String("jpg") : type));
536 if(coverFile.open(QIODevice::WriteOnly))
538 coverFile.write(content);
539 coverFile.close();
540 audioFile.metaInfo().setCover(coverFile.fileName(), true);
543 else
545 qWarning("Image data seems to be invalid! [Header:%s]", content.left(32).toHex().constData());
550 bool AnalyzeTask::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
552 QProcess process;
553 MUtils::init_process(process, QFileInfo(m_avs2wavBin).absolutePath());
555 process.start(m_avs2wavBin, QStringList() << QDir::toNativeSeparators(filePath) << "?");
557 if(!process.waitForStarted())
559 qWarning("AVS2WAV process failed to create!");
560 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
561 process.kill();
562 process.waitForFinished(-1);
563 return false;
566 bool bInfoHeaderFound = false;
568 while(process.state() != QProcess::NotRunning)
570 if(MUTILS_BOOLIFY(m_abortFlag))
572 process.kill();
573 qWarning("Process was aborted on user request!");
574 break;
577 if(!process.waitForReadyRead())
579 if(process.state() == QProcess::Running)
581 qWarning("AVS2WAV time out. Killing process and skipping file!");
582 process.kill();
583 process.waitForFinished(-1);
584 return false;
588 while(process.canReadLine())
590 const QString line = QString::fromUtf8(process.readLine().constData()).simplified();
591 if(!line.isEmpty())
593 if(bInfoHeaderFound)
595 const qint32 index = line.indexOf(':');
596 if (index > 0)
598 const QString key = line.left(index).trimmed();
599 const QString val = line.mid(index + 1).trimmed();
600 if (!(key.isEmpty() || val.isEmpty()))
602 switch (m_avisynthIdx.value(key.toLower(), MI_propertyId_t(-1)))
604 case propertyId_duration: SET_OPTIONAL(quint32, parseUnsigned(val, _tmp), info.techInfo().setDuration(_tmp)); break;
605 case propertyId_samplingrate: SET_OPTIONAL(quint32, parseUnsigned(val, _tmp), info.techInfo().setAudioSamplerate(_tmp)); break;
606 case propertyId_channel_s_: SET_OPTIONAL(quint32, parseUnsigned(val, _tmp), info.techInfo().setAudioChannels(_tmp)); break;
607 case propertyId_bitdepth: SET_OPTIONAL(quint32, parseUnsigned(val, _tmp), info.techInfo().setAudioBitdepth(_tmp)); break;
612 else
614 if(line.contains("[Audio Info]", Qt::CaseInsensitive))
616 info.techInfo().setAudioType("Avisynth");
617 info.techInfo().setContainerType("Avisynth");
618 bInfoHeaderFound = true;
625 process.waitForFinished();
626 if(process.state() != QProcess::NotRunning)
628 process.kill();
629 process.waitForFinished(-1);
632 //Check exit code
633 switch(process.exitCode())
635 case 0:
636 qDebug("Avisynth script was analyzed successfully.");
637 return true;
638 break;
639 case -5:
640 qWarning("It appears that Avisynth is not installed on the system!");
641 return false;
642 break;
643 default:
644 qWarning("Failed to open the Avisynth script, bad AVS file?");
645 return false;
646 break;
650 // ---------------------------------------------------------
651 // Utility Functions
652 // ---------------------------------------------------------
654 QString AnalyzeTask::decodeStr(const QString &str, const QString &encoding)
656 if (STRICMP(encoding, QLatin1String("binary.base64")))
658 const QString decoded = QString::fromUtf8(QByteArray::fromBase64(str.toLatin1()));
659 return decoded;
661 return QString();
664 bool AnalyzeTask::parseUnsigned(const QString &str, quint32 &value)
666 bool okay = false;
667 value = str.toUInt(&okay);
668 return okay;
670 bool AnalyzeTask::parseFloat(const QString &str, double &value)
672 bool okay = false;
673 value = QLocale::c().toDouble(str, &okay);
674 return okay;
677 bool AnalyzeTask::parseYear(const QString &str, quint32 &value)
679 if (str.startsWith(QLatin1String("UTC"), Qt::CaseInsensitive))
681 const QDate date = QDate::fromString(str.mid(3).trimmed().left(10), QLatin1String("yyyy-MM-dd"));
682 if (date.isValid())
684 value = date.year();
685 return true;
687 return false;
689 else
691 return parseUnsigned(str, value);
695 bool AnalyzeTask::parseRCMode(const QString &str, quint32 &value)
697 if (STRICMP(str, QLatin1String("CBR")))
699 value = AudioFileModel::BitrateModeConstant;
700 return true;
702 if (STRICMP(str, QLatin1String("VBR")))
704 value = AudioFileModel::BitrateModeVariable;
705 return true;
707 return false;
710 QString AnalyzeTask::cleanAsciiStr(const QString &str)
712 QByteArray ascii = str.toLatin1();
713 for (QByteArray::Iterator iter = ascii.begin(); iter != ascii.end(); ++iter)
715 if ((*iter < 0x20) || (*iter >= 0x7F)) *iter = 0x3F;
717 return QString::fromLatin1(ascii).remove(QLatin1Char('?')).simplified();
720 bool AnalyzeTask::findNextElement(const QString &name, QXmlStreamReader &xmlStream)
722 while (xmlStream.readNextStartElement())
724 if (STRICMP(xmlStream.name(), name))
726 return true;
728 xmlStream.skipCurrentElement();
730 return false;
733 QString AnalyzeTask::findAttribute(const QString &name, const QXmlStreamAttributes &xmlAttributes)
735 for (QXmlStreamAttributes::ConstIterator iter = xmlAttributes.constBegin(); iter != xmlAttributes.constEnd(); ++iter)
737 if (STRICMP(iter->name(), name))
739 const QString value = iter->value().toString().simplified();
740 if (!value.isEmpty())
742 return value; /*found*/
746 return QString();
749 bool AnalyzeTask::checkVersionStr(const QString &str, const quint32 expectedMajor, const quint32 expectedMinor)
751 QRegExp version("^(\\d+)\\.(\\d+)($|\\.)");
752 if (version.indexIn(str) >= 0)
754 quint32 actual[2];
755 if (MUtils::regexp_parse_uint32(version, actual, 2))
757 if ((actual[0] == expectedMajor) && (actual[1] >= expectedMinor))
759 return true;
763 return false;
766 ////////////////////////////////////////////////////////////
767 // Public Functions
768 ////////////////////////////////////////////////////////////
770 /*NONE*/
772 ////////////////////////////////////////////////////////////
773 // EVENTS
774 ////////////////////////////////////////////////////////////
776 /*NONE*/