void qtDLGAssembler::InsertNewInstructions()
{
	if(lineEdit->text().length() <= 0)
	{
		close();
		return;
	}

	QMap<quint64,DisAsDataRow>::const_iterator i = m_pCurrentDisassembler->SectionDisAs.constFind(m_instructionOffset);
	if(i == m_pCurrentDisassembler->SectionDisAs.constEnd()) 
	{
		close();
		return;
	}

	QString oldOpcodes = i.value().OpCodes;
	DWORD oldOpcodeLen = oldOpcodes.replace(" ", "").length() / 2,
		newOpcodeLen = NULL;
		
	QFile tempOutput("nanomite.asm");
	tempOutput.open(QIODevice::WriteOnly | QIODevice::Text);
	QTextStream out(&tempOutput);

	if(m_is64Bit)
		out << "BITS 64\n";
	else
		out << "BITS 32\n";

	out << "org 0x" << hex << i.value().Offset << "\r\n";
	out << lineEdit->text();
	tempOutput.close();

	QProcess nasm;
	nasm.setReadChannel(QProcess::StandardOutput);
    nasm.setProcessChannelMode(QProcess::MergedChannels);
    nasm.start("nasm.exe -o nanomite.bin nanomite.asm");
    if (!nasm.waitForStarted())
	{
		QMessageBox::critical(this, "Nanomite", "Unable to launch assembler!", QMessageBox::Ok, QMessageBox::Ok);
		close();
		return;
	}

	while(nasm.state() != QProcess::NotRunning)
	{
        nasm.waitForReadyRead();
		QString errorMessage = nasm.readAll();

		if(errorMessage.contains("nanomite.asm:3:"))
		{
			errorMessage.replace("nanomite.asm:3:","");
			QMessageBox::critical(this, "Nanomite", errorMessage, QMessageBox::Ok, QMessageBox::Ok);
			lineEdit->clear();
			return;
		}
    }
	DeleteFile(L"nanomite.asm");

	HANDLE hFile = CreateFileW(L"nanomite.bin",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL);
	if(hFile == INVALID_HANDLE_VALUE)
	{
		lineEdit->clear();
		return;
	}

	int iLen = GetFileSize(hFile,NULL);
	LPVOID pFileBuffer = clsMemManager::CAlloc(iLen);
	DWORD BytesRead = NULL;	
	if(!ReadFile(hFile,pFileBuffer,iLen,&BytesRead,NULL))
	{
		CloseHandle(hFile);
		DeleteFile(L"nanomite.bin");
		clsMemManager::CFree(pFileBuffer);
		QMessageBox::critical(this,"Nanomite","no valid opcodes found!",QMessageBox::Ok,QMessageBox::Ok);
		lineEdit->clear();
		return;
	}
	CloseHandle(hFile);
	DeleteFile(L"nanomite.bin");


	if(BytesRead <= 0)
	{
		clsMemManager::CFree(pFileBuffer);
		QMessageBox::critical(this,"Nanomite","no valid opcodes found!",QMessageBox::Ok,QMessageBox::Ok);
		lineEdit->clear();
		return;
	}

	if(oldOpcodeLen >= BytesRead)
		newOpcodeLen = oldOpcodeLen;
	else if(oldOpcodeLen < BytesRead)
	{
		newOpcodeLen = oldOpcodeLen;
		while(newOpcodeLen < BytesRead)
		{
			++i;
			if(i == m_pCurrentDisassembler->SectionDisAs.constEnd()) return;
			oldOpcodes = i.value().OpCodes;
			newOpcodeLen += oldOpcodes.replace(" ", "").length() / 2;
		}
	}

	LPVOID pBuffer = clsMemManager::CAlloc(newOpcodeLen);
	memset(pBuffer,0x90,newOpcodeLen);
	memcpy(pBuffer,pFileBuffer,BytesRead);

	qtDLGPatchManager::AddNewPatch(GetProcessId(m_processHandle), m_processHandle, m_instructionOffset, newOpcodeLen, pBuffer);

	clsMemManager::CFree(pBuffer);
	clsMemManager::CFree(pFileBuffer);

	lineEdit->clear();
	close();
}
DiagnosticsDialog::DiagnosticsDialog( QWidget *parent )
:	QDialog( parent )
{
	setupUi( this );
	setAttribute( Qt::WA_DeleteOnClose, true );

	QString info;
	QTextStream s( &info );

	s << "<b>" << tr("Locale:") << "</b> ";
	QString locale = QLocale::c().name();
	s << (locale == "C" ? "en_us" : locale) << "<br /><br />";

#if defined(Q_OS_LINUX)
	QString package = getPackageVersion( QStringList() << "estonianidcard", false );
	QString utility = getPackageVersion( QStringList() << "qesteidutil", false );
	if ( !package.isEmpty() )
		s << "<b>" << tr("ID-card package version:") << "</b> " << package << "<br />";
	if ( !utility.isEmpty() )
		s << "<b>" << tr("ID-card utility version:") << "</b> " << utility << "<br />";
#else
	s << "<b>" << tr("ID-card utility version:") << "</b> " << QCoreApplication::applicationVersion() << "<br />";
#endif

	s << "<b>" << tr("OS:") << "</b> ";
#if defined(Q_OS_LINUX)
	QProcess p;
	p.start( "lsb_release", QStringList() << "-s" << "-d" );
	p.waitForReadyRead();
	s << p.readAll();
#elif defined(Q_OS_MAC)
	SInt32 major, minor, bugfix;
	
	if( Gestalt(gestaltSystemVersionMajor, &major) == noErr &&
			Gestalt(gestaltSystemVersionMinor, &minor) == noErr &&
			Gestalt(gestaltSystemVersionBugFix, &bugfix) == noErr )
		s << "Mac OS " << major << "." << minor << "." << bugfix;
	else
		s << "Mac OS 10.3";
#endif

	s << " (" << QSysInfo::WordSize << ")<br />";
#if defined(Q_OS_LINUX)
	s << "<b>" << tr("CPU:") << "</b> " << getProcessor() << "<br /><br />";
#endif

	s << "<b>" << tr("Library paths:") << "</b> " << QCoreApplication::libraryPaths().join( ";" ) << "<br />";

	s << "<b>" << tr("Libraries") << ":</b><br />";
#if defined(Q_OS_MAC)
	QProcess p;
	p.start( "/Library/OpenSC/bin/opensc-tool", QStringList() << "-i" );
	p.waitForReadyRead();
	s << p.readAll() << "<br />";
#elif defined(Q_OS_LINUX)
	s << getPackageVersion( QStringList() << "openssl" << "libpcsclite1" << "opensc" );
#endif
	s << "QT (" << qVersion() << ")<br />" << "<br />";

	s << "<b>" << tr("PCSC service status: ") << "</b>" << " " << (isPCSCRunning() ? tr("Running") : tr("Not running")) << "<br /><br />";

	s << "<b>" << tr("Card readers") << ":</b><br />" << getReaderInfo() << "<br />";

	QString browsers = getBrowsers();
	if ( !browsers.isEmpty() )
		s << "<b>" << tr("Browsers:") << "</b><br />" << browsers << "<br /><br />";

	diagnosticsText->setHtml( info );
}
unsigned int AbstractTool::checkVersion(bool &modified)
{
	if(m_preferences->getSkipVersionTest())
	{
		log("Warning: Skipping the version check this time!");
		return makeRevision(0xFFF0, 0xFFF0);
	}

	QProcess process;
	QList<QRegExp*> patterns;
	QStringList cmdLine;

	//Init encoder-specific values
	checkVersion_init(patterns, cmdLine);

	log("Creating process:");
	if(!startProcess(process, getBinaryPath(), cmdLine))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;

	unsigned int revision = UINT_MAX;
	unsigned int coreVers = UINT_MAX;
	modified = false;

	while(process.state() != QProcess::NotRunning)
	{
		if(*m_abort)
		{
			process.kill();
			bAborted = true;
			break;
		}
		if(!process.waitForReadyRead())
		{
			if(process.state() == QProcess::Running)
			{
				process.kill();
				qWarning("process timed out <-- killing!");
				log("\nPROCESS TIMEOUT !!!");
				bTimeout = true;
				break;
			}
		}
		PROCESS_PENDING_LINES(process, checkVersion_parseLine, patterns, coreVers, revision, modified);
	}

	if(!(bTimeout || bAborted))
	{
		PROCESS_PENDING_LINES(process, checkVersion_parseLine, patterns, coreVers, revision, modified);
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}

	while(!patterns.isEmpty())
	{
		QRegExp *pattern = patterns.takeFirst();
		MUTILS_DELETE(pattern);
	}

	if(bTimeout || bAborted || (!checkVersion_succeeded(process.exitCode())))
	{
		if(!(bTimeout || bAborted))
		{
			log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
		}
		return UINT_MAX;
	}

	if((revision == UINT_MAX) || (coreVers == UINT_MAX))
	{
		log(tr("\nFAILED TO DETERMINE VERSION INFO !!!"));
		return UINT_MAX;
	}
	
	return makeRevision(coreVers, revision);
}
Device::Device()
{
#ifdef i386
    m_model = EMULATOR;
    return;
#endif
    QStringList list;
    QProcess *myProcess = new QProcess();

    list << "-c" << "grep erial /proc/cpuinfo|cut -c12-15";
    myProcess->start("/bin/sh", list);
    if (myProcess->waitForReadyRead(10000)) {
        QByteArray array = myProcess->readAll();
        array.truncate(array.indexOf("\n"));

        bool ok;
        int sn = QString(array).toInt(&ok, 16);

        if (ok) {
            qDebug("serial: %X", sn);
        } else {
            qDebug("unexpected output");
            return;
        }

        switch(sn) {
        case 0xB002:
        case 0xB003:
            m_model = K2; // may not work as K2 doesn't print SN in cpuinfo
            break;
        case 0xB004:
        case 0xB005:
        case 0xB009:
            m_model = KDX;
            break;
        case 0xB006:
        case 0xB008:
        case 0xB00A:
            m_model = K3;
            break;
        case 0xB00E:
            m_model = K4NT;
            break;
        case 0xB00F:
        case 0xB010:
        case 0xB011:
        case 0xB012: // ???
            m_model = KT;
            break;
        case 0x9023:
        case 0xB023:
            m_model = K4NTB;
            break;
        case 0xB01B:
        case 0xB01C:
        case 0xB01D:
        case 0xB01F:
        case 0xB024:
            m_model = KPW;
            break;
        default:
            qDebug("Unknown model: %X", sn);
        }
    }
    myProcess->close();
}
Example #5
0
bool MP3Decoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	args << "-v" << "--utf8" << "-w" << QDir::toNativeSeparators(outputFile);
	args << QDir::toNativeSeparators(sourceFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;

	QRegExp regExp("\\s+Time:\\s+(\\d+):(\\d+)\\.(\\d+)\\s+\\[(\\d+):(\\d+)\\.(\\d+)\\],");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("mpg123 process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				int values[6];
				for(int i = 0; i < 6; i++)
				{
					bool ok = false;
					int temp = regExp.cap(i+1).toInt(&ok);
					values[i] = (ok ? temp : 0);
				}
				int timeDone = (60 * values[0]) + values[1];
				int timeLeft = (60 * values[3]) + values[4];
				if(timeDone > 0 || timeLeft > 0)
				{
					int newProgress = qRound((static_cast<double>(timeDone) / static_cast<double>(timeDone + timeLeft)) * 100.0);
					if(newProgress > prevProgress)
					{
						emit statusUpdated(newProgress);
						prevProgress = qMin(newProgress + 2, 99);
					}
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}
	
	return true;
}
Example #6
0
bool OpusDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	if(m_disableResampling)
	{
		args << "--no-resample";
	}

	args << QDir::toNativeSeparators(sourceFile);
	args << QDir::toNativeSeparators(outputFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;

	QRegExp regExp("\\((\\d+)%\\)");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("opusdec process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok && (progress > prevProgress))
				{
					emit statusUpdated(progress);
					prevProgress = qMin(progress + 2, 99);
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}
	
	return true;
}
Example #7
0
bool ALACDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	args << "--decode";
	args << "-o" << QDir::toNativeSeparators(outputFile);
	args << QDir::toNativeSeparators(sourceFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;

	//The ALAC Decoder doesn't actually send any status updates :-[
	//emit statusUpdated(20 + (QUuid::createUuid().data1 % 60));
	QRegExp regExp("\\[(\\d+)\\.(\\d)%\\]");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("ALAC process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok[2] = {false, false};
				int intVal[2] = {0, 0};
				intVal[0] = regExp.cap(1).toInt(&ok[0]);
				intVal[1] = regExp.cap(2).toInt(&ok[1]);
				if(ok[0] && ok[1])
				{
					int progress = qRound(static_cast<double>(intVal[0]) + (static_cast<double>(intVal[1]) / 10.0));
					if(progress > prevProgress)
					{
						emit statusUpdated(progress);
						prevProgress = qMin(progress + 2, 99);
					}
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS || QFileInfo(outputFile).size() == 0)
	{
		return false;
	}
	
	return true;
}
Example #8
0
bool QAACEncoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const QString &outputFile, volatile bool *abortFlag)
{
	const QString qaac_bin = m_binary_qaac64.isEmpty() ? m_binary_qaac32 : m_binary_qaac64;

	QProcess process;
	QStringList args;

	process.setWorkingDirectory(QFileInfo(outputFile).canonicalPath());

	QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
	env.insert("PATH", QDir::toNativeSeparators(QString("%1;%1/QTfiles;%2").arg(QDir(QCoreApplication::applicationDirPath()).canonicalPath(), MUtils::temp_folder())));
	process.setProcessEnvironment(env);

	if(m_configRCMode != SettingsModel::VBRMode)
	{
		switch(m_configProfile)
		{
		case 2:
		case 3:
			args << "--he"; //Forces use of HE AAC profile (there is no explicit HEv2 switch for QAAC)
			break;
		}
	}

	switch(m_configRCMode)
	{
	case SettingsModel::CBRMode:
		args << "--cbr" << QString::number(qBound(8, index2bitrate(m_configBitrate), 576));
		break;
	case SettingsModel::ABRMode:
		args << "--abr" << QString::number(qBound(8, index2bitrate(m_configBitrate), 576));
		break;
	case SettingsModel::VBRMode:
		args << "--tvbr" << QString::number(g_qaacVBRQualityLUT[qBound(0, m_configBitrate , 14)]);
		break;
	default:
		MUTILS_THROW("Bad rate-control mode!");
		break;
	}

	if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);

	if(!metaInfo.title().isEmpty())   args << "--title"   << cleanTag(metaInfo.title());
	if(!metaInfo.artist().isEmpty())  args << "--artist"  << cleanTag(metaInfo.artist());
	if(!metaInfo.album().isEmpty())   args << "--album"   << cleanTag(metaInfo.album());
	if(!metaInfo.genre().isEmpty())   args << "--genre"   << cleanTag(metaInfo.genre());
	if(!metaInfo.comment().isEmpty()) args << "--comment" << cleanTag( metaInfo.comment());
	if(metaInfo.year())               args << "--date"    << QString::number(metaInfo.year());
	if(metaInfo.position())           args << "--track"   << QString::number(metaInfo.position());
	if(!metaInfo.cover().isEmpty())   args << "--artwork" << metaInfo.cover();

	args << "-d" << ".";
	args << "-o" << QDir::toNativeSeparators(outputFile);
	args << QDir::toNativeSeparators(sourceFile);

	if(!startProcess(process, qaac_bin, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;

	QRegExp regExp("\\[(\\d+)\\.(\\d)%\\]");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("QAAC process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok && (progress > prevProgress))
				{
					emit statusUpdated(progress);
					prevProgress = qMin(progress + 2, 99);
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}

	return true;
}
Example #9
0
/**
 * Starting point for the retracing thread.
 *
 * Overrides QThread::run().
 */
void Retracer::run()
{
    QString msg = QLatin1String("Replay finished!");

    /*
     * Construct command line
     */

    QString prog;
    QStringList arguments;

    switch (m_api) {
    case trace::API_GL:
        prog = QLatin1String("glretrace");
        break;
    case trace::API_EGL:
        prog = QLatin1String("eglretrace");
        break;
    case trace::API_DX:
    case trace::API_D3D7:
    case trace::API_D3D8:
    case trace::API_D3D9:
    case trace::API_DXGI:
#ifdef Q_OS_WIN
        prog = QLatin1String("d3dretrace");
#else
        prog = QLatin1String("wine");
        arguments << QLatin1String("d3dretrace.exe");
#endif
        break;
    default:
        emit finished(QLatin1String("Unsupported API"));
        return;
    }

    if (m_singlethread) {
        arguments << QLatin1String("--singlethread");
    }

    if (m_useCoreProfile) {
        arguments << QLatin1String("--core");
    }

    if (m_captureState) {
        arguments << QLatin1String("-D");
        arguments << QString::number(m_captureCall);
    } else if (m_captureThumbnails) {
        if (!m_thumbnailsToCapture.isEmpty()) {
            arguments << QLatin1String("-S");
            arguments << thumbnailCallSet();
        }
        arguments << QLatin1String("-s"); // emit snapshots
        arguments << QLatin1String("-"); // emit to stdout
    } else if (isProfiling()) {
        if (m_profileGpu) {
            arguments << QLatin1String("--pgpu");
        }

        if (m_profileCpu) {
            arguments << QLatin1String("--pcpu");
        }

        if (m_profilePixels) {
            arguments << QLatin1String("--ppd");
        }
    } else {
        if (!m_doubleBuffered) {
            arguments << QLatin1String("--sb");
        }

        if (m_benchmarking) {
            arguments << QLatin1String("-b");
        }
    }

    arguments << m_fileName;

    /*
     * Support remote execution on a separate target.
     */

    if (m_remoteTarget.length() != 0) {
        arguments.prepend(prog);
        arguments.prepend(m_remoteTarget);
        prog = QLatin1String("ssh");
    }

    /*
     * Start the process.
     */

    {
        QDebug debug(QtDebugMsg);
        debug << "Running:";
        debug << prog;
        foreach (const QString &argument, arguments) {
            debug << argument;
        }
    }

    QProcess process;

    process.start(prog, arguments, QIODevice::ReadOnly);
    if (!process.waitForStarted(-1)) {
        emit finished(QLatin1String("Could not start process"));
        return;
    }

    /*
     * Process standard output
     */

    ImageHash thumbnails;
    QVariantMap parsedJson;
    trace::Profile* profile = NULL;

    process.setReadChannel(QProcess::StandardOutput);
    if (process.waitForReadyRead(-1)) {
        BlockingIODevice io(&process);

        if (m_captureState) {
            process.waitForFinished(-1);
            QByteArray data = process.readAll();
            QJsonParseError error;
            QJsonDocument jsonDoc =
                QJsonDocument::fromJson(data, &error);

            if (error.error != QJsonParseError::NoError) {
                //qDebug()<<"Error is "<<error.errorString();
                msg = error.errorString();
            }
            parsedJson = jsonDoc.toVariant().toMap();
        } else if (m_captureThumbnails) {
            /*
             * Parse concatenated PNM images from output.
             */

            while (!io.atEnd()) {
                image::PNMInfo info;

                char header[512];
                qint64 headerSize = 0;
                int headerLines = 3; // assume no optional comment line

                for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
                    qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize);

                    // if header actually contains optional comment line, ...
                    if (headerLine == 1 && header[headerSize] == '#') {
                        ++headerLines;
                    }

                    headerSize += headerRead;
                }

                const char *headerEnd = image::readPNMHeader(header, headerSize, info);

                // if invalid PNM header was encountered, ...
                if (headerEnd == NULL ||
                    info.channelType != image::TYPE_UNORM8) {
                    qDebug() << "error: invalid snapshot stream encountered";
                    break;
                }

                unsigned channels = info.channels;
                unsigned width = info.width;
                unsigned height = info.height;

                // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";

                QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);

                int rowBytes = channels * width;
                for (int y = 0; y < height; ++y) {
                    unsigned char *scanLine = snapshot.scanLine(y);
                    qint64 readBytes = io.read((char *) scanLine, rowBytes);
                    Q_ASSERT(readBytes == rowBytes);
                    (void)readBytes;
                }

                QImage thumb = thumbnail(snapshot);
                thumbnails.insert(info.commentNumber, thumb);
            }

            Q_ASSERT(process.state() != QProcess::Running);
        } else if (isProfiling()) {
            profile = new trace::Profile();

            while (!io.atEnd()) {
                char line[256];
                qint64 lineLength;

                lineLength = io.readLine(line, 256);

                if (lineLength == -1)
                    break;

                trace::Profiler::parseLine(line, profile);
            }
        } else {
            QByteArray output;
            output = process.readAllStandardOutput();
            if (output.length() < 80) {
                msg = QString::fromUtf8(output);
            }
        }
    }

    /*
     * Wait for process termination
     */

    process.waitForFinished(-1);

    if (process.exitStatus() != QProcess::NormalExit) {
        msg = QLatin1String("Process crashed");
    } else if (process.exitCode() != 0) {
        msg = QLatin1String("Process exited with non zero exit code");
    }

    /*
     * Parse errors.
     */

    QList<ApiTraceError> errors;
    process.setReadChannel(QProcess::StandardError);
    QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
    while (!process.atEnd()) {
        QString line = process.readLine();
        if (regexp.indexIn(line) != -1) {
            ApiTraceError error;
            error.callIndex = regexp.cap(1).toInt();
            error.type = regexp.cap(2);
            error.message = regexp.cap(3);
            errors.append(error);
        } else if (!errors.isEmpty()) {
            // Probably a multiligne message
            ApiTraceError &previous = errors.last();
            if (line.endsWith("\n")) {
                line.chop(1);
            }
            previous.message.append('\n');
            previous.message.append(line);
        }
    }

    /*
     * Emit signals
     */

    if (m_captureState) {
        ApiTraceState *state = new ApiTraceState(parsedJson);
        emit foundState(state);
    }

    if (m_captureThumbnails && !thumbnails.isEmpty()) {
        emit foundThumbnails(thumbnails);
    }

    if (isProfiling() && profile) {
        emit foundProfile(profile);
    }

    if (!errors.isEmpty()) {
        emit retraceErrors(errors);
    }

    emit finished(msg);
}
bool AnalyzeTask::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
{
	QProcess process;
	lamexp_init_process(process, QFileInfo(m_avs2wavBin).absolutePath());

	process.start(m_avs2wavBin, QStringList() << QDir::toNativeSeparators(filePath) << "?");

	if(!process.waitForStarted())
	{
		qWarning("AVS2WAV process failed to create!");
		qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
		process.kill();
		process.waitForFinished(-1);
		return false;
	}

	bool bInfoHeaderFound = false;

	while(process.state() != QProcess::NotRunning)
	{
		if(*m_abortFlag)
		{
			process.kill();
			qWarning("Process was aborted on user request!");
			break;
		}
		
		if(!process.waitForReadyRead())
		{
			if(process.state() == QProcess::Running)
			{
				qWarning("AVS2WAV time out. Killing process and skipping file!");
				process.kill();
				process.waitForFinished(-1);
				return false;
			}
		}

		QByteArray data;

		while(process.canReadLine())
		{
			QString line = QString::fromUtf8(process.readLine().constData()).simplified();
			if(!line.isEmpty())
			{
				int index = line.indexOf(':');
				if(index > 0)
				{
					QString key = line.left(index).trimmed();
					QString val = line.mid(index+1).trimmed();

					if(bInfoHeaderFound && !key.isEmpty() && !val.isEmpty())
					{
						if(key.compare("TotalSeconds", Qt::CaseInsensitive) == 0)
						{
							bool ok = false;
							unsigned int duration = val.toUInt(&ok);
							if(ok) info.techInfo().setDuration(duration);
						}
						if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0)
						{
							bool ok = false;
							unsigned int samplerate = val.toUInt(&ok);
							if(ok) info.techInfo().setAudioSamplerate (samplerate);
						}
						if(key.compare("Channels", Qt::CaseInsensitive) == 0)
						{
							bool ok = false;
							unsigned int channels = val.toUInt(&ok);
							if(ok) info.techInfo().setAudioChannels(channels);
						}
						if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0)
						{
							bool ok = false;
							unsigned int bitdepth = val.toUInt(&ok);
							if(ok) info.techInfo().setAudioBitdepth(bitdepth);
						}
					}
				}
				else
				{
					if(line.contains("[Audio Info]", Qt::CaseInsensitive))
					{
						info.techInfo().setAudioType("Avisynth");
						info.techInfo().setContainerType("Avisynth");
						bInfoHeaderFound = true;
					}
				}
			}
		}
	}
	
	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}

	//Check exit code
	switch(process.exitCode())
	{
	case 0:
		qDebug("Avisynth script was analyzed successfully.");
		return true;
		break;
	case -5:
		qWarning("It appears that Avisynth is not installed on the system!");
		return false;
		break;
	default:
		qWarning("Failed to open the Avisynth script, bad AVS file?");
		return false;
		break;
	}
}
bool ShortenDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	args << "-x";
	args << QDir::toNativeSeparators(sourceFile);
	args << QDir::toNativeSeparators(outputFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;

	//The Shorten Decoder doesn't actually send any status updates :-[
	emit statusUpdated(20 + (QUuid::createUuid().data1 % 80));

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("Shorten process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS || QFileInfo(outputFile).size() == 0)
	{
		return false;
	}
	
	return true;
}
const AudioFileModel AnalyzeTask::analyzeFile(const QString &filePath, int *type)
{
	*type = fileTypeNormal;
	AudioFileModel audioFile(filePath);

	QFile readTest(filePath);
	if(!readTest.open(QIODevice::ReadOnly))
	{
		*type = fileTypeDenied;
		return audioFile;
	}
	if(checkFile_CDDA(readTest))
	{
		*type = fileTypeCDDA;
		return audioFile;
	}
	readTest.close();

	bool skipNext = false;
	unsigned int id_val[2] = {UINT_MAX, UINT_MAX};
	cover_t coverType = coverNone;
	QByteArray coverData;

	QStringList params;
	params << QString("--Inform=file://%1").arg(QDir::toNativeSeparators(m_templateFile));
	params << QDir::toNativeSeparators(filePath);
	
	QProcess process;
	lamexp_init_process(process, QFileInfo(m_mediaInfoBin).absolutePath());

	process.start(m_mediaInfoBin, params);
		
	if(!process.waitForStarted())
	{
		qWarning("MediaInfo process failed to create!");
		qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
		process.kill();
		process.waitForFinished(-1);
		return audioFile;
	}

	while(process.state() != QProcess::NotRunning)
	{
		if(*m_abortFlag)
		{
			process.kill();
			qWarning("Process was aborted on user request!");
			break;
		}
		
		if(!process.waitForReadyRead())
		{
			if(process.state() == QProcess::Running)
			{
				qWarning("MediaInfo time out. Killing process and skipping file!");
				process.kill();
				process.waitForFinished(-1);
				return audioFile;
			}
		}

		QByteArray data;

		while(process.canReadLine())
		{
			QString line = QString::fromUtf8(process.readLine().constData()).simplified();
			if(!line.isEmpty())
			{
				//qDebug("Line:%s", QUTF8(line));
				
				int index = line.indexOf('=');
				if(index > 0)
				{
					QString key = line.left(index).trimmed();
					QString val = line.mid(index+1).trimmed();
					if(!key.isEmpty())
					{
						updateInfo(audioFile, &skipNext, id_val, &coverType, &coverData, key, val);
					}
				}
			}
		}
	}

	if(audioFile.metaInfo().title().isEmpty())
	{
		QString baseName = QFileInfo(filePath).fileName();
		int index = baseName.lastIndexOf(".");

		if(index >= 0)
		{
			baseName = baseName.left(index);
		}

		baseName = baseName.replace("_", " ").simplified();
		index = baseName.lastIndexOf(" - ");

		if(index >= 0)
		{
			baseName = baseName.mid(index + 3).trimmed();
		}

		audioFile.metaInfo().setTitle(baseName);
	}
	
	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}

	if((coverType != coverNone) && (!coverData.isEmpty()))
	{
		retrieveCover(audioFile, coverType, coverData);
	}

	if((audioFile.techInfo().audioType().compare("PCM", Qt::CaseInsensitive) == 0) && (audioFile.techInfo().audioProfile().compare("Float", Qt::CaseInsensitive) == 0))
	{
		if(audioFile.techInfo().audioBitdepth() == 32) audioFile.techInfo().setAudioBitdepth(AudioFileModel::BITDEPTH_IEEE_FLOAT32);
	}

	return audioFile;
}
Example #13
0
bool AC3Encoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const QString &outputFile, volatile bool *abortFlag)
{
    QProcess process;
    QStringList args;

    switch(m_configRCMode)
    {
    case SettingsModel::VBRMode:
        args << "-q" << QString::number(qBound(0, m_configBitrate * 16, 1023));
        break;
    case SettingsModel::CBRMode:
        args << "-b" << QString::number(g_ac3BitratesLUT[qBound(0, m_configBitrate, 18)]);
        break;
    default:
        THROW("Bad rate-control mode!");
        break;
    }

    if(m_configAudioCodingMode >= 1)
    {
        args << "-acmod" << QString::number(m_configAudioCodingMode - 1);
    }
    if(m_configDynamicRangeCompression != 5)
    {
        args << "-dynrng" << QString::number(m_configDynamicRangeCompression);
    }
    if(m_configExponentSearchSize != 8)
    {
        args << "-exps" << QString::number(m_configExponentSearchSize);
    }
    if(m_configFastBitAllocation)
    {
        args << "-fba" << QString::number(1);
    }

    if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);

    args << QDir::toNativeSeparators(sourceFile);
    args << QDir::toNativeSeparators(outputFile);

    if(!startProcess(process, m_binary, args))
    {
        return false;
    }

    bool bTimeout = false;
    bool bAborted = false;
    int prevProgress = -1;

    QRegExp regExp("progress:(\\s+)(\\d+)%(\\s+)\\|");

    while(process.state() != QProcess::NotRunning)
    {
        if(*abortFlag)
        {
            process.kill();
            bAborted = true;
            emit messageLogged("\nABORTED BY USER !!!");
            break;
        }
        process.waitForReadyRead(m_processTimeoutInterval);
        if(!process.bytesAvailable() && process.state() == QProcess::Running)
        {
            process.kill();
            qWarning("Aften process timed out <-- killing!");
            emit messageLogged("\nPROCESS TIMEOUT !!!");
            bTimeout = true;
            break;
        }
        while(process.bytesAvailable() > 0)
        {
            QByteArray line = process.readLine();
            QString text = QString::fromUtf8(line.constData()).simplified();
            if(regExp.lastIndexIn(text) >= 0)
            {
                bool ok = false;
                int progress = regExp.cap(2).toInt(&ok);
                if(ok && (progress > prevProgress))
                {
                    emit statusUpdated(progress);
                    prevProgress = qMin(progress + 2, 99);
                }
            }
            else if(!text.isEmpty())
            {
                emit messageLogged(text);
            }
        }
    }

    process.waitForFinished();
    if(process.state() != QProcess::NotRunning)
    {
        process.kill();
        process.waitForFinished(-1);
    }

    emit statusUpdated(100);
    emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

    if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
    {
        return false;
    }

    return true;
}
Example #14
0
/** Runs the specified command (should be ffmpeg), and lets
 *  writeFrame pipe data into it 1 frame at a time.
 *
 *  @param[in]  strCmd A string containing the command to execute and
 *              all of its arguments
 *  @param[out] progress A function that takes one float argument
 *              (the percentage of the ffmpeg operation complete) and
 *              may display the output to the user in any way it
 *              sees fit.
 *  @param[in]  writeFrame A function that takes two arguments, a
 *              process (the ffmpeg process) and an integer
 *              (frames processed or -1, see full description).
 *              This function should write a single frame to the
 *              process. The function returns true value if it
 *              actually wrote a frame.
 *
 *  This function operates generally as follows:
 *  1. Spawn process with the command from strCmd
 *  2. Check ffmpeg's output for a progress update.
 *  3. Add frames with writeFrame until it returns false.
 *  4. Repeat from step 2 until all frames have been written.
 *
 *  The idea is that there are two forms of processing occuring
 *  simultaneously, generating frames to send to ffmpeg, and ffmpeg
 *  encoding those frames. Whether these this actually occur
 *  concurrently or one after another appears to depend on the environment.
 *
 *  The writeFrame function deserves a bit of extra details. It does
 *  not only return false when there is an error in generating or
 *  writing a frame, it also does it when it wants to "return control"
 *  to the rest of the executeFFMpegPipe function for the purposes of
 *  reading updates from ffmpeg's output. This should be done every
 *  once in a while if possible, but with some formats (specifically gif),
 *  all frames must be loaded before any processing can continue, so
 *  there is no point returning false for it until all frames have
 *  been written. writeFrame is also responsible for closing the writeChannel
 *  of the process when it has finished writing all frames. This indicates
 *  to executeFFMpegPipe that it no longer needs to call writeFrame.
 *
 *  @return Returns Status::OK if everything went well, and Status::FAIL
 *  and error is detected (usually a non-zero exit code for ffmpeg).
 */
