Пример #1
0
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    // Load res_init on demand.
    static volatile bool triedResolve = false;
    if (!triedResolve) {
        QMutexLocker locker(QMutexPool::globalInstanceGet(&local_res_init));
        if (!triedResolve) {
            resolveLibrary();
            triedResolve = true;
        }
    }

    // If res_init is available, poll it.
    if (local_res_init)
        local_res_init();

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
// Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead.
#if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN)
        sockaddr_in sa4;
#ifndef QT_NO_IPV6
        sockaddr_in6 sa6;
#endif
        sockaddr *sa = 0;
        QT_SOCKLEN_T saSize = 0;
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            sa = (sockaddr *)&sa4;
            saSize = sizeof(sa4);
            memset(&sa4, 0, sizeof(sa4));
            sa4.sin_family = AF_INET;
            sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
        }
#ifndef QT_NO_IPV6
        else {
            sa = (sockaddr *)&sa6;
            saSize = sizeof(sa6);
            memset(&sa6, 0, sizeof(sa6));
            sa6.sin6_family = AF_INET6;
            memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
        }
#endif

        char hbuf[NI_MAXHOST];
        if (sa && getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
            results.setHostName(QString::fromLatin1(hbuf));
#else
        in_addr_t inetaddr = qt_safe_inet_addr(hostName.toLatin1().constData());
        struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET);
        if (ent)
            results.setHostName(QString::fromLatin1(ent->h_name));
#endif

        if (results.hostName().isEmpty())
            results.setHostName(address.toString());
        results.setAddresses(QList<QHostAddress>() << address);
        return results;
    }

    // IDN support
    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ?
                               QCoreApplication::translate("QHostInfoAgent", "No host name given") :
                               QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));
        return results;
    }

#if !defined (QT_NO_GETADDRINFO)
    // Call getaddrinfo, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.
    addrinfo *res = 0;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
#ifdef Q_ADDRCONFIG
    hints.ai_flags = Q_ADDRCONFIG;
#endif

    int result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
# ifdef Q_ADDRCONFIG
    if (result == EAI_BADFLAGS) {
        // if the lookup failed with AI_ADDRCONFIG set, try again without it
        hints.ai_flags = 0;
        result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
    }
# endif

    if (result == 0) {
        addrinfo *node = res;
        QList<QHostAddress> addresses;
        while (node) {
#ifdef QHOSTINFO_DEBUG
                qDebug() << "getaddrinfo node: flags:" << node->ai_flags << "family:" << node->ai_family << "ai_socktype:" << node->ai_socktype << "ai_protocol:" << node->ai_protocol << "ai_addrlen:" << node->ai_addrlen;
#endif
            if (node->ai_family == AF_INET) {
                QHostAddress addr;
                addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#ifndef QT_NO_IPV6
            else if (node->ai_family == AF_INET6) {
                QHostAddress addr;
                sockaddr_in6 *sa6 = (sockaddr_in6 *) node->ai_addr;
                addr.setAddress(sa6->sin6_addr.s6_addr);
                if (sa6->sin6_scope_id)
                    addr.setScopeId(QString::number(sa6->sin6_scope_id));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#endif
            node = node->ai_next;
        }
        if (addresses.isEmpty() && node == 0) {
            // Reached the end of the list, but no addresses were found; this
            // means the list contains one or more unknown address types.
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }

        results.setAddresses(addresses);
        freeaddrinfo(res);
    } else if (result == EAI_NONAME
               || result ==  EAI_FAIL
#ifdef EAI_NODATA
	       // EAI_NODATA is deprecated in RFC 3493
	       || result == EAI_NODATA
#endif
	       ) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QString::fromLocal8Bit(gai_strerror(result)));
    }

#else
    // Fall back to gethostbyname for platforms that don't define
    // getaddrinfo. gethostbyname does not support IPv6, and it's not
    // reentrant on all platforms. For now this is okay since we only
    // use one QHostInfoAgent, but if more agents are introduced, locking
    // must be provided.
    QMutexLocker locker(::getHostByNameMutex());
    hostent *result = gethostbyname(aceHostname.constData());
    if (result) {
        if (result->h_addrtype == AF_INET) {
            QList<QHostAddress> addresses;
            for (char **p = result->h_addr_list; *p != 0; p++) {
                QHostAddress addr;
                addr.setAddress(ntohl(*((quint32 *)*p)));
                if (!addresses.contains(addr))
                    addresses.prepend(addr);
            }
            results.setAddresses(addresses);
        } else {
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }
#if !defined(Q_OS_VXWORKS)
    } else if (h_errno == HOST_NOT_FOUND || h_errno == NO_DATA
               || h_errno == NO_ADDRESS) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
#endif
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(tr("Unknown error"));
    }
#endif //  !defined (QT_NO_GETADDRINFO)

#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::fromName(): error #%d %s",
               h_errno, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}",
               addresses.count(), hostName.toLatin1().constData(),
               tmp.toLatin1().constData());
    }
