void EntitySimulation::clearEntities() { QMutexLocker lock(&_mutex); _mortalEntities.clear(); _nextExpiry = quint64(-1); _entitiesToUpdate.clear(); _entitiesToSort.clear(); _simpleKinematicEntities.clear(); clearEntitiesInternal(); for (auto entity : _allEntities) { entity->setSimulated(false); entity->die(); } _allEntities.clear(); _entitiesToDelete.clear(); }
void K3b::IsoImager::slotMkisofsPrintSizeFinished() { if( m_canceled ) { emit canceled(); jobFinished( false ); return; } bool success = true; // if m_collectedMkisofsPrintSizeStdout is not empty we have a recent version of // mkisofs and parsing is very easy (s.o.) if( !m_collectedMkisofsPrintSizeStdout.isEmpty() ) { qDebug() << "(K3b::IsoImager) iso size: " << m_collectedMkisofsPrintSizeStdout; m_mkisofsPrintSizeResult = m_collectedMkisofsPrintSizeStdout.toInt( &success ); } else { // parse the stderr output // I hope parsing the last line is enough! int pos = m_collectedMkisofsPrintSizeStderr.lastIndexOf( "extents scheduled to be written" ); if( pos == -1 ) success = false; else m_mkisofsPrintSizeResult = m_collectedMkisofsPrintSizeStderr.mid( pos+33 ).toInt( &success ); } emit debuggingOutput( "K3b::IsoImager", QString("mkisofs print size result: %1 (%2 bytes)") .arg(m_mkisofsPrintSizeResult) .arg(quint64(m_mkisofsPrintSizeResult)*2048ULL) ); cleanup(); if( success ) { jobFinished( true ); } else { m_mkisofsPrintSizeResult = 0; qDebug() << "(K3b::IsoImager) Parsing mkisofs -print-size failed: " << m_collectedMkisofsPrintSizeStdout; emit infoMessage( i18n("Could not determine size of resulting image file."), MessageError ); jobFinished( false ); } }
void HybrisProximityAdaptor::processSample(const sensors_event_t& data) { ProximityData *d = buffer->nextSlot(); d->timestamp_ = quint64(data.timestamp * .0001); bool near = false; sensordLogD() << "Guhl: HybrisProximityAdaptor processSample absinfo.value=" << data.distance << ", maxRange=" << maxRange << "\n"; if (data.distance < maxRange) { sensordLogD() << "Guhl: HybrisProximityAdaptor processSample setting near=true.\n"; near = true; // near = false; } d->withinProximity_ = near; d->value_ = data.distance; buffer->commit(); buffer->wakeUpReaders(); }
bool getDiskSpace(const QString &anyPath, uint &totalMb, uint &freeMb) { #ifdef _WIN32 SetErrorMode(SEM_FAILCRITICALERRORS); ULARGE_INTEGER free,total; if (GetDiskFreeSpaceExA( QString(anyPath.left(2)+"\\").toUtf8().constData(), &free, &total, 0)) { quint64 MB = quint64(1024*1024); freeMb = (uint)(( free.QuadPart) / MB); totalMb = (uint)((total.QuadPart) / MB); SetErrorMode(0); return true; } #endif return false; }
QT_BEGIN_NAMESPACE // return quint64 to avoid sign-extension static quint64 getMicrosecondFromTick() { static TInt nanokernel_tick_period; if (!nanokernel_tick_period) HAL::Get(HAL::ENanoTickPeriod, nanokernel_tick_period); static quint32 highdword = 0; static quint32 lastval = 0; quint32 val = User::NTickCount(); if (val < lastval) ++highdword; lastval = val; return nanokernel_tick_period * (val | (quint64(highdword) << 32)); }
void Lua4RSNotify::notifyTurtleSearchResult (uint32_t search_id, const std::list<TurtleFileInfo>& files) { LuaEventList lel; foreach (const TurtleFileInfo& file, files) { struct LuaEvent *e = new LuaEvent(); e->eventId = L4R_FILE_SEARCHRESULT; e->timeStamp = QDateTime::currentDateTime(); e->dataParm->setValue("u64searchId", search_id); e->dataParm->setValue("strhash", QString::fromStdString(file.hash.toStdString())); e->dataParm->setValue("strname", QString::fromUtf8((file.name.c_str()))); e->dataParm->setValue("u64size", quint64(file.size)); lel.push_back(e); } L4R::L4RConfig->getCore()->processEvent(lel); }
QVariant CMessagingModel::data(const QModelIndex &index, int role) const { int section = index.column(); int messageIndex = index.row(); if (messageIndex >= rowCount()) { return QVariant(); } if ((role == Qt::DecorationRole) && (section == Message)) { if (m_messages.at(messageIndex).mediaData.isValid()) { return m_messages.at(messageIndex).mediaData; } return QVariant(); } if ((role != Qt::DisplayRole) && (role != Qt::EditRole)) { return QVariant(); } switch (section) { case Phone: return m_messages.at(messageIndex).phone; case Direction: return m_messages.at(messageIndex).outgoing ? tr("out") : tr("in"); case Timestamp: return QDateTime::fromMSecsSinceEpoch(quint64(m_messages.at(messageIndex).timestamp) * 1000); case MessageId: return m_messages.at(messageIndex).messageId; case Message: return m_messages.at(messageIndex).message; case Status: if (m_messages.at(messageIndex).outgoing) { return messageDeliveryStatusStr(m_messages.at(messageIndex).status); } else { return tr("Incoming"); } default: break; } return QVariant(); }
quint64 UtilObject::processTime() { static char buffer[BUFSIZ]; static const quint64 tick = sysconf(_SC_CLK_TCK); int pid, ppid, pgrp, session, tty_nr, tpgid; uint flags; unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime; char comm[256], state; const auto fd = open("/proc/self/stat", O_RDONLY); if (fd < 0) return 0; int len = ::read(fd, buffer, BUFSIZ); if (len > 0) { buffer[len] = '\0'; len = sscanf(buffer , "%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu" , &pid, comm, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid, &flags , &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime); } close(fd); return len > 0 ? quint64(utime + stime)*Q_UINT64_C(1000000)/tick : 0; }
QByteArray QWindowsContext::comErrorString(HRESULT hr) { switch (hr) { case S_OK: return QByteArrayLiteral("S_OK"); case S_FALSE: return QByteArrayLiteral("S_FALSE"); case E_UNEXPECTED: return QByteArrayLiteral("E_UNEXPECTED"); case CO_E_ALREADYINITIALIZED: return QByteArrayLiteral("CO_E_ALREADYINITIALIZED"); case CO_E_NOTINITIALIZED: return QByteArrayLiteral("CO_E_NOTINITIALIZED"); case RPC_E_CHANGED_MODE: return QByteArrayLiteral("RPC_E_CHANGED_MODE"); case OLE_E_WRONGCOMPOBJ: return QByteArrayLiteral("OLE_E_WRONGCOMPOBJ"); case CO_E_NOT_SUPPORTED: return QByteArrayLiteral("CO_E_NOT_SUPPORTED"); case E_NOTIMPL: return QByteArrayLiteral("E_NOTIMPL"); case E_INVALIDARG: return QByteArrayLiteral("E_INVALIDARG"); case E_NOINTERFACE: return QByteArrayLiteral("E_NOINTERFACE"); case E_POINTER: return QByteArrayLiteral("E_POINTER"); case E_HANDLE: return QByteArrayLiteral("E_HANDLE"); case E_ABORT: return QByteArrayLiteral("E_ABORT"); case E_FAIL: return QByteArrayLiteral("E_FAIL"); case RPC_E_WRONG_THREAD: return QByteArrayLiteral("RPC_E_WRONG_THREAD"); case RPC_E_THREAD_NOT_INIT: return QByteArrayLiteral("RPC_E_THREAD_NOT_INIT"); default: break; } return "Unknown error 0x" + QByteArray::number(quint64(hr), 16); }
unsigned Util::getRandomSeed() { /* Because std::random_device seems to be not random at all on MINGW 4.8, we use * the system time and an incrementing counter instead. */ static QAtomicInt counter; auto counterValue = unsigned(counter.fetchAndAddOrdered(1)); unsigned clockValue = quint64(QDateTime::currentMSecsSinceEpoch()) & 0xFFFFFFFFu; //qDebug() << "counterValue:" << counterValue << " clockValue:" << clockValue; auto result = counterValue ^ clockValue; qDebug() << "Util::getRandomSeed returning" << result; /* we want to avoid returning the same result twice by accident (if the clock * advance and the counter difference cancel out each other), so we sleep a * little bit */ QThread::msleep(8); return result; }
void MainWindow::itemMenu(QPoint pos) { QMenu* menu = new QMenu(this); auto selection = ui->tableView->selectionModel(); auto message = ui->tableView->message(selection->currentIndex().row()); if (message) { QList<PathRec> paths; auto text = message->originalMessage.toHtmlEscaped(); findPaths(text, paths); for (int i = 0; i < paths.size(); ++i) { menu->addAction(paths[i].path, this, "uurlClicked()"); } if (paths.size()) { menu->addSeparator(); } if (auto logModel = dynamic_cast<LogModel*>(ui->tableView->sourceModel())) { LogModel::Client client; if (logModel->clientFromMessage(*message, client)) { QFontMetrics metrics(menu->font()); auto path = metrics.elidedText(client.path(), Qt::ElideMiddle, 200); auto name = QString("Disconnect [%1] %2").arg(client.pid()).arg(path); auto action = new QAction(name, this); action->setProperty("socket", quint64(client.socket())); connect(action, &QAction::triggered, this, &MainWindow::disconnectClient); menu->addAction(action); menu->addSeparator(); } } } menu->addAction(ui->actionClear); menu->exec(ui->tableView->mapToGlobal(pos)); delete menu; }
// protected void EntitySimulation::expireMortalEntities(const quint64& now) { if (now > _nextExpiry) { // only search for expired entities if we expect to find one _nextExpiry = quint64(-1); QMutexLocker lock(&_mutex); SetOfEntities::iterator itemItr = _mortalEntities.begin(); while (itemItr != _mortalEntities.end()) { EntityItemPointer entity = *itemItr; quint64 expiry = entity->getExpiry(); if (expiry < now) { itemItr = _mortalEntities.erase(itemItr); entity->die(); prepareEntityForDelete(entity); } else { if (expiry < _nextExpiry) { // remeber the smallest _nextExpiry so we know when to start the next search _nextExpiry = expiry; } ++itemItr; } } } }
bool QNetworkAccessDebugPipeBackend::canReceive() { if (incomingPacketSize == 0) { // read the packet size if (quint64(socket.bytesAvailable()) >= sizeof incomingPacketSize) socket.read((char*)&incomingPacketSize, sizeof incomingPacketSize); else return false; } if (incomingPacketSize == 0) { QString msg = QObject::tr("Protocol error: packet of size 0 received"); error(QNetworkReply::ProtocolFailure, msg); finished(); socket.blockSignals(true); socket.abort(); socket.blockSignals(false); return false; } return socket.bytesAvailable() >= incomingPacketSize; }
// private void EntitySimulation::expireMortalEntities(const quint64& now) { if (now > _nextExpiry) { // only search for expired entities if we expect to find one _nextExpiry = quint64(-1); QSet<EntityItem*>::iterator itemItr = _mortalEntities.begin(); while (itemItr != _mortalEntities.end()) { EntityItem* entity = *itemItr; quint64 expiry = entity->getExpiry(); if (expiry < now) { _entitiesToDelete.insert(entity); itemItr = _mortalEntities.erase(itemItr); _updateableEntities.remove(entity); _entitiesToBeSorted.remove(entity); removeEntityInternal(entity); } else { if (expiry < _nextExpiry) { // remeber the smallest _nextExpiry so we know when to start the next search _nextExpiry = expiry; } ++itemItr; } } } }
QtlRange& QtlRange::scale(qint64 factor) { if (_first < 0 || factor <= 0) { _first = 0; _count = 0; } else if (_first > (RANGE_MAX - factor + 1) / factor) { // Complete overflow at end. _first = RANGE_MAX; _count = 0; } else { _first = _first * factor; const quint64 maxCount = quint64(RANGE_MAX - _first) + 1; if (_count > (maxCount - factor + 1) / factor) { // Partial overflow at end. _count = RANGE_MAX - _first + 1; } else { _count = _count * factor; } } return *this; }
QString CContactModel::contactStatusStr(const SContact &contact) const { switch (contact.status()) { case TelegramNamespace::ContactStatusOnline: return tr("Online"); case TelegramNamespace::ContactStatusOffline: if (contact.wasOnline() > 0) { const QDateTime wasOnline = QDateTime::fromMSecsSinceEpoch(quint64(contact.wasOnline()) * 1000); const QDate currentDate = QDateTime::currentDateTime().date(); if (wasOnline.date().daysTo(currentDate) > 7) { return tr("Offline (since %1)").arg(wasOnline.toString(QLatin1String("yyyy.MM.dd"))); } else if (wasOnline.date() == currentDate) { return tr("Offline (since %1)").arg(wasOnline.toString(QLatin1String("HH:mm"))); } else { return tr("Offline (since %1)").arg(wasOnline.toString(QLatin1String("yyyy.MM.dd HH:mm"))); } } else { return tr("Offline"); } case TelegramNamespace::ContactStatusUnknown: default: return tr("Unknown"); } }
static void count(const QBitArray &data, quint8 bits, Count &most, Count &least) { Number index(0, bits); for (quint8 i=0; i<bits-1; i++) index << data.at(i); const quint64 size = quint64(1) << bits; quint8 *counts = new quint8[size]; memset(counts, 0, size); for (quint64 i=0; i<data.size()-bits; i++) { index << data.at(i + bits - 1); if (counts[index] < 255) counts[index]++; } most = Count(Number(), 0); least = Count(Number(), 255); for (quint64 i=0; i<size; i++) { if (counts[i] > most.count) most = Count(Number(i, bits), counts[i]); if (counts[i] < least.count) least = Count(Number(i, bits), counts[i]); } delete[] counts; }
QColor get_average_color(QImage src){ if (src.depth() < 32) src = src.convertToFormat(QImage::Format_ARGB32); quint64 avg[3] = {0}; unsigned pixel_count=0; for (auto y = src.height() * 0; y < src.height(); y++){ const uchar *p = src.constScanLine(y); for (auto x = src.width() * 0; x < src.width(); x++){ avg[0] += quint64(p[2]) * quint64(p[3]) / 255; avg[1] += quint64(p[1]) * quint64(p[3]) / 255; avg[2] += quint64(p[0]) * quint64(p[3]) / 255; p += 4; pixel_count++; } } for (int a = 0; a < 3; a++) avg[a] /= pixel_count; return QColor(avg[0], avg[1], avg[2]); }
uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size, QFile::MemoryMapFlags flags) { Q_Q(QFSFileEngine); Q_UNUSED(flags); if (openMode == QIODevice::NotOpen) { q->setError(QFile::PermissionsError, qt_error_string(int(EACCES))); return 0; } if (offset < 0 || offset != qint64(QT_OFF_T(offset)) || size < 0 || quint64(size) > quint64(size_t(-1))) { q->setError(QFile::UnspecifiedError, qt_error_string(int(EINVAL))); return 0; } // If we know the mapping will extend beyond EOF, fail early to avoid // undefined behavior. Otherwise, let mmap have its say. if (doStat(QFileSystemMetaData::SizeAttribute) && (QT_OFF_T(size) > metaData.size() - QT_OFF_T(offset))) qWarning("QFSFileEngine::map: Mapping a file beyond its size is not portable"); int access = 0; if (openMode & QIODevice::ReadOnly) access |= PROT_READ; if (openMode & QIODevice::WriteOnly) access |= PROT_WRITE; #if defined(Q_OS_INTEGRITY) int pageSize = sysconf(_SC_PAGESIZE); #else int pageSize = getpagesize(); #endif int extra = offset % pageSize; if (quint64(size + extra) > quint64((size_t)-1)) { q->setError(QFile::UnspecifiedError, qt_error_string(int(EINVAL))); return 0; } size_t realSize = (size_t)size + extra; QT_OFF_T realOffset = QT_OFF_T(offset); realOffset &= ~(QT_OFF_T(pageSize - 1)); #ifdef QT_SYMBIAN_USE_NATIVE_FILEMAP TInt nativeMapError = KErrNone; RFileMap mapping; TUint mode(EFileMapRemovableMedia); TUint64 nativeOffset = offset & ~(mapping.PageSizeInBytes() - 1); //If the file was opened for write or read/write, then open the map for read/write if (openMode & QIODevice::WriteOnly) mode |= EFileMapWrite; if (symbianFile.SubSessionHandle()) { nativeMapError = mapping.Open(symbianFile, nativeOffset, size, mode); } else { //map file by name if we don't have a native handle QString fn = QFileSystemEngine::absoluteName(fileEntry).nativeFilePath(); TUint filemode = EFileShareReadersOrWriters | EFileRead; if (openMode & QIODevice::WriteOnly) filemode |= EFileWrite; nativeMapError = mapping.Open(qt_s60GetRFs(), qt_QString2TPtrC(fn), filemode, nativeOffset, size, mode); } if (nativeMapError == KErrNone) { QScopedResource<RFileMap> ptr(mapping); //will call Close if adding to mapping throws an exception uchar *address = mapping.Base() + (offset - nativeOffset); maps[address] = mapping; ptr.take(); return address; } QFile::FileError reportedError = QFile::UnspecifiedError; switch (nativeMapError) { case KErrAccessDenied: case KErrPermissionDenied: reportedError = QFile::PermissionsError; break; case KErrNoMemory: reportedError = QFile::ResourceError; break; } q->setError(reportedError, QSystemError(nativeMapError, QSystemError::NativeError).toString()); return 0; #else #ifdef Q_OS_SYMBIAN //older phones & emulator don't support native mapping, so need to keep the open C way around for those. void *mapAddress; TRAPD(err, mapAddress = QT_MMAP((void*)0, realSize, access, MAP_SHARED, getMapHandle(), realOffset)); if (err != KErrNone) { qWarning("OpenC bug: leave from mmap %d", err); mapAddress = MAP_FAILED; errno = EINVAL; } #else void *mapAddress = QT_MMAP((void*)0, realSize, access, MAP_SHARED, nativeHandle(), realOffset); #endif if (MAP_FAILED != mapAddress) { uchar *address = extra + static_cast<uchar*>(mapAddress); maps[address] = QPair<int,size_t>(extra, realSize); return address; } switch(errno) { case EBADF: q->setError(QFile::PermissionsError, qt_error_string(int(EACCES))); break; case ENFILE: case ENOMEM: q->setError(QFile::ResourceError, qt_error_string(int(errno))); break; case EINVAL: // size are out of bounds default: q->setError(QFile::UnspecifiedError, qt_error_string(int(errno))); break; } return 0; #endif }
/*! \internal */ QWebSocketFrame QWebSocketFrame::readFrame(QIODevice *pIoDevice) { bool isDone = false; qint64 bytesRead = 0; QWebSocketFrame frame; quint64 dataWaitSize = 0; Q_UNUSED(dataWaitSize); // value is used in MACRO, Q_UNUSED to avoid compiler warnings ProcessingState processingState = PS_READ_HEADER; ProcessingState returnState = PS_READ_HEADER; bool hasMask = false; quint64 payloadLength = 0; while (!isDone) { switch (processingState) { case PS_WAIT_FOR_MORE_DATA: //TODO: waitForReadyRead should really be changed //now, when a websocket is used in a GUI thread //the GUI will hang for at most 5 seconds //maybe, a QStateMachine should be used if (!pIoDevice->waitForReadyRead(5000)) { frame.setError(QWebSocketProtocol::CC_GOING_AWAY, QObject::tr("Timeout when reading data from socket.")); processingState = PS_DISPATCH_RESULT; } else { processingState = returnState; } break; case PS_READ_HEADER: if (Q_LIKELY(pIoDevice->bytesAvailable() >= 2)) { //FIN, RSV1-3, Opcode char header[2] = {0}; bytesRead = pIoDevice->read(header, 2); frame.m_isFinalFrame = (header[0] & 0x80) != 0; frame.m_rsv1 = (header[0] & 0x40); frame.m_rsv2 = (header[0] & 0x20); frame.m_rsv3 = (header[0] & 0x10); frame.m_opCode = static_cast<QWebSocketProtocol::OpCode>(header[0] & 0x0F); //Mask, PayloadLength hasMask = (header[1] & 0x80) != 0; frame.m_length = (header[1] & 0x7F); switch (frame.m_length) { case 126: { processingState = PS_READ_PAYLOAD_LENGTH; break; } case 127: { processingState = PS_READ_BIG_PAYLOAD_LENGTH; break; } default: { payloadLength = frame.m_length; processingState = hasMask ? PS_READ_MASK : PS_READ_PAYLOAD; break; } } if (!frame.checkValidity()) processingState = PS_DISPATCH_RESULT; } else { WAIT_FOR_MORE_DATA(2); } break; case PS_READ_PAYLOAD_LENGTH: if (Q_LIKELY(pIoDevice->bytesAvailable() >= 2)) { uchar length[2] = {0}; bytesRead = pIoDevice->read(reinterpret_cast<char *>(length), 2); if (Q_UNLIKELY(bytesRead == -1)) { frame.setError(QWebSocketProtocol::CC_GOING_AWAY, QObject::tr("Error occurred while reading from the network: %1") .arg(pIoDevice->errorString())); processingState = PS_DISPATCH_RESULT; } else { payloadLength = qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(length)); if (Q_UNLIKELY(payloadLength < 126)) { //see http://tools.ietf.org/html/rfc6455#page-28 paragraph 5.2 //"in all cases, the minimal number of bytes MUST be used to encode //the length, for example, the length of a 124-byte-long string //can't be encoded as the sequence 126, 0, 124" frame.setError(QWebSocketProtocol::CC_PROTOCOL_ERROR, QObject::tr("Lengths smaller than 126 " \ "must be expressed as one byte.")); processingState = PS_DISPATCH_RESULT; } else { processingState = hasMask ? PS_READ_MASK : PS_READ_PAYLOAD; } } } else { WAIT_FOR_MORE_DATA(2); } break; case PS_READ_BIG_PAYLOAD_LENGTH: if (Q_LIKELY(pIoDevice->bytesAvailable() >= 8)) { uchar length[8] = {0}; bytesRead = pIoDevice->read(reinterpret_cast<char *>(length), 8); if (Q_UNLIKELY(bytesRead < 8)) { frame.setError(QWebSocketProtocol::CC_ABNORMAL_DISCONNECTION, QObject::tr("Something went wrong during "\ "reading from the network.")); processingState = PS_DISPATCH_RESULT; } else { //Most significant bit must be set to 0 as //per http://tools.ietf.org/html/rfc6455#section-5.2 payloadLength = qFromBigEndian<quint64>(length); if (Q_UNLIKELY(payloadLength & (quint64(1) << 63))) { frame.setError(QWebSocketProtocol::CC_PROTOCOL_ERROR, QObject::tr("Highest bit of payload length is not 0.")); processingState = PS_DISPATCH_RESULT; } else if (Q_UNLIKELY(payloadLength <= 0xFFFFu)) { //see http://tools.ietf.org/html/rfc6455#page-28 paragraph 5.2 //"in all cases, the minimal number of bytes MUST be used to encode //the length, for example, the length of a 124-byte-long string //can't be encoded as the sequence 126, 0, 124" frame.setError(QWebSocketProtocol::CC_PROTOCOL_ERROR, QObject::tr("Lengths smaller than 65536 (2^16) " \ "must be expressed as 2 bytes.")); processingState = PS_DISPATCH_RESULT; } else { processingState = hasMask ? PS_READ_MASK : PS_READ_PAYLOAD; } } } else { WAIT_FOR_MORE_DATA(8); } break; case PS_READ_MASK: if (Q_LIKELY(pIoDevice->bytesAvailable() >= 4)) { bytesRead = pIoDevice->read(reinterpret_cast<char *>(&frame.m_mask), sizeof(frame.m_mask)); if (bytesRead == -1) { frame.setError(QWebSocketProtocol::CC_GOING_AWAY, QObject::tr("Error while reading from the network: %1.") .arg(pIoDevice->errorString())); processingState = PS_DISPATCH_RESULT; } else { frame.m_mask = qFromBigEndian(frame.m_mask); processingState = PS_READ_PAYLOAD; } } else { WAIT_FOR_MORE_DATA(4); } break; case PS_READ_PAYLOAD: if (!payloadLength) { processingState = PS_DISPATCH_RESULT; } else if (Q_UNLIKELY(payloadLength > MAX_FRAME_SIZE_IN_BYTES)) { frame.setError(QWebSocketProtocol::CC_TOO_MUCH_DATA, QObject::tr("Maximum framesize exceeded.")); processingState = PS_DISPATCH_RESULT; } else { quint64 bytesAvailable = quint64(pIoDevice->bytesAvailable()); if (bytesAvailable >= payloadLength) { frame.m_payload = pIoDevice->read(payloadLength); //payloadLength can be safely cast to an integer, //because MAX_FRAME_SIZE_IN_BYTES = MAX_INT if (Q_UNLIKELY(frame.m_payload.length() != int(payloadLength))) { //some error occurred; refer to the Qt documentation of QIODevice::read() frame.setError(QWebSocketProtocol::CC_ABNORMAL_DISCONNECTION, QObject::tr("Some serious error occurred " \ "while reading from the network.")); processingState = PS_DISPATCH_RESULT; } else { if (hasMask) QWebSocketProtocol::mask(&frame.m_payload, frame.m_mask); processingState = PS_DISPATCH_RESULT; } } else { //if payload is too big, then this will timeout WAIT_FOR_MORE_DATA(payloadLength); } } break; case PS_DISPATCH_RESULT: processingState = PS_READ_HEADER; isDone = true; break; default: //should not come here qWarning() << "DataProcessor::process: Found invalid state. This should not happen!"; frame.clear(); isDone = true; break; } //end switch } return frame; }
void PropagateUploadFileQNAM::startNextChunk() { if (_propagator->_abortRequested.fetchAndAddRelaxed(0)) return; if (! _jobs.isEmpty() && _currentChunk + _startChunk >= _chunkCount - 1) { // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that // https://github.com/owncloud/core/issues/11106 // We return now and when the _jobs are finished we will proceed with the last chunk // NOTE: Some other parts of the code such as slotUploadProgress also assume that the last chunk // is sent last. return; } quint64 fileSize = _item->_size; QMap<QByteArray, QByteArray> headers; headers["OC-Total-Length"] = QByteArray::number(fileSize); headers["OC-Async"] = "1"; headers["OC-Chunk-Size"]= QByteArray::number(quint64(chunkSize())); headers["Content-Type"] = "application/octet-stream"; headers["X-OC-Mtime"] = QByteArray::number(qint64(_item->_modtime)); if(_item->_file.contains(".sys.admin#recall#")) { // This is a file recall triggered by the admin. Note: the // recall list file created by the admin and downloaded by the // client (.sys.admin#recall#) also falls into this category // (albeit users are not supposed to mess up with it) // We use a special tag header so that the server may decide to store this file away in some admin stage area // And not directly in the user's area (which would trigger redownloads etc). headers["OC-Tag"] = ".sys.admin#recall#"; } if (!_item->_etag.isEmpty() && _item->_etag != "empty_etag" && _item->_instruction != CSYNC_INSTRUCTION_NEW // On new files never send a If-Match && _item->_instruction != CSYNC_INSTRUCTION_TYPE_CHANGE && !_deleteExisting ) { // We add quotes because the owncloud server always adds quotes around the etag, and // csync_owncloud.c's owncloud_file_id always strips the quotes. headers["If-Match"] = '"' + _item->_etag + '"'; } QString path = _item->_file; UploadDevice *device = new UploadDevice(&_propagator->_bandwidthManager); qint64 chunkStart = 0; qint64 currentChunkSize = fileSize; bool isFinalChunk = false; if (_chunkCount > 1) { int sendingChunk = (_currentChunk + _startChunk) % _chunkCount; // XOR with chunk size to make sure everything goes well if chunk size changes between runs uint transid = _transferId ^ chunkSize(); qDebug() << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid; path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk); headers["OC-Chunked"] = "1"; chunkStart = chunkSize() * quint64(sendingChunk); currentChunkSize = chunkSize(); if (sendingChunk == _chunkCount - 1) { // last chunk currentChunkSize = (fileSize % chunkSize()); if( currentChunkSize == 0 ) { // if the last chunk pretends to be 0, its actually the full chunk size. currentChunkSize = chunkSize(); } isFinalChunk = true; } } else { // if there's only one chunk, it's the final one isFinalChunk = true; } if (isFinalChunk && !_transmissionChecksumType.isEmpty()) { headers[checkSumHeaderC] = makeChecksumHeader( _transmissionChecksumType, _transmissionChecksum); } const QString fileName = _propagator->getFilePath(_item->_file); if (! device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) { qDebug() << "ERR: Could not prepare upload device: " << device->errorString(); // If the file is currently locked, we want to retry the sync // when it becomes available again. if (FileSystem::isFileLocked(fileName)) { emit _propagator->seenLockedFile(fileName); } // Soft error because this is likely caused by the user modifying his files while syncing abortWithError( SyncFileItem::SoftError, device->errorString() ); delete device; return; } // job takes ownership of device via a QScopedPointer. Job deletes itself when finishing PUTFileJob* job = new PUTFileJob(_propagator->account(), _propagator->_remoteFolder + path, device, headers, _currentChunk); _jobs.append(job); connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished())); connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64))); connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64))); connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*))); job->start(); _propagator->_activeJobList.append(this); _currentChunk++; bool parallelChunkUpload = true; QByteArray env = qgetenv("OWNCLOUD_PARALLEL_CHUNK"); if (!env.isEmpty()) { parallelChunkUpload = env != "false" && env != "0"; } else { int versionNum = _propagator->account()->serverVersionInt(); if (versionNum < 0x080003) { // Disable parallel chunk upload severs older than 8.0.3 to avoid too many // internal sever errors (#2743, #2938) parallelChunkUpload = false; } } if (_currentChunk + _startChunk >= _chunkCount - 1) { // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that // https://github.com/owncloud/core/issues/11106 parallelChunkUpload = false; } if (parallelChunkUpload && (_propagator->_activeJobList.count() < _propagator->maximumActiveJob()) && _currentChunk < _chunkCount ) { startNextChunk(); } if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) { emit ready(); } }
// Returns a "human readable" string representation of the MSG and the // information it points to QString decodeMSG(const MSG& msg) { const WPARAM wParam = msg.wParam; const LPARAM lParam = msg.lParam; QString wmmsg = QString::fromLatin1(findWMstr(msg.message)); // Unknown WM_, so use number if (wmmsg.isEmpty()) wmmsg = QString::fromLatin1("WM_(%1)").arg(msg.message); QString rawParameters; rawParameters.sprintf("hwnd(0x%p) ", (void *)msg.hwnd); // Custom WM_'s if (msg.message > WM_APP) wmmsg = QString::fromLatin1("WM_APP + %1").arg(msg.message - WM_APP); else if (msg.message > WM_USER) wmmsg = QString::fromLatin1("WM_USER + %1").arg(msg.message - WM_USER); QString parameters; switch (msg.message) { #ifdef WM_ACTIVATE case WM_ACTIVATE: { QString activation = valueCheck(wParam, FLAG_STRING(WA_ACTIVE, "Activate"), FLAG_STRING(WA_INACTIVE, "Deactivate"), FLAG_STRING(WA_CLICKACTIVE, "Activate by mouseclick"), FLAG_STRING()); parameters.sprintf("%s Hwnd (0x%p)", activation.toLatin1().data(), (void *)msg.hwnd); } break; #endif #ifdef WM_CAPTURECHANGED case WM_CAPTURECHANGED: parameters.sprintf("Hwnd gaining capture (0x%p)", (void *)lParam); break; #endif #ifdef WM_CREATE case WM_CREATE: { LPCREATESTRUCT lpcs = (LPCREATESTRUCT)lParam; QString styles = flagCheck(lpcs->style, FLGSTR(WS_BORDER), FLGSTR(WS_CAPTION), FLGSTR(WS_CHILD), FLGSTR(WS_CLIPCHILDREN), FLGSTR(WS_CLIPSIBLINGS), FLGSTR(WS_DISABLED), FLGSTR(WS_DLGFRAME), FLGSTR(WS_GROUP), FLGSTR(WS_HSCROLL), FLGSTR(WS_OVERLAPPED), #if defined(WS_OVERLAPPEDWINDOW) && (WS_OVERLAPPEDWINDOW != 0) FLGSTR(WS_OVERLAPPEDWINDOW), #endif #ifdef WS_ICONIC FLGSTR(WS_ICONIC), #endif FLGSTR(WS_MAXIMIZE), FLGSTR(WS_MAXIMIZEBOX), FLGSTR(WS_MINIMIZE), FLGSTR(WS_MINIMIZEBOX), FLGSTR(WS_OVERLAPPEDWINDOW), FLGSTR(WS_POPUP), #ifdef WS_POPUPWINDOW FLGSTR(WS_POPUPWINDOW), #endif FLGSTR(WS_SIZEBOX), FLGSTR(WS_SYSMENU), FLGSTR(WS_TABSTOP), FLGSTR(WS_THICKFRAME), #ifdef WS_TILED FLGSTR(WS_TILED), #endif #ifdef WS_TILEDWINDOW FLGSTR(WS_TILEDWINDOW), #endif FLGSTR(WS_VISIBLE), FLGSTR(WS_VSCROLL), FLAG_STRING()); QString exStyles = flagCheck(lpcs->dwExStyle, #ifdef WS_EX_ACCEPTFILES FLGSTR(WS_EX_ACCEPTFILES), #endif #ifdef WS_EX_APPWINDOW FLGSTR(WS_EX_APPWINDOW), #endif FLGSTR(WS_EX_CLIENTEDGE), FLGSTR(WS_EX_DLGMODALFRAME), #ifdef WS_EX_LEFT FLGSTR(WS_EX_LEFT), #endif FLGSTR(WS_EX_LEFTSCROLLBAR), #ifdef WS_EX_LTRREADING FLGSTR(WS_EX_LTRREADING), #endif #ifdef WS_EX_MDICHILD FLGSTR(WS_EX_MDICHILD), #endif #ifdef WS_EX_NOACTIVATE FLGSTR(WS_EX_NOACTIVATE), #endif #ifdef WS_EX_NOANIMATION FLGSTR(WS_EX_NOANIMATION), #endif FLGSTR(WS_EX_NOPARENTNOTIFY), FLGSTR(WS_EX_OVERLAPPEDWINDOW), #ifdef WS_EX_PALETTEWINDOW FLGSTR(WS_EX_PALETTEWINDOW), #endif #ifdef WS_EX_RIGHT FLGSTR(WS_EX_RIGHT), #endif #ifdef WS_EX_RIGHTSCROLLBAR FLGSTR(WS_EX_RIGHTSCROLLBAR), #endif #ifdef WS_EX_RTLREADING FLGSTR(WS_EX_RTLREADING), #endif FLGSTR(WS_EX_STATICEDGE), FLGSTR(WS_EX_TOOLWINDOW), FLGSTR(WS_EX_TOPMOST), #ifdef WS_EX_TRANSPARENT FLGSTR(WS_EX_TRANSPARENT), #endif FLGSTR(WS_EX_WINDOWEDGE), #ifdef WS_EX_CAPTIONOKBTN FLGSTR(WS_EX_CAPTIONOKBTN), #endif FLAG_STRING()); QString className; if (lpcs->lpszClass != 0) { if (HIWORD(lpcs->lpszClass) == 0) // Atom className = QString::number(LOWORD(lpcs->lpszClass), 16); else // String className = QString((QChar*)lpcs->lpszClass, (int)wcslen(reinterpret_cast<const wchar_t *>(lpcs->lpszClass))); } QString windowName; if (lpcs->lpszName != 0) windowName = QString((QChar*)lpcs->lpszName, (int)wcslen(reinterpret_cast<const wchar_t *>(lpcs->lpszName))); parameters.sprintf("x,y(%4d,%4d) w,h(%4d,%4d) className(%s) windowName(%s) parent(0x%p) style(%s) exStyle(%s)", lpcs->x, lpcs->y, lpcs->cx, lpcs->cy, className.toLatin1().data(), windowName.toLatin1().data(), (void *)lpcs->hwndParent, styles.toLatin1().data(), exStyles.toLatin1().data()); } break; #endif #ifdef WM_DESTROY case WM_DESTROY: parameters.sprintf("Destroy hwnd (0x%p)", (void *)msg.hwnd); break; #endif #ifdef WM_IME_NOTIFY case WM_IME_NOTIFY: { QString imnCommand = valueCheck(wParam, FLGSTR(IMN_CHANGECANDIDATE), FLGSTR(IMN_CLOSECANDIDATE), FLGSTR(IMN_CLOSESTATUSWINDOW), FLGSTR(IMN_GUIDELINE), FLGSTR(IMN_OPENCANDIDATE), FLGSTR(IMN_OPENSTATUSWINDOW), FLGSTR(IMN_SETCANDIDATEPOS), FLGSTR(IMN_SETCOMPOSITIONFONT), FLGSTR(IMN_SETCOMPOSITIONWINDOW), FLGSTR(IMN_SETCONVERSIONMODE), FLGSTR(IMN_SETOPENSTATUS), FLGSTR(IMN_SETSENTENCEMODE), FLGSTR(IMN_SETSTATUSWINDOWPOS), FLAG_STRING()); parameters.sprintf("Command(%s : 0x%p)", imnCommand.toLatin1().data(), (void *)lParam); } break; #endif #ifdef WM_IME_SETCONTEXT case WM_IME_SETCONTEXT: { bool fSet = (BOOL)wParam; DWORD fShow = (DWORD)lParam; QString showFlgs = flagCheck(fShow, #ifdef ISC_SHOWUICOMPOSITIONWINDOW FLGSTR(ISC_SHOWUICOMPOSITIONWINDOW), #endif #ifdef ISC_SHOWUIGUIDWINDOW FLGSTR(ISC_SHOWUIGUIDWINDOW), #endif #ifdef ISC_SHOWUISOFTKBD FLGSTR(ISC_SHOWUISOFTKBD), #endif FLGSTR(ISC_SHOWUICANDIDATEWINDOW), FLGSTR(ISC_SHOWUICANDIDATEWINDOW << 1), FLGSTR(ISC_SHOWUICANDIDATEWINDOW << 2), FLGSTR(ISC_SHOWUICANDIDATEWINDOW << 3), FLAG_STRING()); parameters.sprintf("Input context(%s) Show flags(%s)", (fSet? "Active" : "Inactive"), showFlgs.toLatin1().data()); } break; #endif #ifdef WM_KILLFOCUS case WM_KILLFOCUS: parameters.sprintf("Hwnd gaining keyboard focus (0x%p)", (void *)wParam); break; #endif #ifdef WM_CHAR case WM_CHAR: #endif #ifdef WM_IME_CHAR case WM_IME_CHAR: #endif #ifdef WM_KEYDOWN case WM_KEYDOWN: #endif #ifdef WM_KEYUP case WM_KEYUP: { int nVirtKey = (int)wParam; long lKeyData = (long)lParam; int repCount = (lKeyData & 0xffff); // Bit 0-15 int scanCode = (lKeyData & 0xf0000) >> 16; // Bit 16-23 bool contextCode = (lKeyData && 0x20000000); // Bit 29 bool prevState = (lKeyData && 0x40000000); // Bit 30 bool transState = (lKeyData && 0x80000000); // Bit 31 parameters.sprintf("Virual-key(0x%x) Scancode(%d) Rep(%d) Contextcode(%d), Prev state(%d), Trans state(%d)", nVirtKey, scanCode, repCount, contextCode, prevState, transState); } break; #endif #ifdef WM_INPUTLANGCHANGE case WM_INPUTLANGCHANGE: parameters = QLatin1String("Keyboard layout changed"); break; #endif // WM_INPUTLANGCHANGE #ifdef WM_NCACTIVATE case WM_NCACTIVATE: { parameters = (msg.wParam? QLatin1String("Active Titlebar") : QLatin1String("Inactive Titlebar")); } break; #endif #ifdef WM_MOUSEACTIVATE case WM_MOUSEACTIVATE: { QString mouseMsg = QString::fromLatin1(findWMstr(HIWORD(lParam))); parameters.sprintf("TLW(0x%p) HittestCode(0x%x) MouseMsg(%s)", (void *)wParam, LOWORD(lParam), mouseMsg.toLatin1().data()); } break; #endif #ifdef WM_MOUSELEAVE case WM_MOUSELEAVE: break; // wParam & lParam not used #endif #ifdef WM_MOUSEHOVER case WM_MOUSEHOVER: #endif #ifdef WM_MOUSEWHEEL case WM_MOUSEWHEEL: #endif #ifdef WM_MOUSEHWHEEL case WM_MOUSEHWHEEL: #endif #ifdef WM_LBUTTONDBLCLK case WM_LBUTTONDBLCLK: #endif #ifdef WM_LBUTTONDOWN case WM_LBUTTONDOWN: #endif #ifdef WM_LBUTTONUP case WM_LBUTTONUP: #endif #ifdef WM_MBUTTONDBLCLK case WM_MBUTTONDBLCLK: #endif #ifdef WM_MBUTTONDOWN case WM_MBUTTONDOWN: #endif #ifdef WM_MBUTTONUP case WM_MBUTTONUP: #endif #ifdef WM_RBUTTONDBLCLK case WM_RBUTTONDBLCLK: #endif #ifdef WM_RBUTTONDOWN case WM_RBUTTONDOWN: #endif #ifdef WM_RBUTTONUP case WM_RBUTTONUP: #endif #ifdef WM_MOUSEMOVE case WM_MOUSEMOVE: { QString vrtKeys = flagCheck(wParam, FLGSTR(MK_CONTROL), FLGSTR(MK_LBUTTON), FLGSTR(MK_MBUTTON), FLGSTR(MK_RBUTTON), FLGSTR(MK_SHIFT), #ifdef MK_XBUTTON1 FLGSTR(MK_XBUTTON1), #endif #ifdef MK_XBUTTON2 FLGSTR(MK_XBUTTON2), #endif FLAG_STRING()); parameters.sprintf("x,y(%4d,%4d) Virtual Keys(%s)", GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), vrtKeys.toLatin1().data()); } break; #endif #ifdef WM_MOVE case WM_MOVE: parameters.sprintf("x,y(%4d,%4d)", LOWORD(lParam), HIWORD(lParam)); break; #endif #if defined(WM_PAINT) && defined(WM_ERASEBKGND) case WM_ERASEBKGND: case WM_PAINT: parameters.sprintf("hdc(0x%p)", (void *)wParam); break; #endif #ifdef WM_QUERYNEWPALETTE case WM_QUERYNEWPALETTE: break; // lParam & wParam are unused #endif #ifdef WM_SETCURSOR case WM_SETCURSOR: { QString mouseMsg = QString::fromLatin1(findWMstr(HIWORD(lParam))); parameters.sprintf("HitTestCode(0x%x) MouseMsg(%s)", LOWORD(lParam), mouseMsg.toLatin1().data()); } break; #endif #ifdef WM_SETFOCUS case WM_SETFOCUS: parameters.sprintf("Lost Focus (0x%p)", (void *)wParam); break; #endif #ifdef WM_SETTEXT case WM_SETTEXT: parameters.sprintf("Set Text (%s)", QString((QChar*)lParam, (int)wcslen(reinterpret_cast<const wchar_t *>(lParam))).toLatin1().data()); //Unicode string break; #endif #ifdef WM_SIZE case WM_SIZE: { QString showMode = valueCheck(wParam, FLGSTR(SIZE_MAXHIDE), FLGSTR(SIZE_MAXIMIZED), FLGSTR(SIZE_MAXSHOW), FLGSTR(SIZE_MINIMIZED), FLGSTR(SIZE_RESTORED), FLAG_STRING()); parameters.sprintf("w,h(%4d,%4d) showmode(%s)", LOWORD(lParam), HIWORD(lParam), showMode.toLatin1().data()); } break; #endif #ifdef WM_WINDOWPOSCHANGED case WM_WINDOWPOSCHANGED: { LPWINDOWPOS winPos = (LPWINDOWPOS)lParam; if (!winPos) break; QString hwndAfter = valueCheck(quint64(winPos->hwndInsertAfter), FLAG_STRING((qptrdiff)HWND_BOTTOM, "HWND_BOTTOM"), FLAG_STRING((qptrdiff)HWND_NOTOPMOST, "HWND_NOTOPMOST"), FLAG_STRING((qptrdiff)HWND_TOP, "HWND_TOP"), FLAG_STRING((qptrdiff)HWND_TOPMOST, "HWND_TOPMOST"), FLAG_STRING()); if (hwndAfter.isEmpty()) hwndAfter = QString::number((quintptr)winPos->hwndInsertAfter, 16); QString flags = flagCheck(winPos->flags, FLGSTR(SWP_DRAWFRAME), FLGSTR(SWP_FRAMECHANGED), FLGSTR(SWP_HIDEWINDOW), FLGSTR(SWP_NOACTIVATE), #ifdef SWP_NOCOPYBITS FLGSTR(SWP_NOCOPYBITS), #endif FLGSTR(SWP_NOMOVE), FLGSTR(SWP_NOOWNERZORDER), FLGSTR(SWP_NOREDRAW), FLGSTR(SWP_NOREPOSITION), #ifdef SWP_NOSENDCHANGING FLGSTR(SWP_NOSENDCHANGING), #endif FLGSTR(SWP_NOSIZE), FLGSTR(SWP_NOZORDER), FLGSTR(SWP_SHOWWINDOW), FLAG_STRING()); parameters.sprintf("x,y(%4d,%4d) w,h(%4d,%4d) flags(%s) hwndAfter(%s)", winPos->x, winPos->y, winPos->cx, winPos->cy, flags.toLatin1().data(), hwndAfter.toLatin1().data()); } break; #endif default: parameters.sprintf("wParam(0x%p) lParam(0x%p)", (void *)wParam, (void *)lParam); break; } // Yes, we want to give the WM_ names 20 chars of space before showing the // decoded message, since some of the common messages are quite long, and // we don't want the decoded information to vary in output position QString message = QString::fromLatin1("%1: ").arg(wmmsg, 20); message += rawParameters; message += parameters; return message; }
void OnActive(Character* character, InteractiveElementType /*type*/) { // Seuelement une instance du script ou bien ? Du coup va poser des problèmes // si plusieurs joueurs en même temps ? Du coup gérer la création de nouvelles instances de scripts ? m_char = character; // Envoie comme quoi l'élémentId n'est plus "usable" (différence avec le paquet de spawn 200) WorldPacket data(SMSG_INTERACTIVE_ELEMENT_UPDATE); data << quint64(20114); // Instance ElementId data.StartBlock<quint16>(); { data << quint8(1); // BlockCount data << quint8(2); // blockId data << quint32(6); // offset data << quint8(2); // BlockId data << quint16(1); // ? data << quint8(1); // isVisible data << quint8(0); // isUsable data << quint8(0); // ? data << quint8(0); // ? data << quint8(0); // ? data << quint32(0); // ? } data.EndBlock<quint16>(); character->GetSession()->SendPacket(data); // Spawn Wapin WorldPacket data2(SMSG_UPDATE_OBJECT); data2 << quint8(0); data2 << quint8(1); data2 << quint8(1); data2 << qint64(-1706442045669898); data2.StartBlock<quint16>(); { data2 << quint8(7); // GUID data2 << qint64(-1706442045669898); // IDENTITY data2 << quint8(1); data2 << qint64(-1); // NAME data2 << quint16(0); // BREED data2 << quint16(2644); // POSITION data2 << qint32(0); // X data2 << qint32(-17); // Y data2 << qint16(0); // Z data2 << quint16(-1); // InstanceId data2 << quint8(3); // Direction // APPEARANCE data2 << quint8(1); // Show // PUBLIC_CHARACTERISTICS data2 << quint16(1); // Level data2 << quint16(0); // States size // FIGHT_PROPERTIES data2 << quint8(0); // hasProperties // FIGHT data2 << qint32(-1); // currentFightId data2 << quint8(0); // isKo data2 << quint8(0); // isDead data2 << quint8(0); // isSummoned data2 << quint8(0); // isFleeing data2 << qint8(-1); // obstacleId data2 << quint8(0); // hasSummon // EQUIPMENT_APPEARANCE data2 << quint8(0); // size // RUNNING_EFFECTS data2 << quint8(1); // hasInFightData data2 << quint16(1); // data size data2 << quint8(13); // data data2 << quint8(1); // hasOutFightData data2 << quint16(0); // size // CURRENT_MOVEMENT_PATH data2 << quint8(0); // hasCurrentPath // WORLD_PROPERTIES data2 << quint8(0); // hasProperties // GROUP data2 << quint64(79645873605204); // PartyId data2 << quint16(1); // Members size data2 << qint16(-1); // breedId data2 << qint16(-1); // Level // TEMPLATE data2 << quint16(0); // sightRadius data2 << quint16(0); // aggroRadius // COLLECT data2 << quint16(0); // OCCUPATION data2 << quint8(0); // XP data2 << quint64(0); // XP_CHARACTERISTICS data2 << quint16(0); data2 << quint16(0); //data2 << quint16(0); //data2 << quint32(0); // Pourquoi sniff size 110 et la on est déjà à 117 ?? } data2.EndBlock<quint16>(); character->GetSession()->SendPacket(data2); // Activation du script (mouvement de la fenêtre entre autre) // Root aussi le joueur ? WorldPacket data3(SMSG_SCENARIO_SCRIPT); data3 << quint8(0); // Event data3 << quint32(12603); // Function data3 << quint32(1611); // ScenarioId data3 << quint8(1); // Long size? data3 << qint64(-1706442045669898); // Param character->GetSession()->SendPacket(data3); // Spawn Kano WorldPacket data4(SMSG_UPDATE_OBJECT); data4 << quint8(0); data4 << quint8(1); data4 << quint8(1); data4 << qint64(-1706442045669878); data4.StartBlock<quint16>(); { data4 << quint8(7); // GUID data4 << qint64(-1706442045669878); // IDENTITY data4 << quint8(1); data4 << qint64(-1); // NAME data4 << quint16(0); // BREED data4 << quint16(2694); // POSITION data4 << qint32(0); // X data4 << qint32(-21); // Y data4 << qint16(3); // Z data4 << quint16(-1); // InstanceId data4 << quint8(3); // Direction // APPEARANCE data4 << quint8(1); // Show // PUBLIC_CHARACTERISTICS data4 << quint16(100); // Level data4 << quint16(0); // States size // FIGHT_PROPERTIES data4 << quint8(0); // hasProperties // FIGHT data4 << qint32(-1); // currentFightId data4 << quint8(0); // isKo data4 << quint8(0); // isDead data4 << quint8(0); // isSummoned data4 << quint8(0); // isFleeing data4 << qint8(-1); // obstacleId data4 << quint8(0); // hasSummon // EQUIPMENT_APPEARANCE data4 << quint8(0); // size // RUNNING_EFFECTS should be wrong data4 << quint8(1); // hasInFightData data4 << quint16(1); // data size data4 << quint8(13); // data data4 << quint8(1); // hasOutFightData data4 << quint16(0); // size // CURRENT_MOVEMENT_PATH data4 << quint8(0); // hasCurrentPath // WORLD_PROPERTIES data4 << quint8(0); // hasProperties // GROUP data4 << quint64(79645873605204); // PartyId data4 << quint16(1); // Members size data4 << qint16(-1); // breedId data4 << qint16(-1); // Level // TEMPLATE data4 << quint16(0); // sightRadius data4 << quint16(0); // aggroRadius // COLLECT data4 << quint16(0); // OCCUPATION data4 << quint8(0); // XP data4 << quint64(0); // XP_CHARACTERISTICS data4 << quint16(0); data4 << quint16(0); //data4 << quint16(0); //data4 << quint32(0); // Pourquoi sniff size 110 et la on est déjà à 117 ?? } data4.EndBlock<quint16>(); character->GetSession()->SendPacket(data4); // Texte : "Hé toi le nouveau" etc. WorldPacket data5(SMSG_SCENARIO_SCRIPT); data5 << quint8(0); // Event data5 << quint32(12687); // Function data5 << quint32(1611); // ScenarioId data5 << quint8(1); // Params size? data5 << qint64(-1706442045669878); // Param character->GetSession()->SendPacket(data5); // Flèche sur le wapin WorldPacket data6(SMSG_SCENARIO_SCRIPT); data6 << quint8(0); // Event data6 << quint32(12691); // Function data6 << quint32(1611); // ScenarioId data6 << quint8(1); // Long size? data6 << qint64(-1706442045669898); // Param character->GetSession()->SendPacket(data6); m_spawned = true; }
void WorldSession::SendUpdateObject() { Character* character = GetCharacter(); if (!character) return; WorldPacket data(SMSG_UPDATE_OBJECT); data << quint8(0); data << quint8(1); data << quint8(0); data << character->GetGuid(); data.StartBlock<quint16>(); { data << quint8(7); data << character->GetGuid(); data << quint8(0); data << GetAccountInfos().id; data.WriteString(character->GetName(), true); data << character->GetBreed(); data << character->GetPositionX(); data << character->GetPositionY(); data << character->GetPositionZ(); data << character->GetInstanceId(); data << character->GetDirection(); // *** Skin data << character->GetGender(); data << character->GetSkinColor(); data << character->GetHairColor(); data << character->GetPupilColor(); data << character->GetSkinColorFactor(); data << character->GetHairColorFactor(); data << character->GetClothIndex(); data << character->GetFaceIndex(); data << qint16(-1); // Titles // PUBLIC_CHARACTERISTICS data << quint16(0); // size // FIGHT_PROPERTIES data << quint8(0); // hasProperties // FIGHT data << qint32(-1); // currentFightId data << quint8(0); // isKo data << quint8(0); // isDead data << quint8(0); // isSummonned data << quint8(0); // isFleeing data << qint8(-1); // obstacleId data << quint8(0); // hasSummon // EQUIPMENT_APPEARANCE data << quint16(0); // Views size // RUNNING_EFFECTS data << quint8(0); // hasInFightData data << quint8(0); // hasOutFightData // CURRENT_MOVEMENT_PATH data << quint8(0); // hasCurrentPath // WORLD_PROPERTIES data << quint8(0); // hasProperties // GROUP data << quint64(0); // partyId // TEMPLATE data << quint16(0); // sightRadius data << quint16(0); // aggroRadius // COLLECT data << quint16(0); // unavailableActions size // OCCUPATION data << quint8(0); // hasOccupation // XP data << character->GetXP(); // XP_CHARACTERISTICS data << character->GetXPFreePoints(); data << quint16(0); // xpBonusPoints size data << quint16(0); // characteristicBonusPoints size data << character->GetXPGauge(); // Should be named WakfuGauge... // CITIZEN_POINT data << quint16(0); // nationCitizenScores data << quint16(0); // offendedNations // GUILD_REMOTE_INFO data << character->GetGuildId(); data << quint64(0); // Blazon data << quint16(0); // Level data << quint16(0); // GuildName // NATION_ID data << quint32(0); // NationId // NATION_SYNCHRO data << quint64(0); // rank data << quint64(0); // jobs data << quint64(0); // vote data << quint8(0); // governmentOpinion data << quint8(0); // isCandidate // SOCIAL_STATES data << quint8(0); // afkState data << quint8(0); // dndState // PET data << quint8(0); // hasPet // ACCOUNT_INFORMATION_REMOTE data << quint32(0); // subscriptionLevel data << quint16(0); // additionalRights size // COMPANION_CONTROLLER_ID data << quint64(0); // controllerId data << quint64(0); // companionId } data.EndBlock<quint16>(); SendPacket(data); }
int main(int argc, char *argv[]) { QString workDir; #ifdef Q_OS_MAC if (QDir(QString()).absolutePath() == "/") { QString first = argc ? QString::fromLocal8Bit(argv[0]) : QString(); if (!first.isEmpty()) { QFileInfo info(first); if (info.exists()) { QDir result(info.absolutePath() + "/../../.."); workDir = result.absolutePath() + '/'; } } } #endif QString remove; int version = 0; QFileInfoList files; for (int i = 0; i < argc; ++i) { if (string("-path") == argv[i] && i + 1 < argc) { QString path = workDir + QString(argv[i + 1]); QFileInfo info(path); files.push_back(info); if (remove.isEmpty()) remove = info.canonicalPath() + "/"; } else if (string("-version") == argv[i] && i + 1 < argc) { version = QString(argv[i + 1]).toInt(); } else if (string("-dev") == argv[i]) { DevChannel = true; } else if (string("-beta") == argv[i] && i + 1 < argc) { BetaVersion = QString(argv[i + 1]).toULongLong(); if (BetaVersion > version * 1000ULL && BetaVersion < (version + 1) * 1000ULL) { DevChannel = false; BetaSignature = countBetaVersionSignature(BetaVersion); if (BetaSignature.isEmpty()) { return -1; } } else { cout << "Bad -beta param value passed, should be for the same version: " << version << ", beta: " << BetaVersion << "\n"; return -1; } } } if (files.isEmpty() || remove.isEmpty() || version <= 1016 || version > 999999999) { #ifdef Q_OS_WIN cout << "Usage: Packer.exe -path {file} -version {version} OR Packer.exe -path {dir} -version {version}\n"; #elif defined Q_OS_MAC cout << "Usage: Packer.app -path {file} -version {version} OR Packer.app -path {dir} -version {version}\n"; #else cout << "Usage: Packer -path {file} -version {version} OR Packer -path {dir} -version {version}\n"; #endif return -1; } bool hasDirs = true; while (hasDirs) { hasDirs = false; for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { QFileInfo info(*i); QString fullPath = info.canonicalFilePath(); if (info.isDir()) { hasDirs = true; files.erase(i); QDir d = QDir(info.absoluteFilePath()); QString fullDir = d.canonicalPath(); QStringList entries = d.entryList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); files.append(d.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot)); break; } else if (!info.isReadable()) { cout << "Can't read: " << info.absoluteFilePath().toUtf8().constData() << "\n"; return -1; } else if (info.isHidden()) { hasDirs = true; files.erase(i); break; } } } for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { QFileInfo info(*i); if (!info.canonicalFilePath().startsWith(remove)) { cout << "Can't find '" << remove.toUtf8().constData() << "' in file '" << info.canonicalFilePath().toUtf8().constData() << "' :(\n"; return -1; } } QByteArray result; { QBuffer buffer(&result); buffer.open(QIODevice::WriteOnly); QDataStream stream(&buffer); stream.setVersion(QDataStream::Qt_5_1); if (BetaVersion) { stream << quint32(0x7FFFFFFF); stream << quint64(BetaVersion); } else { stream << quint32(version); } stream << quint32(files.size()); cout << "Found " << files.size() << " file" << (files.size() == 1 ? "" : "s") << "..\n"; for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { QFileInfo info(*i); QString fullName = info.canonicalFilePath(); QString name = fullName.mid(remove.length()); cout << name.toUtf8().constData() << " (" << info.size() << ")\n"; QFile f(fullName); if (!f.open(QIODevice::ReadOnly)) { cout << "Can't open '" << fullName.toUtf8().constData() << "' for read..\n"; return -1; } QByteArray inner = f.readAll(); stream << name << quint32(inner.size()) << inner; #if defined Q_OS_MAC || defined Q_OS_LINUX stream << (QFileInfo(fullName).isExecutable() ? true : false); #endif } if (stream.status() != QDataStream::Ok) { cout << "Stream status is bad: " << stream.status() << "\n"; return -1; } } int32 resultSize = result.size(); cout << "Compression start, size: " << resultSize << "\n"; QByteArray compressed, resultCheck; #ifdef Q_OS_WIN // use Lzma SDK for win const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size size_t compressedLen = compressed.size() - hSize; size_t outPropsSize = LZMA_PROPS_SIZE; uchar *_dest = (uchar*)(compressed.data() + hSize); size_t *_destLen = &compressedLen; const uchar *_src = (const uchar*)(result.constData()); size_t _srcLen = result.size(); uchar *_outProps = (uchar*)(compressed.data() + hSigLen + hShaLen); int res = LzmaCompress(_dest, _destLen, _src, _srcLen, _outProps, &outPropsSize, 9, 64 * 1024 * 1024, 4, 0, 2, 273, 2); if (res != SZ_OK) { cout << "Error in compression: " << res << "\n"; return -1; } compressed.resize(int(hSize + compressedLen)); memcpy(compressed.data() + hSigLen + hShaLen + hPropsLen, &resultSize, hOriginalSizeLen); cout << "Compressed to size: " << compressedLen << "\n"; cout << "Checking uncompressed..\n"; int32 resultCheckLen; memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen); if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) { cout << "Bad result len: " << resultCheckLen << "\n"; return -1; } resultCheck.resize(resultCheckLen); size_t resultLen = resultCheck.size(); SizeT srcLen = compressedLen; int uncompressRes = LzmaUncompress((uchar*)resultCheck.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE); if (uncompressRes != SZ_OK) { cout << "Uncompress failed: " << uncompressRes << "\n"; return -1; } if (resultLen != size_t(result.size())) { cout << "Uncompress bad size: " << resultLen << ", was: " << result.size() << "\n"; return -1; } #else // use liblzma for others const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size size_t compressedLen = compressed.size() - hSize; lzma_stream stream = LZMA_STREAM_INIT; int preset = 9 | LZMA_PRESET_EXTREME; lzma_ret ret = lzma_easy_encoder(&stream, preset, LZMA_CHECK_CRC64); if (ret != LZMA_OK) { const char *msg; switch (ret) { case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break; case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break; default: msg = "Unknown error, possibly a bug"; break; } cout << "Error initializing the encoder: " << msg << " (error code " << ret << ")\n"; return -1; } stream.avail_in = resultSize; stream.next_in = (uint8_t*)result.constData(); stream.avail_out = compressedLen; stream.next_out = (uint8_t*)(compressed.data() + hSize); lzma_ret res = lzma_code(&stream, LZMA_FINISH); compressedLen -= stream.avail_out; lzma_end(&stream); if (res != LZMA_OK && res != LZMA_STREAM_END) { const char *msg; switch (res) { case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; case LZMA_DATA_ERROR: msg = "File size limits exceeded"; break; default: msg = "Unknown error, possibly a bug"; break; } cout << "Error in compression: " << msg << " (error code " << res << ")\n"; return -1; } compressed.resize(int(hSize + compressedLen)); memcpy(compressed.data() + hSigLen + hShaLen, &resultSize, hOriginalSizeLen); cout << "Compressed to size: " << compressedLen << "\n"; cout << "Checking uncompressed..\n"; int32 resultCheckLen; memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen, hOriginalSizeLen); if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) { cout << "Bad result len: " << resultCheckLen << "\n"; return -1; } resultCheck.resize(resultCheckLen); size_t resultLen = resultCheck.size(); stream = LZMA_STREAM_INIT; ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED); if (ret != LZMA_OK) { const char *msg; switch (ret) { case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break; case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break; default: msg = "Unknown error, possibly a bug"; break; } cout << "Error initializing the decoder: " << msg << " (error code " << ret << ")\n"; return -1; } stream.avail_in = compressedLen; stream.next_in = (uint8_t*)(compressed.constData() + hSize); stream.avail_out = resultLen; stream.next_out = (uint8_t*)resultCheck.data(); res = lzma_code(&stream, LZMA_FINISH); if (stream.avail_in) { cout << "Error in decompression, " << stream.avail_in << " bytes left in _in of " << compressedLen << " whole.\n"; return -1; } else if (stream.avail_out) { cout << "Error in decompression, " << stream.avail_out << " bytes free left in _out of " << resultLen << " whole.\n"; return -1; } lzma_end(&stream); if (res != LZMA_OK && res != LZMA_STREAM_END) { const char *msg; switch (res) { case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break; case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break; case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break; case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break; default: msg = "Unknown error, possibly a bug"; break; } cout << "Error in decompression: " << msg << " (error code " << res << ")\n"; return -1; } #endif if (memcmp(result.constData(), resultCheck.constData(), resultLen)) { cout << "Data differ :(\n"; return -1; } /**/ result = resultCheck = QByteArray(); cout << "Counting SHA1 hash..\n"; uchar sha1Buffer[20]; memcpy(compressed.data() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, uint32(compressedLen + hPropsLen + hOriginalSizeLen), sha1Buffer), hShaLen); // count sha1 uint32 siglen = 0; cout << "Signing..\n"; RSA *prKey = PEM_read_bio_RSAPrivateKey(BIO_new_mem_buf(const_cast<char*>((DevChannel || BetaVersion) ? PrivateDevKey : PrivateKey), -1), 0, 0, 0); if (!prKey) { cout << "Could not read RSA private key!\n"; return -1; } if (RSA_size(prKey) != hSigLen) { cout << "Bad private key, size: " << RSA_size(prKey) << "\n"; RSA_free(prKey); return -1; } if (RSA_sign(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (uchar*)(compressed.data()), &siglen, prKey) != 1) { // count signature cout << "Signing failed!\n"; RSA_free(prKey); return -1; } RSA_free(prKey); if (siglen != hSigLen) { cout << "Bad signature length: " << siglen << "\n"; return -1; } cout << "Checking signature..\n"; RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>((DevChannel || BetaVersion) ? PublicDevKey : PublicKey), -1), 0, 0, 0); if (!pbKey) { cout << "Could not read RSA public key!\n"; return -1; } if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), siglen, pbKey) != 1) { // verify signature RSA_free(pbKey); cout << "Signature verification failed!\n"; return -1; } cout << "Signature verified!\n"; RSA_free(pbKey); #ifdef Q_OS_WIN QString outName(QString("tupdate%1").arg(BetaVersion ? BetaVersion : version)); #elif defined Q_OS_MAC QString outName(QString("tmacupd%1").arg(BetaVersion ? BetaVersion : version)); #elif defined Q_OS_LINUX32 QString outName(QString("tlinux32upd%1").arg(BetaVersion ? BetaVersion : version)); #elif defined Q_OS_LINUX64 QString outName(QString("tlinuxupd%1").arg(BetaVersion ? BetaVersion : version)); #else #error Unknown platform! #endif if (BetaVersion) { outName += "_" + BetaSignature; } QFile out(outName); if (!out.open(QIODevice::WriteOnly)) { cout << "Can't open '" << outName.toUtf8().constData() << "' for write..\n"; return -1; } out.write(compressed); out.close(); if (BetaVersion) { QString keyName(QString("tbeta_%1_key").arg(BetaVersion)); QFile key(keyName); if (!key.open(QIODevice::WriteOnly)) { cout << "Can't open '" << keyName.toUtf8().constData() << "' for write..\n"; return -1; } key.write(BetaSignature.toUtf8()); key.close(); } cout << "Update file '" << outName.toUtf8().constData() << "' written successfully!\n"; return 0; }
MP::operator quint64() const { return m and not p.size() ? m->operator quint64() : 0; }
void Canvas::genUserid() { userid_ = quint64(&userid_); // treat as ramdom number }
SoundSource::OpenResult SoundSourceMp3::tryOpen(const AudioSourceConfig& /*audioSrcCfg*/) { DEBUG_ASSERT(!hasValidChannelCount()); DEBUG_ASSERT(!hasValidSamplingRate()); DEBUG_ASSERT(!m_file.isOpen()); if (!m_file.open(QIODevice::ReadOnly)) { qWarning() << "Failed to open file:" << m_file.fileName(); return OpenResult::FAILED; } // Get a pointer to the file using memory mapped IO m_fileSize = m_file.size(); m_pFileData = m_file.map(0, m_fileSize); // NOTE(uklotzde): If the file disappears unexpectedly while mapped // a SIGBUS error might occur that is not handled and will terminate // Mixxx immediately. This behavior is documented in the manpage of // mmap(). It has already appeared due to hardware errors and is // described in the following bug report: // https://bugs.launchpad.net/mixxx/+bug/1452005 // Transfer it to the mad stream-buffer: mad_stream_options(&m_madStream, MAD_OPTION_IGNORECRC); mad_stream_buffer(&m_madStream, m_pFileData, m_fileSize); DEBUG_ASSERT(m_pFileData == m_madStream.this_frame); DEBUG_ASSERT(m_seekFrameList.empty()); m_avgSeekFrameCount = 0; m_curFrameIndex = getMinFrameIndex(); int headerPerSamplingRate[kSamplingRateCount]; for (int i = 0; i < kSamplingRateCount; ++i) { headerPerSamplingRate[i] = 0; } // Decode all the headers and calculate audio properties unsigned long sumBitrate = 0; mad_header madHeader; mad_header_init(&madHeader); SINT maxChannelCount = getChannelCount(); do { if (!decodeFrameHeader(&madHeader, &m_madStream, true)) { if (isStreamValid(m_madStream)) { // Skip frame continue; } else { // Abort decoding break; } } // Grab data from madHeader const unsigned int madSampleRate = madHeader.samplerate; // TODO(XXX): Replace DEBUG_ASSERT with static_assert // MAD must not change its enum values! DEBUG_ASSERT(MAD_UNITS_8000_HZ == 8000); const mad_units madUnits = static_cast<mad_units>(madSampleRate); const long madFrameLength = mad_timer_count(madHeader.duration, madUnits); if (0 >= madFrameLength) { qWarning() << "Skipping MP3 frame with invalid length" << madFrameLength << "in:" << m_file.fileName(); // Skip frame continue; } const SINT madChannelCount = MAD_NCHANNELS(&madHeader); if (isValidChannelCount(maxChannelCount) && (madChannelCount != maxChannelCount)) { qWarning() << "Differing number of channels" << madChannelCount << "<>" << maxChannelCount << "in some MP3 frame headers:" << m_file.fileName(); } maxChannelCount = math_max(madChannelCount, maxChannelCount); const int samplingRateIndex = getIndexBySamplingRate(madSampleRate); if (samplingRateIndex >= kSamplingRateCount) { qWarning() << "Invalid sample rate:" << m_file.fileName() << madSampleRate; // Abort mad_header_finish(&madHeader); return OpenResult::FAILED; } // Count valid frames separated by its sampling rate headerPerSamplingRate[samplingRateIndex]++; addSeekFrame(m_curFrameIndex, m_madStream.this_frame); // Accumulate data from the header sumBitrate += madHeader.bitrate; // Update current stream position m_curFrameIndex += madFrameLength; DEBUG_ASSERT(m_madStream.this_frame); DEBUG_ASSERT(0 <= (m_madStream.this_frame - m_pFileData)); } while (quint64(m_madStream.this_frame - m_pFileData) < m_fileSize); mad_header_finish(&madHeader); if (MAD_ERROR_NONE != m_madStream.error) { // Unreachable code for recoverable errors DEBUG_ASSERT(!MAD_RECOVERABLE(m_madStream.error)); if (MAD_ERROR_BUFLEN != m_madStream.error) { qWarning() << "Unrecoverable MP3 header error:" << mad_stream_errorstr(&m_madStream); // Abort return OpenResult::FAILED; } } if (m_seekFrameList.empty()) { // This is not a working MP3 file. qWarning() << "SSMP3: This is not a working MP3 file:" << m_file.fileName(); // Abort return OpenResult::FAILED; } int mostCommonSamplingRateIndex = kSamplingRateCount; // invalid int mostCommonSamplingRateCount = 0; int differentRates = 0; for (int i = 0; i < kSamplingRateCount; ++i) { // Find most common sampling rate if (mostCommonSamplingRateCount < headerPerSamplingRate[i]) { mostCommonSamplingRateCount = headerPerSamplingRate[i]; mostCommonSamplingRateIndex = i; differentRates++; } } if (differentRates > 1) { qWarning() << "Differing sampling rate in some headers:" << m_file.fileName(); for (int i = 0; i < kSamplingRateCount; ++i) { if (0 < headerPerSamplingRate[i]) { qWarning() << headerPerSamplingRate[i] << "MP3 headers with sampling rate" << getSamplingRateByIndex(i); } } qWarning() << "MP3 files with varying sample rate are not supported!"; qWarning() << "Since this happens most likely due to a corrupt file"; qWarning() << "Mixxx tries to plays it with the most common sample rate for this file"; } if (mostCommonSamplingRateIndex < kSamplingRateCount) { setSamplingRate(getSamplingRateByIndex(mostCommonSamplingRateIndex)); } else { qWarning() << "No single valid sampling rate in header"; // Abort return OpenResult::FAILED; } // Initialize the AudioSource setChannelCount(maxChannelCount); setFrameCount(m_curFrameIndex); // Calculate average values m_avgSeekFrameCount = getFrameCount() / m_seekFrameList.size(); const unsigned long avgBitrate = sumBitrate / m_seekFrameList.size(); setBitrate(avgBitrate / 1000); // Terminate m_seekFrameList addSeekFrame(m_curFrameIndex, 0); // Reset positions m_curFrameIndex = getMinFrameIndex(); // Restart decoding at the beginning of the audio stream m_curFrameIndex = restartDecoding(m_seekFrameList.front()); if (m_curFrameIndex != m_seekFrameList.front().frameIndex) { qWarning() << "Failed to start decoding:" << m_file.fileName(); // Abort return OpenResult::FAILED; } return OpenResult::SUCCEEDED; }
/*! * \internal */ qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary) { qint64 payloadWritten = 0; if (Q_UNLIKELY(!m_pSocket) || (state() != QAbstractSocket::ConnectedState)) return payloadWritten; Q_Q(QWebSocket); const QWebSocketProtocol::OpCode firstOpCode = isBinary ? QWebSocketProtocol::OpCodeBinary : QWebSocketProtocol::OpCodeText; int numFrames = data.size() / FRAME_SIZE_IN_BYTES; QByteArray tmpData(data); tmpData.detach(); char *payload = tmpData.data(); quint64 sizeLeft = quint64(data.size()) % FRAME_SIZE_IN_BYTES; if (Q_LIKELY(sizeLeft)) ++numFrames; //catch the case where the payload is zero bytes; //in this case, we still need to send a frame if (Q_UNLIKELY(numFrames == 0)) numFrames = 1; quint64 currentPosition = 0; qint64 bytesWritten = 0; quint64 bytesLeft = data.size(); for (int i = 0; i < numFrames; ++i) { quint32 maskingKey = 0; if (m_mustMask) maskingKey = generateMaskingKey(); const bool isLastFrame = (i == (numFrames - 1)); const bool isFirstFrame = (i == 0); const quint64 size = qMin(bytesLeft, FRAME_SIZE_IN_BYTES); const QWebSocketProtocol::OpCode opcode = isFirstFrame ? firstOpCode : QWebSocketProtocol::OpCodeContinue; //write header bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame)); //write payload if (Q_LIKELY(size > 0)) { char *currentData = payload + currentPosition; if (m_mustMask) QWebSocketProtocol::mask(currentData, size, maskingKey); qint64 written = m_pSocket->write(currentData, static_cast<qint64>(size)); if (Q_LIKELY(written > 0)) { bytesWritten += written; payloadWritten += written; } else { m_pSocket->flush(); setErrorString(QWebSocket::tr("Error writing bytes to socket: %1.") .arg(m_pSocket->errorString())); Q_EMIT q->error(QAbstractSocket::NetworkError); break; } } currentPosition += size; bytesLeft -= size; } if (Q_UNLIKELY(payloadWritten != data.size())) { setErrorString(QWebSocket::tr("Bytes written %1 != %2.") .arg(payloadWritten).arg(data.size())); Q_EMIT q->error(QAbstractSocket::NetworkError); } return payloadWritten; }
/*! Returns true if this QElapsedTimer has already expired by \a timeout milliseconds (that is, more than \a timeout milliseconds have elapsed). The value of \a timeout can be -1 to indicate that this timer does not expire, in which case this function will always return false. \sa elapsed() */ bool QElapsedTimer::hasExpired(qint64 timeout) const { // if timeout is -1, quint64(timeout) is LLINT_MAX, so this will be // considered as never expired return quint64(elapsed()) > quint64(timeout); }