Status MovieExporter::executeFFMpegPipe(QString strCmd, std::function<void(float)> progress, std::function<bool(QProcess&, int)> writeFrame)
{
    qDebug() << strCmd;

    QProcess ffmpeg;
    ffmpeg.setReadChannel(QProcess::StandardOutput);
    // FFmpeg writes to stderr only for some reason, so we just read both channels together
    ffmpeg.setProcessChannelMode(QProcess::MergedChannels);
    ffmpeg.start(strCmd);
    if (ffmpeg.waitForStarted())
    {
        int framesGenerated = 0;
        int lastFrameProcessed = 0;
        const int frameStart = mDesc.startFrame;
        const int frameEnd = mDesc.endFrame;
        while(ffmpeg.state() == QProcess::Running)
        {
            if (mCanceled)
            {
                ffmpeg.terminate();
                return Status::CANCELED;
            }

            // Check FFmpeg progress

            int framesProcessed = -1;
            if(ffmpeg.waitForReadyRead(10))
            {
                QString output(ffmpeg.readAll());
                QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
                for (const QString& s : sList)
                {
                    qDebug() << "[ffmpeg]" << s;
                }
                if(output.startsWith("frame="))
                {
                    lastFrameProcessed = framesProcessed = output.mid(6, output.indexOf(' ')).toInt();
                }
            }

            if(!ffmpeg.isWritable())
            {
                continue;
            }

            while(writeFrame(ffmpeg, framesProcessed))
            {
                framesGenerated++;

                const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart);
                const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart);
                progress((percentGenerated + percentConverted) / 2);
            }
            const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart);
            const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart);
            progress((percentGenerated + percentConverted) / 2);
        }

        QString output(ffmpeg.readAll());
        QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
        for (const QString& s : sList)
        {
            qDebug() << "[ffmpeg]" << s;
        }

        if(ffmpeg.exitStatus() != QProcess::NormalExit)
        {
            qDebug() << "ERROR: FFmpeg crashed";
            return Status::FAIL;
        }
    }
    else
    {
        qDebug() << "ERROR: Could not start FFmpeg.";
        return Status::FAIL;
    }

    return Status::OK;
}
void MarketSrcPackage::process()
{
  if (!m_Initialized)
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                              "package "+m_PackageFilename+" not initialized");

  if (!m_Downloaded)
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                              "package "+m_PackageFilename+" cannot be processed before download");

  if (!m_CMakeProgram.isFound())
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,"CMake command not defined");


  std::string BuildConfigOptions = composeFullBuildOptions(getPackageType(), m_BuildConfigOptions);

  std::string BuildDir = m_TempBuildsDir + "/" + m_ID;
  std::string SrcInstallDir = getInstallPath() + "/" + m_ID;

  // creating installation dir
  if (openfluid::tools::Filesystem::isDirectory(SrcInstallDir))
    openfluid::tools::Filesystem::removeDirectory(SrcInstallDir);

  if (!openfluid::tools::Filesystem::makeDirectory(SrcInstallDir))
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                              "unable to create source directory for "+m_ID+" package");

  // creating build dir
  if (openfluid::tools::Filesystem::isDirectory(BuildDir))
    openfluid::tools::Filesystem::removeDirectory(BuildDir);

  if (!openfluid::tools::Filesystem::makeDirectory(BuildDir))
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                              "unable to create build directory for "+m_ID+" package");


  // == Building commands ==

  QString UntarCommand = QString("\"%1\" -E chdir \"%2\" \"%1\" -E tar xfz \"%3\"")
                                .arg(m_CMakeProgram.getFullProgramPath(),
                                     QString::fromStdString(SrcInstallDir),
                                     QString::fromStdString(m_PackageDest));

  QString BuildConfigCommand = QString("\"%1\" -E chdir \"%2\" \"%1\" \"%3\" %4")
                                      .arg(m_CMakeProgram.getFullProgramPath(),
                                           QString::fromStdString(BuildDir),
                                           QString::fromStdString(SrcInstallDir),
                                           QString::fromStdString(BuildConfigOptions));

  QString BuildCommand = QString("\"%1\" -E chdir \"%2\" \"%1\" --build .")
                                      .arg(m_CMakeProgram.getFullProgramPath(),
                                           QString::fromStdString(BuildDir));

  // uncompressing package
  {
    QProcess Untar;

    Untar.start(UntarCommand);
    Untar.waitForFinished(-1);
    Untar.waitForReadyRead(-1);

    appendToLogFile(QString(Untar.readAllStandardOutput()).toStdString());

    int RetValue = Untar.exitCode();

    if (RetValue != 0)
    {
      appendToLogFile(QString(Untar.readAllStandardError()).toStdString());
      throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                "Error uncompressing sources package using CMake");
    }
  }

  // configuring the build
  {
    QProcess Config;

    Config.start(BuildConfigCommand);
    Config.waitForFinished(-1);
    Config.waitForReadyRead(-1);

    appendToLogFile(QString(Config.readAllStandardOutput()).toStdString());

    int RetValue = Config.exitCode();

    if (RetValue != 0)
    {
      appendToLogFile(QString(Config.readAllStandardError()).toStdString());
      throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                "Error configuring package build using CMake");
    }
  }

  // building
  {
    QProcess Build;

    Build.start(BuildCommand);
    Build.waitForFinished(-1);
    Build.waitForReadyRead(-1);

    appendToLogFile(QString(Build.readAllStandardOutput()).toStdString());

    int RetValue = Build.exitCode();

    if (RetValue != 0)
    {
      appendToLogFile(QString(Build.readAllStandardError()).toStdString());
      throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,"Error building package using CMake");
    }
  }


  // TODO add management of plugins suffixes for builder-extensions
  std::string PackagesPluginsSuffixes= "";
  if (getPackageType() == PackageInfo::SIM)
    PackagesPluginsSuffixes = openfluid::config::SIMULATORS_PLUGINS_SUFFIX;
  else if (getPackageType() == PackageInfo::OBS)
    PackagesPluginsSuffixes = openfluid::config::OBSERVERS_PLUGINS_SUFFIX;


  if (!openfluid::tools::Filesystem::isFile(BuildDir+"/"+m_ID+PackagesPluginsSuffixes+openfluid::config::PLUGINS_EXT))
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,"Error finding built package");

  std::string BinInstallDir = getInstallPath() + "/../" + m_MarketBagBinSubDir;
  if (openfluid::tools::Filesystem::isFile(BinInstallDir+"/"+m_ID+
                                           PackagesPluginsSuffixes +openfluid::config::PLUGINS_EXT))
    openfluid::tools::Filesystem::removeFile(BinInstallDir+"/"+m_ID+
                                             PackagesPluginsSuffixes+openfluid::config::PLUGINS_EXT);

  openfluid::tools::Filesystem::copyFile(BuildDir+"/"+m_ID+PackagesPluginsSuffixes+openfluid::config::PLUGINS_EXT,
                                         BinInstallDir+"/"+m_ID+PackagesPluginsSuffixes+openfluid::config::PLUGINS_EXT);

  if (!m_KeepSources)
    openfluid::tools::Filesystem::removeDirectory(SrcInstallDir);

}
bool AvisynthDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	process.setWorkingDirectory(QFileInfo(outputFile).absolutePath());

	args << QDir::toNativeSeparators(sourceFile);
	args << QDir::toNativeSeparators(outputFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;

	QRegExp regExp("(\\d+)/(\\d+) \\[(\\d+)%\\]");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("AVS2WAV process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(3).toInt(&ok);
				if(ok) emit statusUpdated(progress);
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS || QFileInfo(outputFile).size() == 0)
	{
		return false;
	}
	
	return true;
}
Example #17
0
bool FHGAACEncoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const unsigned int channels, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;
	
	int maxBitrate = 576;

	if(m_configRCMode == SettingsModel::CBRMode)
	{
		switch(m_configProfile)
		{
		case 1:
			args << L1S("--profile") << L1S("lc"); //Forces use of LC AAC profile
			break;
		case 2:
			maxBitrate = 128;
			args << L1S("--profile") << L1S("he"); //Forces use of HE AAC profile
			break;
		case 3:
			maxBitrate = 56;
			args << L1S("--profile") << L1S("hev2"); //Forces use of HEv2 AAC profile
			break;
		}
	}

	switch(m_configRCMode)
	{
	case SettingsModel::CBRMode:
		args << L1S("--cbr") << QString::number(qBound(8, index2bitrate(m_configBitrate), maxBitrate));
		break;
	case SettingsModel::VBRMode:
		args << L1S("--vbr") << QString::number(qBound(1, m_configBitrate + 1, 6));
		break;
	default:
		MUTILS_THROW("Bad rate-control mode!");
		break;
	}

	//args << "--dll" << m_binary_dll;

	if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);

	args << QDir::toNativeSeparators(sourceFile);
	args << QDir::toNativeSeparators(outputFile);

	if(!startProcess(process, m_binary_enc, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;

	QRegExp regExp(L1S("Progress:\\s*(\\d+)%"));

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged(L1S("\nABORTED BY USER !!!"));
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("FhgAacEnc process timed out <-- killing!");
			emit messageLogged(L1S("\nPROCESS TIMEOUT !!!"));
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok && (progress > prevProgress))
				{
					emit statusUpdated(progress);
					prevProgress = qMin(progress + 2, 99);
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}

	return true;
}
Example #18
0
void InitAacEncTask::initAacEncImpl(const char *const toolName, const char *const fileNames[], const quint32 &toolMinVersion, const quint32 &verDigits, const quint32 &verShift, const char *const verStr, QRegExp &regExpVer, QRegExp &regExpSig)
{
	static const size_t MAX_FILES = 8;
	const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
	
	QFileInfoList fileInfo;
	for(size_t i = 0; fileNames[i] && (fileInfo.count() < MAX_FILES); i++)
	{
		fileInfo.append(QFileInfo(QString("%1/%2").arg(appPath, QString::fromLatin1(fileNames[i]))));
	}
	
	for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
	{
		if(!(iter->exists() && iter->isFile()))
		{
			qDebug("%s encoder binaries not found -> Encoding support will be disabled!\n", toolName);
			return;
		}
		if((iter->suffix().compare("exe", Qt::CaseInsensitive) == 0) && (!MUtils::OS::is_executable_file(iter->canonicalFilePath())))
		{
			qDebug("%s executable is invalid -> %s support will be disabled!\n", MUTILS_UTF8(iter->fileName()), toolName);
			return;
		}
	}

	qDebug("Found %s encoder binary:\n%s\n", toolName, MUTILS_UTF8(fileInfo.first().canonicalFilePath()));

	//Lock the encoder binaries
	QScopedPointer<LockedFile> binaries[MAX_FILES];
	try
	{
		size_t index = 0;
		for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
		{
			binaries[index++].reset(new LockedFile(iter->canonicalFilePath()));
		}
	}
	catch(...)
	{
		qWarning("Failed to get excluive lock to encoder binary -> %s support will be disabled!", toolName);
		return;
	}

	QProcess process;
	MUtils::init_process(process, fileInfo.first().absolutePath());

	process.start(fileInfo.first().canonicalFilePath(), QStringList() << "-help");

	if(!process.waitForStarted())
	{
		qWarning("%s process failed to create!", toolName);
		qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
		process.kill();
		process.waitForFinished(-1);
		return;
	}

	quint32 toolVersion = 0;
	bool sigFound = regExpSig.isEmpty() ? true : false;

	while(process.state() != QProcess::NotRunning)
	{
		if(!process.waitForReadyRead())
		{
			if(process.state() == QProcess::Running)
			{
				qWarning("%s process time out -> killing!", toolName);
				process.kill();
				process.waitForFinished(-1);
				return;
			}
		}
		while(process.canReadLine())
		{
			QString line = QString::fromUtf8(process.readLine().constData()).simplified();
			if((!sigFound) && regExpSig.lastIndexIn(line) >= 0)
			{
				sigFound = true;
				continue;
			}
			if(sigFound && (regExpVer.lastIndexIn(line) >= 0))
			{
				quint32 tmp[8];
				if(MUtils::regexp_parse_uint32(regExpVer, tmp, qMin(verDigits, 8U)))
				{
					toolVersion = 0;
					for(quint32 i = 0; i < verDigits; i++)
					{
						toolVersion = (toolVersion * verShift) + qBound(0U, tmp[i], (verShift - 1));
					}
				}
			}
		}
	}

	if(toolVersion <= 0)
	{
		qWarning("%s version could not be determined -> Encoding support will be disabled!", toolName);
		return;
	}
	else if(toolVersion < toolMinVersion)
	{
		qWarning("%s version is too much outdated (%s) -> Encoding support will be disabled!", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion,    "N/A")));
		qWarning("Minimum required %s version currently is: %s\n",                             toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolMinVersion, "N/A")));
		return;
	}

	qDebug("Enabled %s encoder %s.\n", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion, "N/A")));

	size_t index = 0;
	for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
	{
		lamexp_tools_register(iter->fileName(), binaries[index++].take(), toolVersion);
	}
}
Example #19
0
bool cxr()
{
   p = "ps"; QStringList args; args << "-u" << un; QProcess *cxrn = new QProcess(a); cxrn->start(p, args); bool ret = FALSE;
   QString outp; cxrn->waitForReadyRead(3000); outp = cxrn->readAllStandardOutput();
   ret = outp.contains("x11vnc", Qt::CaseInsensitive); return ret;
}
Example #20
0
bool SpeexDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;

	args << "-V";
	args << QDir::toNativeSeparators(sourceFile);
	args << QDir::toNativeSeparators(outputFile);

	if(!startProcess(process, m_binary, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;

	QRegExp regExp("Working\\.\\.\\. (.)");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("SpeexDec process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp.lastIndexIn(text) >= 0)
			{
				/* qDebug("Status: %s", regExp.cap(1).toLatin1().constData()); */
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS || QFileInfo(outputFile).size() == 0)
	{
		return false;
	}
	
	return true;
}
Example #21
0
// actually execute the command here
int AdminThread::executeScript(const QString &command)
{
    // Qt standard stream output
    QTextStream out(stdout);
    //out << tr("Qt signing out from thread!!") << endl;

    int i;
    int &ref = i;
    QString str;
    emit signalOutput(command);
    emit signalOutput("\n");

    // debugging output in threads works
    //qDebug("Hello world from thread!");

    // C++ standard stream output
    //cout << "Goodbye World from thread!!" << endl;
    //str = tr("Goodbye World 2!");
    //cout << str.toStdString() << endl;
    //fflush(stdout);

    out << tr("about to start: %1").arg(command) << endl;

    QProcess process;
    //process.start("/home/oliver/projects/vm/test");
    process.start(command);

    // now read the output line by line
    // and send to calling thread
    //char buf[1024];
    //qint64 lineLength;
    QString stdout;

    if (!process.waitForStarted())
        return false;

    // signal process is now running
    running = true;
    emit signalRunning(running);

    out << tr("started: %1").arg(command) << endl;

    while (!stop && !abort) {
        // wait for output on timeout or process finished for some reason
        if (!process.waitForReadyRead()) {
            // process finished for some reason so exit from output loop
            out << tr("nothing left to read") << endl;
            break;
        }
        stdout = process.readAllStandardOutput();
        //lineLength = process.readLine(buf, sizeof(buf));
        //if (lineLength == -1) {
            // end of stream
        //    break;
        //}
        emit signalOutput(stdout);
        out << tr("line...") << endl;
        //emit signalOutput("zzz\n");
    }

    int  ec = process.exitCode();
    int  es = process.exitStatus();
    int  er = process.error();
    int  st = process.state();

    out << "Exit code: " + QString::number(ec) << endl;
    out << "Exit status: " + QString::number(es) << endl;
    out << "Error: " + QString::number(er) << endl;
    out << "State: " + QString::number(st) << endl;

    // wait for process to terminate, if it hasn't stopped already
    process.close();

    out << tr("finished: %1").arg(command) << endl;

    ec = process.exitCode();    // exit code from process run eg
                                // 0 - exit OK
                                // 1 - exit with some error
    es = process.exitStatus();  // 0 - OK
                                // 1 - crash/kill
    er = process.error();       // 0 - failed to start
                                // 1 - crashed
                                // 2 - timedout - can recall waitFor
                                // 3 - write error
                                // 4 - read error
                                // 5 - unknown (default)
    st = process.state();       // 0 - not running
                                // 1 - starting
                                // 2 - running

    out << "Exit code: " + QString::number(ec) << endl;
    out << "Exit status: " + QString::number(es) << endl;
    out << "Error: " + QString::number(er) << endl;
    out << "State: " + QString::number(st) << endl;

    //if (!process.waitForFinished())
    //    return false;

    //process.waitForFinished(-1); // will wait forever until finished
    //QString stdout = process.readAllStandardOutput();
    //QString stderr = process.readAllStandardError();

    //emit signalStatus(i);
    //emit signalOutput(stdout);

    // signal process is now stopped
    running = false;
    emit signalRunning(running);

    // successful execution - return 0
    emit signalResult(0);
    return 0;
}
Example #22
0
QPair<QString, QString> GetOSNameSplit ()
{
#if defined(Q_OS_MAC)
    QSysInfo::MacVersion v = QSysInfo::MacintoshVersion;
    if (v == QSysInfo::MV_10_3)
        return SplitInfo_t ("Mac OS X", "10.3");
    else if (v == QSysInfo::MV_10_4)
        return SplitInfo_t ("Mac OS X", "10.4");
    else if (v == QSysInfo::MV_10_5)
        return SplitInfo_t ("Mac OS X", "10.5");
    else if (v == QSysInfo::MV_10_6)
        return SplitInfo_t ("Mac OS X", "10.6");
    else if (v == QSysInfo::MV_10_7)
        return SplitInfo_t ("Mac OS X", "10.7");
    else
        return SplitInfo_t ("Mac OS X", "Unknown version");
#elif defined(Q_OS_WIN32)
    QSysInfo::WinVersion v = QSysInfo::WindowsVersion;
    if (v == QSysInfo::WV_95)
        return SplitInfo_t ("Windows", "95");
    else if (v == QSysInfo::WV_98)
        return SplitInfo_t ("Windows", "98");
    else if (v == QSysInfo::WV_Me)
        return SplitInfo_t ("Windows", "Me");
    else if (v == QSysInfo::WV_DOS_based)
        return SplitInfo_t ("Windows", "9x/Me");
    else if (v == QSysInfo::WV_NT)
        return SplitInfo_t ("Windows", "NT 4.x");
    else if (v == QSysInfo::WV_2000)
        return SplitInfo_t ("Windows", "2000");
    else if (v == QSysInfo::WV_XP)
        return SplitInfo_t ("Windows", "XP");
    else if (v == QSysInfo::WV_2003)
        return SplitInfo_t ("Windows", "2003");
    else if (v == QSysInfo::WV_VISTA)
        return SplitInfo_t ("Windows", "Vista");
    else if (v == QSysInfo::WV_WINDOWS7)
        return SplitInfo_t ("Windows", "7");
    else if (v == 0x00a0)
        return SplitInfo_t ("Windows", "8");
    else if (v == QSysInfo::WV_NT_based)
        return SplitInfo_t ("Windows", "NT-based");
#else
    QString osName;

    QProcess proc;
    proc.start (QString ("/bin/sh"),
                QStringList ("-c") << "lsb_release -ds", QIODevice::ReadOnly);
    if (proc.waitForStarted ())
    {
        QTextStream stream (&proc);
        QString ret;
        while (proc.waitForReadyRead ())
            ret += stream.readAll ();
        proc.close ();
        if (!ret.isEmpty ())
            osName = ret.remove ('"').trimmed ();
    }

    if (osName.isEmpty ())
    {
        struct OsInfo_t
        {
            QString path;
            QString name;
        } OsInfo [] =
        {
            { "/etc/mandrake-release", "Mandrake Linux" },
            { "/etc/debian_version", "Debian GNU/Linux" },
            { "/etc/gentoo-release", "Gentoo Linux" },
            { "/etc/exherbo-release", "Exherbo" },
            { "/etc/arch-release", "Arch Linux" },
            { "/etc/slackware-version", "Slackware Linux" },
            { "/etc/pld-release", "" },
            { "/etc/lfs-release", "LFS" },
            { "/etc/SuSE-release", "SuSE linux" },
            { "/etc/conectiva-release", "Connectiva" },
            { "/etc/.installed", "" },
            { "/etc/redhat-release", "" },
            { "", "" }
        };
        OsInfo_t *osptr = OsInfo;
        while (!osptr->path.isEmpty ())
        {
            QFileInfo fi (osptr->path);
            if (fi.exists ())
            {
                QFile f (osptr->path);
                f.open (QIODevice::ReadOnly);
                QString data = QString (f.read (1024)).trimmed ();
                if (osptr->name.isEmpty ())
                    osName = data;
                else
                    osName = QString ("%1 (%2)")
                             .arg (osptr->name)
                             .arg (data);
                break;
            }
            ++osptr;
        }
    }

    utsname u;
    uname (&u);

    return qMakePair (osName.isEmpty () ? QString (u.sysname) : osName,
                      QString ("%1 %2 %3").arg (u.machine, u.release, u.version));
#endif

    return qMakePair (QString ("Unknown OS"), QString ("Unknown version"));
}