#endif
    return results;
}
Пример #2
0
void RemotePeer::writeMessage(const QByteArray &msg)
{
    quint32 size = qToBigEndian<quint32>(msg.size());
    _compressor->write((const char*)&size, 4, Compressor::NoFlush);
    _compressor->write(msg.constData(), msg.size());
}
Пример #3
0
bool FLACDecoder::decode(const QString &sourceFile, const QString &outputFile, volatile bool *abortFlag)
{
    QProcess process;
    QStringList args;

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

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

    bool bTimeout = false;
    bool bAborted = false;

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

    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("FLAC 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) 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.exitStatus() != QProcess::NormalExit || QFileInfo(outputFile).size() == 0)
    {
        return false;
    }

    return true;
}
void Lib_initializer::load_filters_plugins()
{
    SmartPtr<Named_interface> ni = Root::instance()->interface(topLevelInputFilters_manager);
    Manager* mng = dynamic_cast<Manager*> (ni.raw_ptr());
    appli_assert( mng );

    std::string filters_plugin_path(mng->plugin_path());
    QString path(filters_plugin_path.c_str());

    // Loop on all the library files (.so or .dll) in directory "path"
    QDir dir(path);
    if (!dir.exists())
        return;

    QStringList filters;
    filters << "*.so" << "*.dll";
    dir.setNameFilters(filters);
    dir.setFilter(QDir::Files);
    const QFileInfoList list = dir.entryInfoList();

    if (list.empty())
    {
        GsTLlog << "No filter plugins found.\n" << gstlIO::end;
        return;
    }

    QFileInfoList::const_iterator it = list.begin();
    const QFileInfo* f_info;

    for (; it != list.end(); ++it)
    {
        f_info = &(*it);
        // QLibrary wants the absolute path
        QString tmp = path + "/" + f_info->fileName();
        QByteArray tmps = tmp.toLatin1();
        appli_message( "loading file: " << tmps.constData());
        QLibrary lib(path + "/" + f_info->fileName());
        //lib.setAutoUnload( false );
        lib.load();
        if (!lib.isLoaded())
        {
            appli_warning( "library not loaded " << std::endl );
            continue;
        }

        typedef int (*Init_func_prototype)(void);

        // The function must be called [filename]_init()
        // QString init_func_name( f_info->baseName() + "_init" );

        // The function must be called plugin_init()
        QString init_func_name = "plugin_init";
        QByteArray tmp1 = init_func_name.toLatin1();
        Init_func_prototype init_func = (Init_func_prototype) lib.resolve(tmp1.constData());

        if (init_func)
            init_func();
        else
        {
            QByteArray s = init_func_name.toLatin1();
            appli_warning( "unable to resolve symbol " << s.constData() );
        }

    }

}
Пример #5
0
static bool matchString(const QMimeMagicRulePrivate *d, const QByteArray &data)
{
    const int rangeLength = d->endPos - d->startPos + 1;
    return QMimeMagicRule::matchSubstring(data.constData(), data.size(), d->startPos, rangeLength, d->pattern.size(), d->pattern.constData(), d->mask.constData());
}
Пример #6
0
void MpegRecorder::run(void)
{
    if (!Open())
    {
        if (_error.isEmpty())
            _error = "Failed to open V4L device";
        return;
    }

    bool has_select = true;

#if defined(__FreeBSD__)
    // HACK. FreeBSD PVR150/500 driver doesn't currently support select()
    has_select = false;
#endif

    if (driver == "hdpvr")
    {
        int progNum = 1;
        MPEGStreamData *sd = new MPEGStreamData(progNum, true);
        sd->SetRecordingType(_recording_type);
        DTVRecorder::SetStreamData(sd);

        _stream_data->AddAVListener(this);
        _stream_data->AddWritingListener(this);

        // Make sure the first things in the file are a PAT & PMT
        _wait_for_keyframe_option = false;
        HandleSingleProgramPAT(_stream_data->PATSingleProgram());
        HandleSingleProgramPMT(_stream_data->PMTSingleProgram());
        _wait_for_keyframe_option = true;
    }

    {
        QMutexLocker locker(&pauseLock);
        request_recording = true;
        request_helper = true;
        recording = true;
        recordingWait.wakeAll();
    }

    unsigned char *buffer = new unsigned char[bufferSize + 1];
    int len;
    int remainder = 0;

    MythTimer elapsedTimer;
    float elapsed;
    long long bytesRead = 0;
    int dummyBPS = 0;  // Bytes per second, but env var is BITS PER SECOND

    if (getenv("DUMMYBPS"))
    {
        dummyBPS = atoi(getenv("DUMMYBPS")) / 8;
        LOG(VB_GENERAL, LOG_INFO,
            LOC + QString("Throttling dummy recorder to %1 bits per second")
                .arg(dummyBPS * 8));
    }

    struct timeval tv;
    fd_set rdset;

    if (deviceIsMpegFile)
        elapsedTimer.start();
    else if (_device_read_buffer)
    {
        LOG(VB_RECORD, LOG_INFO, LOC + "Initial startup of recorder");
        StartEncoding();
    }

    QByteArray vdevice = videodevice.toAscii();
    while (IsRecordingRequested() && !IsErrored())
    {
        if (PauseAndWait(100))
            continue;

        if (deviceIsMpegFile)
        {
            if (dummyBPS && bytesRead)
            {
                elapsed = (elapsedTimer.elapsed() / 1000.0) + 1;
                while ((bytesRead / elapsed) > dummyBPS)
                {
                    usleep(50000);
                    elapsed = (elapsedTimer.elapsed() / 1000.0) + 1;
                }
            }
            else if (GetFramesWritten())
            {
                elapsed = (elapsedTimer.elapsed() / 1000.0) + 1;
                while ((GetFramesWritten() / elapsed) > 30)
                {
                    usleep(50000);
                    elapsed = (elapsedTimer.elapsed() / 1000.0) + 1;
                }
            }
        }

        if (_device_read_buffer)
        {
            len = _device_read_buffer->Read(
                    &(buffer[remainder]), bufferSize - remainder);

            // Check for DRB errors
            if (_device_read_buffer->IsErrored())
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "Device error detected");

                RestartEncoding();
            }
            else if (_device_read_buffer->IsEOF() &&
                     IsRecordingRequested())
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "Device EOF detected");
                _error = "Device EOF detected";
            }
        }
        else
        {
            if (has_select)
            {
                tv.tv_sec = 5;
                tv.tv_usec = 0;
                FD_ZERO(&rdset);
                FD_SET(readfd, &rdset);

                switch (select(readfd + 1, &rdset, NULL, NULL, &tv))
                {
                    case -1:
                        if (errno == EINTR)
                            continue;

                        LOG(VB_GENERAL, LOG_ERR, LOC + "Select error" + ENO);
                        continue;

                    case 0:
                        LOG(VB_GENERAL, LOG_ERR, LOC + "select timeout - "
                                "driver has stopped responding");

                        if (close(readfd) != 0)
                        {
                            LOG(VB_GENERAL, LOG_ERR, LOC + "Close error" + ENO);
                        }

                        // Force card to be reopened on next iteration..
                        readfd = -1;
                        continue;

                    default:
                        break;
                }
            }

            len = read(readfd, &(buffer[remainder]), bufferSize - remainder);

            if (len < 0 && !has_select)
            {
                QMutexLocker locker(&pauseLock);
                if (request_recording && !request_pause)
                    unpauseWait.wait(&pauseLock, 25);
                continue;
            }

            if ((len == 0) && (deviceIsMpegFile))
            {
                close(readfd);
                readfd = open(vdevice.constData(), O_RDONLY);

                if (readfd >= 0)
                {
                    len = read(readfd,
                               &(buffer[remainder]), bufferSize - remainder);
                }

                if (len <= 0)
                {
                    _error = "Failed to read from video file";
                    continue;
                }
            }
            else if (len < 0 && errno != EAGAIN)
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + QString("error reading from: %1")
                        .arg(videodevice) + ENO);
                continue;
            }
        }

        if (len > 0)
        {
            bytesRead += len;
            len += remainder;

            if (driver == "hdpvr")
            {
                remainder = _stream_data->ProcessData(buffer, len);
                int start_remain = len - remainder;
                if (remainder && (start_remain >= remainder))
                    memcpy(buffer, buffer+start_remain, remainder);
                else if (remainder)
                    memmove(buffer, buffer+start_remain, remainder);
            }
            else
            {
                FindPSKeyFrames(buffer, len);
            }
        }
    }

    LOG(VB_RECORD, LOG_INFO, LOC + "run finishing up");

    StopEncoding();

    {
        QMutexLocker locker(&pauseLock);
        request_helper = false;
    }

    if (vbi_thread)
    {
        vbi_thread->wait();
        delete vbi_thread;
        vbi_thread = NULL;
        CloseVBIDevice();
    }

    FinishRecording();

    delete[] buffer;

    if (driver == "hdpvr")
    {
        _stream_data->RemoveWritingListener(this);
        _stream_data->RemoveAVListener(this);
        DTVRecorder::SetStreamData(NULL);
    }

    QMutexLocker locker(&pauseLock);
    request_recording = false;
    recording = false;
    recordingWait.wakeAll();
}
Пример #7
0
void VoiceMessagesLoader::onLoad(AudioData *audio) {
	bool started = false;
	int32 audioindex = -1;
	Loader *l = 0;
	Loaders::iterator j = _loaders.end();
	{
		QMutexLocker lock(&voicemsgsMutex);
		VoiceMessages *voice = audioVoice();
		if (!voice) return;

		for (int32 i = 0; i < AudioVoiceMsgSimultaneously; ++i) {
			VoiceMessages::Msg &m(voice->_data[i]);
			if (m.audio != audio || !m.loading) continue;

			audioindex = i;
			j = _loaders.find(audio);
			if (j != _loaders.end() && (j.value()->fname != m.fname || j.value()->data.size() != m.data.size())) {
				delete j.value();
				_loaders.erase(j);
				j = _loaders.end();
			}
			if (j == _loaders.end()) {
				l = (j = _loaders.insert(audio, new Loader())).value();
				l->fname = m.fname;
				l->data = m.data;
				
				int ret;
				if (m.data.isEmpty()) {
					l->file = op_open_file(m.fname.toUtf8().constData(), &ret);
				} else {
					l->file = op_open_memory((const unsigned char*)m.data.constData(), m.data.size(), &ret);
				}
				if (!l->file) {
					LOG(("Audio Error: op_open_file failed for '%1', data size '%2', error code %3").arg(m.fname).arg(m.data.size()).arg(ret));
					m.state = VoiceMessageStopped;
					return loadError(j);
				}
				ogg_int64_t duration = op_pcm_total(l->file, -1);
				if (duration < 0) {
					LOG(("Audio Error: op_pcm_total failed to get full duration for '%1', data size '%2', error code %3").arg(m.fname).arg(m.data.size()).arg(duration));
					m.state = VoiceMessageStopped;
					return loadError(j);
				}
				m.duration = duration;
				m.skipStart = 0;
				m.skipEnd = duration;
				m.position = 0;
				m.started = 0;
				started = true;
			} else {
				if (!m.skipEnd) continue;
				l = j.value();
			}
			break;
		}
	}

	if (j == _loaders.end()) {
		LOG(("Audio Error: trying to load part of audio, that is not playing at the moment"));
		emit error(audio);
		return;
	}
	if (started) {
		l->pcm_offset = op_pcm_tell(l->file);
		l->pcm_print_offset = l->pcm_offset - AudioVoiceMsgFrequency;
	}

	bool finished = false;
    DEBUG_LOG(("Audio Info: reading buffer for file '%1', data size '%2', current pcm_offset %3").arg(l->fname).arg(l->data.size()).arg(l->pcm_offset));

	QByteArray result;
	int64 samplesAdded = 0;
	while (result.size() < AudioVoiceMsgBufferSize) {
		opus_int16 pcm[AudioVoiceMsgFrequency * AudioVoiceMsgChannels];

		int ret = op_read_stereo(l->file, pcm, sizeof(pcm) / sizeof(*pcm));
		if (ret < 0) {
			{
				QMutexLocker lock(&voicemsgsMutex);
				VoiceMessages *voice = audioVoice();
				if (voice) {
					VoiceMessages::Msg &m(voice->_data[audioindex]);
					if (m.audio == audio) {
						m.state = VoiceMessageStopped;
					}
				}
			}
			LOG(("Audio Error: op_read_stereo failed, error code %1").arg(ret));
			return loadError(j);
		}

		int li = op_current_link(l->file);
		if (li != l->prev_li) {
			const OpusHead *head = op_head(l->file, li);
			const OpusTags *tags = op_tags(l->file, li);
			for (int32 ci = 0; ci < tags->comments; ++ci) {
				const char *comment = tags->user_comments[ci];
				if (opus_tagncompare("METADATA_BLOCK_PICTURE", 22, comment) == 0) {
					OpusPictureTag pic;
					int err = opus_picture_tag_parse(&pic, comment);
					if (err >= 0) {
						opus_picture_tag_clear(&pic);
					}
				}
			}
			if (!op_seekable(l->file)) {
				l->pcm_offset = op_pcm_tell(l->file) - ret;
			}
		}
		if (li != l->prev_li || l->pcm_offset >= l->pcm_print_offset + AudioVoiceMsgFrequency) {
			l->pcm_print_offset = l->pcm_offset;
		}
		l->pcm_offset = op_pcm_tell(l->file);

		if (!ret) {
			DEBUG_LOG(("Audio Info: read completed"));
			finished = true;
			break;
		}
		result.append((const char*)pcm, sizeof(*pcm) * ret * AudioVoiceMsgChannels);
		l->prev_li = li;
		samplesAdded += ret;

		{
			QMutexLocker lock(&voicemsgsMutex);
			VoiceMessages *voice = audioVoice();
			if (!voice) return;

			VoiceMessages::Msg &m(voice->_data[audioindex]);
			if (m.audio != audio || !m.loading || m.fname != l->fname || m.data.size() != l->data.size()) {
				LOG(("Audio Error: playing changed while loading"));
				m.state = VoiceMessageStopped;
				return loadError(j);
			}
		}
	}

	QMutexLocker lock(&voicemsgsMutex);
	VoiceMessages *voice = audioVoice();
	if (!voice) return;

	VoiceMessages::Msg &m(voice->_data[audioindex]);
	if (m.audio != audio || !m.loading || m.fname != l->fname || m.data.size() != l->data.size()) {
		LOG(("Audio Error: playing changed while loading"));
		m.state = VoiceMessageStopped;
		return loadError(j);
	}

	if (started) {
		if (m.source) {
			alSourceStop(m.source);
			for (int32 i = 0; i < 3; ++i) {
				if (m.samplesCount[i]) {
					alSourceUnqueueBuffers(m.source, 1, m.buffers + i);
					m.samplesCount[i] = 0;
				}
			}
			m.nextBuffer = 0;
		}
	}
	if (samplesAdded) {
		if (!m.source) {
			alGenSources(1, &m.source);
			alSourcef(m.source, AL_PITCH, 1.f);
			alSourcef(m.source, AL_GAIN, 1.f);
			alSource3f(m.source, AL_POSITION, 0, 0, 0);
			alSource3f(m.source, AL_VELOCITY, 0, 0, 0);
			alSourcei(m.source, AL_LOOPING, 0);
		}
		if (!m.buffers[m.nextBuffer]) alGenBuffers(3, m.buffers);
		if (!_checkALError()) {
			m.state = VoiceMessageStopped;
			return loadError(j);
		}

		if (m.samplesCount[m.nextBuffer]) {
			alSourceUnqueueBuffers(m.source, 1, m.buffers + m.nextBuffer);
			m.skipStart += m.samplesCount[m.nextBuffer];
		}

		m.samplesCount[m.nextBuffer] = samplesAdded;
		alBufferData(m.buffers[m.nextBuffer], AL_FORMAT_STEREO16, result.constData(), result.size(), AudioVoiceMsgFrequency);
		alSourceQueueBuffers(m.source, 1, m.buffers + m.nextBuffer);
		m.skipEnd -= samplesAdded;

		m.nextBuffer = (m.nextBuffer + 1) % 3;

		if (!_checkALError()) {
			m.state = VoiceMessageStopped;
			return loadError(j);
		}
	} else {
		finished = true;
	}
	if (finished) {
		m.skipEnd = 0;
		m.duration = m.skipStart + m.samplesCount[0] + m.samplesCount[1] + m.samplesCount[2];
	}
	m.loading = false;
	if (m.state == VoiceMessageResuming || m.state == VoiceMessagePlaying || m.state == VoiceMessageStarting) {
		ALint state = AL_INITIAL;
		alGetSourcei(m.source, AL_SOURCE_STATE, &state);
		if (_checkALError()) {
			if (state != AL_PLAYING) {
				alSourcePlay(m.source);
				emit needToCheck();
			}
		}
	}
}
Пример #8
0
void DatagramProcessor::processDatagrams() {
    PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings),
                            "DatagramProcessor::processDatagrams()");
    
    HifiSockAddr senderSockAddr;
    
    static QByteArray incomingPacket;
    
    Application* application = Application::getInstance();
    auto nodeList = DependencyManager::get<NodeList>();
    
    while (DependencyManager::get<NodeList>()->getNodeSocket().hasPendingDatagrams()) {
        incomingPacket.resize(nodeList->getNodeSocket().pendingDatagramSize());
        nodeList->getNodeSocket().readDatagram(incomingPacket.data(), incomingPacket.size(),
                                               senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer());
        
        _packetCount++;
        _byteCount += incomingPacket.size();
        
        if (nodeList->packetVersionAndHashMatch(incomingPacket)) {
            
            PacketType incomingType = packetTypeForPacket(incomingPacket);
            // only process this packet if we have a match on the packet version
            switch (incomingType) {
                case PacketTypeAudioEnvironment:
                case PacketTypeAudioStreamStats:
                case PacketTypeMixedAudio:
                case PacketTypeSilentAudioFrame: {
                    if (incomingType == PacketTypeAudioStreamStats) {
                        QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "parseAudioStreamStatsPacket",
                                                  Qt::QueuedConnection,
                                                  Q_ARG(QByteArray, incomingPacket));
                    } else if (incomingType == PacketTypeAudioEnvironment) {
                        QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "parseAudioEnvironmentData",
                                                  Qt::QueuedConnection,
                                                  Q_ARG(QByteArray, incomingPacket));
                    } else {
                        QMetaObject::invokeMethod(DependencyManager::get<Audio>().data(), "addReceivedAudioToStream",
                                                  Qt::QueuedConnection,
                                                  Q_ARG(QByteArray, incomingPacket));
                    }
                    
                    // update having heard from the audio-mixer and record the bytes received
                    SharedNodePointer audioMixer = nodeList->sendingNodeForPacket(incomingPacket);
                    
                    if (audioMixer) {
                        audioMixer->setLastHeardMicrostamp(usecTimestampNow());
                        audioMixer->recordBytesReceived(incomingPacket.size());
                    }
                    
                    break;
                }
                case PacketTypeEntityAddResponse:
                    // this will keep creatorTokenIDs to IDs mapped correctly
                    EntityItemID::handleAddEntityResponse(incomingPacket);
                    application->getEntities()->getTree()->handleAddEntityResponse(incomingPacket);
                    break;
                case PacketTypeEntityData:
                case PacketTypeEntityErase:
                case PacketTypeOctreeStats:
                case PacketTypeEnvironmentData: {
                    PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings),
                                            "Application::networkReceive()... _octreeProcessor.queueReceivedPacket()");
                    SharedNodePointer matchedNode = DependencyManager::get<NodeList>()->sendingNodeForPacket(incomingPacket);
                    
                    if (matchedNode) {
                        // add this packet to our list of octree packets and process them on the octree data processing
                        application->_octreeProcessor.queueReceivedPacket(matchedNode, incomingPacket);
                    }
                    
                    break;
                }
                case PacketTypeMetavoxelData:
                    nodeList->findNodeAndUpdateWithDataFromPacket(incomingPacket);
                    break;
                case PacketTypeBulkAvatarData:
                case PacketTypeKillAvatar:
                case PacketTypeAvatarIdentity:
                case PacketTypeAvatarBillboard: {
                    // update having heard from the avatar-mixer and record the bytes received
                    SharedNodePointer avatarMixer = nodeList->sendingNodeForPacket(incomingPacket);
                    
                    if (avatarMixer) {
                        avatarMixer->setLastHeardMicrostamp(usecTimestampNow());
                        avatarMixer->recordBytesReceived(incomingPacket.size());
                        
                        QMetaObject::invokeMethod(&application->getAvatarManager(), "processAvatarMixerDatagram",
                                                  Q_ARG(const QByteArray&, incomingPacket),
                                                  Q_ARG(const QWeakPointer<Node>&, avatarMixer));
                    }
                    
                    application->_bandwidthMeter.inputStream(BandwidthMeter::AVATARS).updateValue(incomingPacket.size());
                    break;
                }
                case PacketTypeDomainConnectionDenied: {
                    // output to the log so the user knows they got a denied connection request
                    // and check and signal for an access token so that we can make sure they are logged in
                    qDebug() << "The domain-server denied a connection request.";
                    qDebug() << "You may need to re-log to generate a keypair so you can provide a username signature.";
                    AccountManager::getInstance().checkAndSignalForAccessToken();
                    break;
                }
                case PacketTypeNoisyMute:
                case PacketTypeMuteEnvironment: {
                    bool mute = !DependencyManager::get<Audio>()->isMuted();
                    
                    if (incomingType == PacketTypeMuteEnvironment) {
                        glm::vec3 position;
                        float radius, distance;
                        
                        int headerSize = numBytesForPacketHeaderGivenPacketType(PacketTypeMuteEnvironment);
                        memcpy(&position, incomingPacket.constData() + headerSize, sizeof(glm::vec3));
                        memcpy(&radius, incomingPacket.constData() + headerSize + sizeof(glm::vec3), sizeof(float));
                        distance = glm::distance(Application::getInstance()->getAvatar()->getPosition(), position);
                        
                        mute = mute && (distance < radius);
                    }
                    
                    if (mute) {
                        DependencyManager::get<Audio>()->toggleMute();
                        if (incomingType == PacketTypeMuteEnvironment) {
                            AudioScriptingInterface::getInstance().environmentMuted();
                        } else {
                            AudioScriptingInterface::getInstance().mutedByMixer();
                        }
                    }
                    break;
                }
                case PacketTypeEntityEditNack:
                    if (!Menu::getInstance()->isOptionChecked(MenuOption::DisableNackPackets)) {
                        application->_entityEditSender.processNackPacket(incomingPacket);
                    }
                    break;
                default:
                    nodeList->processNodeData(senderSockAddr, incomingPacket);
                    break;
            }
        }
    }
Пример #9
0
int QgsGml::getFeatures( const QString& uri, QGis::WkbType* wkbType, QgsRectangle* extent )
{
  mUri = uri;
  mWkbType = wkbType;

  XML_Parser p = XML_ParserCreateNS( NULL, NS_SEPARATOR );
  XML_SetUserData( p, this );
  XML_SetElementHandler( p, QgsGml::start, QgsGml::end );
  XML_SetCharacterDataHandler( p, QgsGml::chars );

  //start with empty extent
  mExtent.setMinimal();

  QNetworkRequest request( mUri );
  QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request );

  connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) );
  connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) );

  //find out if there is a QGIS main window. If yes, display a progress dialog
  QProgressDialog* progressDialog = 0;
  QWidget* mainWindow = qApp->activeWindow();
  if ( mainWindow )
  {
    progressDialog = new QProgressDialog( tr( "Loading GML data\n%1" ).arg( mTypeName ), tr( "Abort" ), 0, 0, mainWindow );
    progressDialog->setWindowModality( Qt::ApplicationModal );
    connect( this, SIGNAL( dataReadProgress( int ) ), progressDialog, SLOT( setValue( int ) ) );
    connect( this, SIGNAL( totalStepsUpdate( int ) ), progressDialog, SLOT( setMaximum( int ) ) );
    connect( progressDialog, SIGNAL( canceled() ), this, SLOT( setFinished() ) );
    progressDialog->show();
  }

  int atEnd = 0;
  while ( !atEnd )
  {
    if ( mFinished )
    {
      atEnd = 1;
    }
    QByteArray readData = reply->readAll();
    if ( readData.size() > 0 )
    {
      XML_Parse( p, readData.constData(), readData.size(), atEnd );
    }
    QCoreApplication::processEvents();
  }

  delete reply;
  delete progressDialog;

  if ( *mWkbType != QGis::WKBNoGeometry )
  {
    if ( mExtent.isEmpty() )
    {
      //reading of bbox from the server failed, so we calculate it less efficiently by evaluating the features
      calculateExtentFromFeatures();
    }
  }

  XML_ParserFree( p );

  if ( extent )
    *extent = mExtent;

  return 0;
}
Пример #10
0
static void qStreamNtlmBuffer(QDataStream& ds, const QByteArray& s)
{
    ds.writeRawData(s.constData(), s.size());
}
Пример #11
0
QString QDeclarativeNdefMimeRecord::uri() const
{
    QByteArray dataUri = "data:" + record().type() + ";base64," + record().payload().toBase64();
    return QString::fromAscii(dataUri.constData(), dataUri.length());
}
Пример #12
0
QHash<QByteArray, QByteArray> QAuthenticatorPrivate::parseDigestAuthenticationChallenge(const QByteArray &challenge)
{
    QHash<QByteArray, QByteArray> options;
    // parse the challenge
    const char *d = challenge.constData();
    const char *end = d + challenge.length();
    while (d < end) {
        while (d < end && (*d == ' ' || *d == '\n' || *d == '\r'))
            ++d;
        const char *start = d;
        while (d < end && *d != '=')
            ++d;
        QByteArray key = QByteArray(start, d - start);
        ++d;
        if (d >= end)
            break;
        bool quote = (*d == '"');
        if (quote) 
            ++d;
        if (d >= end)
            break;
        start = d;
        QByteArray value;
        while (d < end) {
            bool backslash = false;
            if (*d == '\\' && d < end - 1) {
                ++d;
                backslash = true;
            }
            if (!backslash) {
                if (quote) {
                    if (*d == '"')
                        break;
                } else {
                    if (*d == ',')
                        break;
                }
            }
            value += *d;
            ++d;
        }
        while (d < end && *d != ',')
            ++d;
        ++d;
        options[key] = value;
    }

    QByteArray qop = options.value("qop");
    if (!qop.isEmpty()) {
        QList<QByteArray> qopoptions = qop.split(',');
        if (!qopoptions.contains("auth"))
            return QHash<QByteArray, QByteArray>();
        // #### can't do auth-int currently
//         if (qop.contains("auth-int"))
//             qop = "auth-int";
//         else if (qop.contains("auth"))
//             qop = "auth";
//         else
//             qop = QByteArray();
        options["qop"] = "auth";
    }
    
    return options;
}
Пример #13
0
bool BaseTextDocument::open(const QString &fileName)
{
    QString title = tr("untitled");
    if (!fileName.isEmpty()) {
        const QFileInfo fi(fileName);
        m_fileName = fi.absoluteFilePath();

        QFile file(fileName);
        if (!file.exists())
            return false;

        if (!fi.isReadable())
            return false;

        if (!fi.isWritable()) {
            if (!file.open(QIODevice::ReadOnly))
                return false;
        } else {
            if (!file.open(QIODevice::ReadWrite))
                return false;
        }
        title = fi.fileName();

        QByteArray buf = file.readAll();
        int bytesRead = buf.size();

        QTextCodec *codec = m_codec;

        // code taken from qtextstream
        if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0)
                               || (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) {
            codec = QTextCodec::codecForName("UTF-32");
        } else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe)
                                      || (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) {
            codec = QTextCodec::codecForName("UTF-16");
        } else if (!codec) {
            codec = QTextCodec::codecForLocale();
        }
        // end code taken from qtextstream

        m_codec = codec;

#if 0 // should work, but does not, Qt bug with "system" codec
        QTextDecoder *decoder = m_codec->makeDecoder();
        QString text = decoder->toUnicode(buf);
        m_hasDecodingError = (decoder->hasFailure());
        delete decoder;
#else
        QString text = m_codec->toUnicode(buf);
        QByteArray verifyBuf = m_codec->fromUnicode(text); // slow
        // the minSize trick lets us ignore unicode headers
        int minSize = qMin(verifyBuf.size(), buf.size());
        m_hasDecodingError = (minSize < buf.size()- 4
                              || memcmp(verifyBuf.constData() + verifyBuf.size() - minSize,
                                        buf.constData() + buf.size() - minSize, minSize));
#endif

        if (m_hasDecodingError) {
            int p = buf.indexOf('\n', 16384);
            if (p < 0)
                m_decodingErrorSample = buf;
            else
                m_decodingErrorSample = buf.left(p);
        } else {
            m_decodingErrorSample.clear();
        }

        int lf = text.indexOf('\n');
        if (lf > 0 && text.at(lf-1) == QLatin1Char('\r')) {
            m_lineTerminatorMode = CRLFLineTerminator;
        } else if (lf >= 0) {
            m_lineTerminatorMode = LFLineTerminator;
        } else {
            m_lineTerminatorMode = NativeLineTerminator;
        }

        m_document->setModified(false);
        m_document->setUndoRedoEnabled(false);
        if (m_isBinaryData)
            m_document->setHtml(tr("<em>Binary data</em>"));
        else
            m_document->setPlainText(text);
        m_document->setUndoRedoEnabled(true);
        TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(m_document->documentLayout());
        QTC_ASSERT(documentLayout, return true);
        documentLayout->lastSaveRevision = 0;
        m_document->setModified(false);
        emit titleChanged(title);
        emit changed();
    }
    return true;
}
Пример #14
0
void Writer::writeFromBuffer(const QByteArray &buffer)
{
	int len = protocol::Message::sniffLength(buffer.constData());
	Q_ASSERT(len <= buffer.length());
	_file->write(buffer.constData(), len);
}
Пример #15
0
QMap<QString, CallTip> CallTipsList::extractTips(const QString& context) const
{
    Base::PyGILStateLocker lock;
    QMap<QString, CallTip> tips;
    if (context.isEmpty())
        return tips;

    try {
        QStringList items = context.split(QLatin1Char('.'));
        Py::Module module("__main__");
        Py::Dict dict = module.getDict();
        QString modname = items.front();
        items.pop_front();
        if (!dict.hasKey(std::string(modname.toLatin1())))
            return tips; // unknown object

        // get the Python object we need
        Py::Object obj = dict.getItem(std::string(modname.toLatin1()));
        while (!items.isEmpty()) {
            QByteArray name = items.front().toLatin1();
            std::string attr = name.constData();
            items.pop_front();
            if (obj.hasAttr(attr))
                obj = obj.getAttr(attr);
            else
                return tips;
        }
        
        // Checks whether the type is a subclass of PyObjectBase because to get the doc string
        // of a member we must get it by its type instead of its instance otherwise we get the
        // wrong string, namely that of the type of the member. 
        // Note: 3rd party libraries may use their own type object classes so that we cannot 
        // reliably use Py::Type. To be on the safe side we should use Py::Object to assign
        // the used type object to.
        //Py::Object type = obj.type();
        Py::Object type(PyObject_Type(obj.ptr()), true);
        Py::Object inst = obj; // the object instance 
        union PyType_Object typeobj = {&Base::PyObjectBase::Type};
        union PyType_Object typedoc = {&App::DocumentObjectPy::Type};
        if (PyObject_IsSubclass(type.ptr(), typedoc.o) == 1) {
            // From the template Python object we don't query its type object because there we keep
            // a list of additional methods that we won't see otherwise. But to get the correct doc
            // strings we query the type's dict in the class itself.
            // To see if we have a template Python object we check for the existence of supportedProperties
            if (!type.hasAttr("supportedProperties")) {
                obj = type;
            }
        }
        else if (PyObject_IsSubclass(type.ptr(), typeobj.o) == 1) {
            obj = type;
        }
        
        // If we have an instance of PyObjectBase then determine whether it's valid or not
        if (PyObject_IsInstance(inst.ptr(), typeobj.o) == 1) {
            Base::PyObjectBase* baseobj = static_cast<Base::PyObjectBase*>(inst.ptr());
            const_cast<CallTipsList*>(this)->validObject = baseobj->isValid();
        }
        else {
            // PyObject_IsInstance might set an exception
            PyErr_Clear();
        }

        Py::List list(PyObject_Dir(obj.ptr()), true);

        // If we derive from PropertyContainerPy we can search for the properties in the
        // C++ twin class.
        union PyType_Object proptypeobj = {&App::PropertyContainerPy::Type};
        if (PyObject_IsSubclass(type.ptr(), proptypeobj.o) == 1) {
            // These are the attributes of the instance itself which are NOT accessible by
            // its type object
            extractTipsFromProperties(inst, tips);
        }

        // If we derive from App::DocumentPy we have direct access to the objects by their internal
        // names. So, we add these names to the list, too.
        union PyType_Object appdoctypeobj = {&App::DocumentPy::Type};
        if (PyObject_IsSubclass(type.ptr(), appdoctypeobj.o) == 1) {
            App::DocumentPy* docpy = (App::DocumentPy*)(inst.ptr());
            App::Document* document = docpy->getDocumentPtr();
            // Make sure that the C++ object is alive
            if (document) {
                std::vector<App::DocumentObject*> objects = document->getObjects();
                Py::List list;
                for (std::vector<App::DocumentObject*>::iterator it = objects.begin(); it != objects.end(); ++it)
                    list.append(Py::String((*it)->getNameInDocument()));
                extractTipsFromObject(inst, list, tips);
            }
        }

        // If we derive from Gui::DocumentPy we have direct access to the objects by their internal
        // names. So, we add these names to the list, too.
        union PyType_Object guidoctypeobj = {&Gui::DocumentPy::Type};
        if (PyObject_IsSubclass(type.ptr(), guidoctypeobj.o) == 1) {
            Gui::DocumentPy* docpy = (Gui::DocumentPy*)(inst.ptr());
            if (docpy->getDocumentPtr()) {
                App::Document* document = docpy->getDocumentPtr()->getDocument();
                // Make sure that the C++ object is alive
                if (document) {
                    std::vector<App::DocumentObject*> objects = document->getObjects();
                    Py::List list;
                    for (std::vector<App::DocumentObject*>::iterator it = objects.begin(); it != objects.end(); ++it)
                        list.append(Py::String((*it)->getNameInDocument()));
                    extractTipsFromObject(inst, list, tips);
                }
            }
        }

        // These are the attributes from the type object
        extractTipsFromObject(obj, list, tips);
    }
    catch (Py::Exception& e) {
        // Just clear the Python exception
        e.clear();
    }

    return tips;
}
Пример #16
0
bool ParamComboBox :: StoreParameterValue ()
{
	QVariant v = pcb_combo_box_p -> currentData ();
	bool success_flag = false;

	switch (bpw_param_p -> pa_type)
		{
			case PT_LARGE_STRING:
			case PT_STRING:
			case PT_FILE_TO_READ:
			case PT_FILE_TO_WRITE:
			case PT_DIRECTORY:
			case PT_KEYWORD:
				{
					QString s (v.toString ());
					QByteArray ba = s.toLocal8Bit ();

					const char *value_s = ba.constData ();

					success_flag = SetParameterValue (bpw_param_p, value_s, true);

					qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << value_s;
				}
				break;

			case PT_CHAR:
				{
					QChar qc = v.toChar ();
					char c = qc.toLatin1 ();
					success_flag = SetParameterValue (bpw_param_p, &c, true);

					qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << c;
				}
				break;

			case PT_BOOLEAN:
				{
					bool b = v.toBool ();
					success_flag = SetParameterValue (bpw_param_p, &b, true);

					qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << b;
				}
				break;

			case PT_SIGNED_INT:
			case PT_UNSIGNED_INT:
				{
					bool conv_flag = false;
					int i = v.toInt (&conv_flag);

					if (conv_flag)
						{
							success_flag = SetParameterValue (bpw_param_p, &i, true);
							qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << i;
						}
				}
				break;

			case PT_SIGNED_REAL:
			case PT_UNSIGNED_REAL:
				{
					bool conv_flag = false;
					double d = v.toDouble (&conv_flag);

					if (conv_flag)
						{
							success_flag = SetParameterValue (bpw_param_p, &d, true);

							qDebug () << "Setting " << bpw_param_p -> pa_name_s << " to " << d;
						}
				}
				break;

			default:
				break;
		}


	return success_flag;
}
Пример #17
0
bool MpegRecorder::OpenV4L2DeviceAsInput(void)
{
    // open implicitly starts encoding, so we need the lock..
    QMutexLocker locker(&start_stop_encoding_lock);

    QByteArray vdevice = videodevice.toAscii();
    chanfd = open(vdevice.constData(), O_RDWR);
    if (chanfd < 0)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "Can't open video device. " + ENO);
        return false;
    }

    bufferSize = 4096;

    bool supports_tuner = false, supports_audio = false;
    uint32_t capabilities = 0;
    if (CardUtil::GetV4LInfo(chanfd, card, driver, version, capabilities))
    {
        supports_sliced_vbi = !!(capabilities & V4L2_CAP_SLICED_VBI_CAPTURE);
        supports_tuner      = !!(capabilities & V4L2_CAP_TUNER);
        supports_audio      = !!(capabilities & V4L2_CAP_AUDIO);
        /// Determine hacks needed for specific drivers & driver versions
        if (driver == "hdpvr")
        {
            bufferSize = 1500 * TSPacket::kSize;
            m_h264_parser.use_I_forKeyframes(false);
        }
    }

    if (!(capabilities & V4L2_CAP_VIDEO_CAPTURE))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "V4L version 1, unsupported");
        close(chanfd);
        chanfd = -1;
        return false;
    }

    if (!SetVideoCaptureFormat(chanfd))
    {
        close(chanfd);
        chanfd = -1;
        return false;
    }

    if (supports_tuner)
        SetLanguageMode(chanfd);    // we don't care if this fails...

    if (supports_audio)
        SetRecordingVolume(chanfd); // we don't care if this fails...

    if (!SetV4L2DeviceOptions(chanfd))
    {
        close(chanfd);
        chanfd = -1;
        return false;
    }

    SetVBIOptions(chanfd); // we don't care if this fails...

    readfd = open(vdevice.constData(), O_RDWR | O_NONBLOCK);

    if (readfd < 0)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "Can't open video device." + ENO);
        close(chanfd);
        chanfd = -1;
        return false;
    }

    if (_device_read_buffer)
    {
        if (_device_read_buffer->IsRunning())
            _device_read_buffer->Stop();

        delete _device_read_buffer;
        _device_read_buffer = NULL;
    }

    _device_read_buffer = new DeviceReadBuffer(this);

    if (!_device_read_buffer)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to allocate DRB buffer");
        _error = "Failed to allocate DRB buffer";
        close(chanfd);
        chanfd = -1;
        close(readfd);
        readfd = -1;
        return false;
    }

    if (!_device_read_buffer->Setup(vdevice.constData(), readfd))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to setup DRB buffer");
        _error = "Failed to setup DRB buffer";
        close(chanfd);
        chanfd = -1;
        close(readfd);
        readfd = -1;
        return false;
    }

    LOG(VB_RECORD, LOG_INFO, LOC + "DRB ready");

    if (vbi_fd >= 0)
        vbi_thread = new VBIThread(this);

    return true;
}
Пример #18
0
QStringList QWebOSFontDatabase::addTTFile(QWebOSFontDatabase* qwfdb, const QByteArray &fontData, const QByteArray &file, const QStringList &additionalFamilies)
{
    if (qwfdb && qwfdb->m_debug)
        qDebug("addTTFile(fontData.size() = %d, file = '%s', additionalFamilies = '%s')",
               fontData.size(),
               qPrintable(file),
               qPrintable(additionalFamilies.join(",")));
    extern FT_Library qt_getFreetype();
    FT_Library library = qt_getFreetype();

    int numFaces = 0;
    int index = 0;
    QStringList families;

    FT_Face face;
    FT_Error error;
    if (!fontData.isEmpty()) {
        error = FT_New_Memory_Face(library, (const FT_Byte *)fontData.constData(), fontData.size(), index, &face);
    } else {
        error = FT_New_Face(library, file.constData(), index, &face);
    }
    if (error != FT_Err_Ok) {
        qDebug() << "FT_New_Face for " << qPrintable(file) << " failed with index" << index << ":" << hex << error;
        return families;
    }

    numFaces = face->num_faces;
    if (numFaces > 1) {
        qWarning() << "numFaces for " << qPrintable(file) << " is " << numFaces << ", expected just 1";
    }

    QFont::Weight weight = QFont::Normal;
    QFont::Stretch stretch = QFont::Unstretched;
    QFont::Style style = QFont::StyleNormal;

    if (face->style_flags & FT_STYLE_FLAG_ITALIC)
        style = QFont::StyleItalic;

    if (face->style_flags & FT_STYLE_FLAG_BOLD)
        weight = QFont::Bold;

    QSupportedWritingSystems writingSystems;
    // detect symbol fonts
    for (int i = 0; i < face->num_charmaps; ++i) {
        FT_CharMap cm = face->charmaps[i];
        if (cm->encoding == ft_encoding_adobe_custom
            || cm->encoding == ft_encoding_symbol) {
            writingSystems.setSupported(QFontDatabase::Symbol);
            break;
        }
    }

    TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(face, ft_sfnt_os2);
    if (os2) {
        quint32 unicodeRange[4] = {
            os2->ulUnicodeRange1, os2->ulUnicodeRange2, os2->ulUnicodeRange3, os2->ulUnicodeRange4
        };
        quint32 codePageRange[2] = {
            os2->ulCodePageRange1, os2->ulCodePageRange2
        };

        writingSystems = determineWritingSystemsFromTrueTypeBits(unicodeRange, codePageRange);
        // If the OS2 struct is availabel read the weight from there and convert it
        // to a QFont::Weight. This fixes OWEBOS-1866
        weight = weightFromInteger(os2->usWeightClass);
        stretch = determineStretchFromTrueTypeWidthClass(os2->usWidthClass);
        style = determineStyleFromTrueTypeSelection(os2->fsSelection);
    }

    QString family = QString::fromAscii(face->family_name);

    QStringList allFamilies(family);
    allFamilies << additionalFamilies;

    for (int i = 0; i < allFamilies.size(); ++i) {
        FontFile *fontFile = new FontFile;
        fontFile->fileName = file;
        fontFile->indexValue = index;
        fontFile->familyName = allFamilies.at(i);
        qDebug("registerFont(\"%s\",\"\",%s,%s,%s,true,true,0,\"%s\",fontFile = {fileName = \"%s\", indexValue = %d, familyName = %s})",
               qPrintable(allFamilies.at(i)),
               qPrintable(qWeightToQString(weight)),
               qPrintable(qStyleToQString(style)),
               qPrintable(qStretchToQString(stretch)),
               qPrintable(qSupportedWritingSystemsToQString(writingSystems)),
               qPrintable(fontFile->fileName),
               fontFile->indexValue,
               qPrintable(fontFile->familyName));

        registerFont(allFamilies.at(i), "", weight, style, stretch, true, true, 0, writingSystems, fontFile);
        families.append(family);
    }

    FT_Done_Face(face);

    return families;
}
Пример #19
0
static void
rtty_done()
{
  if (rtty_inited)
    write_history(rtty_history.constData());
}
Пример #20
0
void ShaderParamsDialog::onShaderAddPassClicked()
{
   QString path;
   QString filter;
   QByteArray pathArray;
   struct video_shader *menu_shader = NULL;
   struct video_shader *video_shader = NULL;
   struct video_shader_pass *shader_pass = NULL;
   const char *pathData = NULL;
   settings_t *settings = config_get_ptr();
   bool is_preset = false;

   if (!settings)
      return;

   getShaders(&menu_shader, &video_shader);

   if (!menu_shader)
      return;

   filter = "Shader (";

   /* NOTE: Maybe we should have a way to get a list of all shader types instead of hard-coding this? */
   if (video_shader_is_supported(RARCH_SHADER_CG) &&
         video_shader_get_type_from_ext(".cg", &is_preset)
         != RARCH_SHADER_NONE)
      filter += QLatin1Literal("*.cg");

   if (video_shader_is_supported(RARCH_SHADER_GLSL) &&
         video_shader_get_type_from_ext(".glsl", &is_preset)
         != RARCH_SHADER_NONE)
      filter += QLatin1Literal(" *.glsl");

   if (video_shader_is_supported(RARCH_SHADER_SLANG) &&
         video_shader_get_type_from_ext(".slang", &is_preset)
         != RARCH_SHADER_NONE)
      filter += QLatin1Literal(" *.slang");

   filter += ")";

   path = QFileDialog::getOpenFileName(this, msg_hash_to_str(MENU_ENUM_LABEL_VALUE_VIDEO_SHADER_PRESET), settings->paths.directory_video_shader, filter);

   if (path.isEmpty())
      return;

   pathArray = path.toUtf8();
   pathData = pathArray.constData();

   if (menu_shader->passes < GFX_MAX_SHADERS)
      menu_shader_manager_increment_amount_passes();
   else
      return;

   shader_pass = &menu_shader->pass[menu_shader->passes - 1];

   if (!shader_pass)
      return;

   strlcpy(shader_pass->source.path, pathData, sizeof(shader_pass->source.path));

   video_shader_resolve_parameters(NULL, menu_shader);

   command_event(CMD_EVENT_SHADERS_APPLY_CHANGES, NULL);
}
Пример #21
0
void audioInit() {
	if (audioDevice) return;

	audioDevice = alcOpenDevice(NULL);
	if (!audioDevice) {
		LOG(("Audio Error: default sound device not present."));
		return;
	}
	
	ALCint attributes[] = { ALC_STEREO_SOURCES, 8, 0 };
	audioContext = alcCreateContext(audioDevice, attributes);
	alcMakeContextCurrent(audioContext);
	if (!_checkALCError()) return audioFinish();

	ALfloat v[] = { 0.f, 0.f, -1.f, 0.f, 1.f, 0.f };
	alListener3f(AL_POSITION, 0.f, 0.f, 0.f);
	alListener3f(AL_VELOCITY, 0.f, 0.f, 0.f);
	alListenerfv(AL_ORIENTATION, v);

	alDistanceModel(AL_NONE);

	alGenSources(1, &notifySource);
	alSourcef(notifySource, AL_PITCH, 1.f);
	alSourcef(notifySource, AL_GAIN, 1.f);
	alSource3f(notifySource, AL_POSITION, 0, 0, 0);
	alSource3f(notifySource, AL_VELOCITY, 0, 0, 0);
	alSourcei(notifySource, AL_LOOPING, 0);

	alGenBuffers(1, &notifyBuffer);
	if (!_checkALError()) return audioFinish();

	QFile notify(st::newMsgSound);
	if (!notify.open(QIODevice::ReadOnly)) return audioFinish();

	QByteArray blob = notify.readAll();
	const char *data = blob.constData();
	if (blob.size() < 44) return audioFinish();

	if (*((const uint32*)(data + 0)) != 0x46464952) return audioFinish(); // ChunkID - "RIFF"
	if (*((const uint32*)(data + 4)) != uint32(blob.size() - 8)) return audioFinish(); // ChunkSize
	if (*((const uint32*)(data + 8)) != 0x45564157) return audioFinish(); // Format - "WAVE"
	if (*((const uint32*)(data + 12)) != 0x20746d66) return audioFinish(); // Subchunk1ID - "fmt "
	uint32 subchunk1Size = *((const uint32*)(data + 16)), extra = subchunk1Size - 16;
	if (subchunk1Size < 16 || (extra && extra < 2)) return audioFinish();
	if (*((const uint16*)(data + 20)) != 1) return audioFinish(); // AudioFormat - PCM (1)

	uint16 numChannels = *((const uint16*)(data + 22));
	if (numChannels != 1 && numChannels != 2) return audioFinish();

	uint32 sampleRate = *((const uint32*)(data + 24));
	uint32 byteRate = *((const uint32*)(data + 28));

	uint16 blockAlign = *((const uint16*)(data + 32));
	uint16 bitsPerSample = *((const uint16*)(data + 34));
	if (bitsPerSample % 8) return audioFinish();
	uint16 bytesPerSample = bitsPerSample / 8;
	if (bytesPerSample != 1 && bytesPerSample != 2) return audioFinish();

	if (blockAlign != numChannels * bytesPerSample) return audioFinish();
	if (byteRate != sampleRate * blockAlign) return audioFinish();

	if (extra) {
		uint16 extraSize = *((const uint16*)(data + 36));
        if (uint32(extraSize + 2) != extra) return audioFinish();
		if (uint32(blob.size()) < 44 + extra) return audioFinish();
	}

	if (*((const uint32*)(data + extra + 36)) != 0x61746164) return audioFinish(); // Subchunk2ID - "data"
	uint32 subchunk2Size = *((const uint32*)(data + extra + 40));
	if (subchunk2Size % (numChannels * bytesPerSample)) return audioFinish();
	uint32 numSamples = subchunk2Size / (numChannels * bytesPerSample);

	if (uint32(blob.size()) < 44 + extra + subchunk2Size) return audioFinish();
	data += 44 + extra;

	ALenum format = 0;
	switch (bytesPerSample) {
	case 1:
		switch (numChannels) {
		case 1: format = AL_FORMAT_MONO8; break;
		case 2: format = AL_FORMAT_STEREO8; break;
		}
	break;

	case 2:
		switch (numChannels) {
		case 1: format = AL_FORMAT_MONO16; break;
		case 2: format = AL_FORMAT_STEREO16; break;
		}
	break;
	}
	if (!format) return audioFinish();

	alBufferData(notifyBuffer, format, data, subchunk2Size, sampleRate);
	alSourcei(notifySource, AL_BUFFER, notifyBuffer);
	if (!_checkALError()) return audioFinish();

	voicemsgs = new VoiceMessages();
}
Пример #22
0
void AVEncoderPrivate::applyOptionsForDict()
{
    if (dict) {
        av_dict_free(&dict);
        dict = 0; //aready 0 in av_free
    }
    if (options.isEmpty())
        return;
    // TODO: use QVariantMap only
    QVariant opt;
    if (options.contains("avcodec"))
        opt = options.value("avcodec");
    if (opt.type() == QVariant::Hash) {
        QVariantHash avcodec_dict = opt.toHash();
        // workaround for AVEncoder. now it does not call av_opt_set_xxx, so set here in dict
        // TODO: wrong if opt is empty
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toHash());
        QHashIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Hash: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::Int: {
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_dict_set(&dict, key.constData(), QByteArray::number(i.value().toInt()).constData(), 0);
            }
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong: {
                av_dict_set(&dict, key.constData(), QByteArray::number(i.value().toLongLong()).constData(), 0);
            }
                break;
            default:
                // avcodec key and value are in lower case
                av_dict_set(&dict, i.key().toLower().toUtf8().constData(), i.value().toByteArray().toLower().constData(), 0);
                break;
            }
            qDebug("avcodec dict: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    } else if (opt.type() == QVariant::Map) {
        QVariantMap avcodec_dict = opt.toMap();
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toMap());
        QMapIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Map: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::UInt:
            case QVariant::Int: {
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_dict_set(&dict, key.constData(), QByteArray::number(i.value().toInt()), 0);
            }
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong: {
                av_dict_set(&dict, key.constData(), QByteArray::number(i.value().toLongLong()).constData(), 0);
            }
                break;
            default:
                // avcodec key and value are in lower case
                av_dict_set(&dict, i.key().toLower().toUtf8().constData(), i.value().toByteArray().toLower().constData(), 0);
                break;
            }
            qDebug("avcodec dict: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    }
}
void Lib_initializer::load_action_plugins()
{
    SmartPtr<Named_interface> ni = Root::instance()->interface(actions_manager);
    Manager* mng = dynamic_cast<Manager*> (ni.raw_ptr());
    appli_assert( mng );

    std::string action_plugin_path(mng->plugin_path());
    QString path(action_plugin_path.c_str());

    // Loop on all the library files (.so or .dll) in directory "path"
    QDir dir(path);
    QStringList filters;
    filters << "*.so" << "*.dll";
    dir.setNameFilters(filters);
    dir.setFilter(QDir::Files);
    const QFileInfoList list = dir.entryInfoList();

    if (list.empty())
    {
        //		GsTLlog << "No action plugin could be found.\n" << "Check that environment variable GSTLAPPLIHOME is set to " << "where SGeMS was installed\n"
        //				<< "or that directory plugins/actions actually contains plugins\n" << gstlIO::end;
        return;
    }

    QFileInfoList::const_iterator it = list.begin();
    const QFileInfo* f_info;

    for (; it != list.end(); ++it)
    {
        f_info = &(*it);
        // QLibrary wants the absolute path
        QString abs_path(path + "/" + f_info->fileName());
        QByteArray tmp = abs_path.toAscii();
        GsTLlog << "Trying to load plug-in: " << tmp.constData() << "...\n";
        QLibrary lib(abs_path);
        //lib.setAutoUnload( false );
        lib.load();
        if (!lib.isLoaded())
        {
            GsTLlog << "The plug-in was not loaded: QLibrary::load failed. Aborting \n\n";
            continue;
        }

        typedef int (*Init_func_prototype)(void);

        //// The function must be called [filename]_init()
        //QString init_func_name( f_info->baseName() + "_init" );

        // The function must be called plugin_init()
        QString init_func_name = "plugin_init";
        QByteArray tmp1 = init_func_name.toLatin1();
        Init_func_prototype init_func = (Init_func_prototype) lib.resolve(tmp1.constData());

        if (init_func)
        {
            init_func();
            GsTLlog << "... OK\n\n";
        } else
        {
            QByteArray n = init_func_name.toAscii();
            GsTLlog << "unable to resolve symbol " << n.constData() << "\n\n";
        }
    }

    Root::instance()->list_all(GsTLlog);
}
Пример #24
0
void AVEncoderPrivate::applyOptionsForContext()
{
    if (!avctx)
        return;
    if (options.isEmpty()) {
        // av_opt_set_defaults(avctx); //can't set default values! result maybe unexpected
        return;
    }
    // TODO: use QVariantMap only
    QVariant opt;
    if (options.contains("avcodec"))
        opt = options.value("avcodec");
    if (opt.type() == QVariant::Hash) {
        QVariantHash avcodec_dict = opt.toHash();
        // workaround for AVEncoder. now it does not call av_opt_set_xxx, so set here in dict
        // TODO: wrong if opt is empty
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toHash());
        QHashIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Hash: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::Int:
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_opt_set_int(avctx, key.constData(), i.value().toInt(), 0);
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong:
                av_opt_set_int(avctx, key.constData(), i.value().toLongLong(), 0);
                break;
            default:
                break;
            }
            qDebug("avcodec option: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    } else if (opt.type() == QVariant::Map) {
        QVariantMap avcodec_dict = opt.toMap();
        // workaround for AVEncoder. now it does not call av_opt_set_xxx, so set here in dict
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toMap());
        QMapIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Map: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::UInt:
            case QVariant::Int:
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_opt_set_int(avctx, key.constData(), i.value().toInt(), 0);
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong:
                av_opt_set_int(avctx, key.constData(), i.value().toLongLong(), 0);
                break;
            default:
                break;
            }
            qDebug("avcodec option: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    }
}
Пример #25
0
qint64 PacketList::writeString(const QString& string) {
    QByteArray data = string.toUtf8();
    writePrimitive(static_cast<uint32_t>(data.length()));
    return writeData(data.constData(), data.length());
}
Пример #26
0
int PtyProcess::waitForChild()
{
    fd_set fds;
    FD_ZERO(&fds);
    QByteArray remainder;

    while (1)
    {
        FD_SET(fd(), &fds);

        // specify timeout to make sure select() does not block, even if the
        // process is dead / non-responsive. It does not matter if we abort too
        // early. In that case 0 is returned, and we'll try again in the next
        // iteration. (As long as we don't consitently time out in each iteration)
        timeval timeout;
        timeout.tv_sec = 0;
        timeout.tv_usec = 100000;
        int ret = select(fd()+1, &fds, 0L, 0L, &timeout);
        if (ret == -1)
        {
            if (errno != EINTR)
            {
                kError(kdesuDebugArea()) << k_lineinfo << "select():" << perror;
                return -1;
            }
            ret = 0;
        }

        if (ret)
        {
            forever {
                QByteArray output = readAll(false);
                if (output.isEmpty())
                    break;
                if (m_bTerminal)
                {
                    fwrite(output.constData(), output.size(), 1, stdout);
                    fflush(stdout);
                }
                if (!m_Exit.isEmpty())
                {
                    // match exit string only at line starts
                    remainder += output;
                    while (remainder.length() >= m_Exit.length()) {
                        if (remainder.startsWith(m_Exit)) {
                            kill(m_Pid, SIGTERM);
                            remainder.remove(0, m_Exit.length());
                        }
                        int off = remainder.indexOf('\n');
                        if (off < 0)
                            break;
                        remainder.remove(0, off + 1);
                    }
                }
            }
        }

        ret = checkPidExited(m_Pid);
        if (ret == Error)
        {
            if (errno == ECHILD) return 0;
            else return 1;
        }
        else if (ret == Killed)
        {
            return 0;
        }
        else if (ret == NotExited)
        {
            // keep checking
        }
        else
        {
            return ret;
        }
    }
}
Пример #27
0
void XdgShellSurfaceUnstableV5::Private::setAppId(const QByteArray & appId)
{
    xdg_surface_set_app_id(xdgsurfacev5, appId.constData());
}
Пример #28
0
 StandardInputRecord::StandardInputRecord(const RecordHeader& header, const QByteArray& data)
 {
     Q_ASSERT(header.type() == RecordHeader::StandardInputRecord);
     m_streamData = QByteArray(data.constData(), header.contentLength());
 }
Пример #29
0
ReturnedValue Serialize::deserialize(const QByteArray &data, ExecutionEngine *engine)
{
    const char *stream = data.constData();
    return deserialize(stream, engine);
}
Пример #30
0
// Receive data slot.
void qmidinetJackMidiDevice::receive ( const QByteArray& data, int port )
{
	sendData((unsigned char *) data.constData(), data.length(), port);
}