From ae47e6e40f4fa98897eb649cf9b110605cb8eb49 Mon Sep 17 00:00:00 2001 From: Tim Blechmann Date: Fri, 02 Oct 2026 08:31:27 +0800 Subject: [PATCH] Read WAV frames in chunks instead of trusting the header count The PCM frame count declared by a WAV header is untrusted. Both QDrWavAudioDecoder and QSampleCache sized their output buffer up front from that count, so a crafted file with a huge or wrapping frame count could trigger an enormous allocation or an integer overflow. Add a QtMultimediaPrivate::readFramesInChunks() helper that grows the buffer chunk by chunk as frames are actually produced, and fails unless exactly the declared frame count is read. Fixes: QTBUG-151155 Change-Id: I32c9e77cfd29857b8f08f085fe7c77553cb3e3fd Reviewed-by: Artem Dyomin Reviewed-by: Nils Petter Skålerud (cherry picked from commit ab5d16cdca6d1560bb36b5629352c3e8bc78a408) Reviewed-by: Tim Blechmann (cherry picked from commit 52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad) --- diff --git a/src/multimedia/audio/qdrawavaudiodecoder.cpp b/src/multimedia/audio/qdrawavaudiodecoder.cpp new file mode 100644 index 0000000..88fcbaa --- /dev/null +++ b/src/multimedia/audio/qdrawavaudiodecoder.cpp @@ -0,0 +1,375 @@ +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) +======= +// Copyright (C) 2026 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qdrawavaudiodecoder_p.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#if QT_CONFIG(network) +# include +# include +# include +#endif + +#include + +QT_BEGIN_NAMESPACE + +Q_STATIC_LOGGING_CATEGORY(qLcDrWavDecoder, "qt.multimedia.drwavdecoder") + +namespace QtMultimediaPrivate { + +static QDrWavDecodeResult makeFormatError(const QString &message) +{ + return q23::unexpected(std::pair(QAudioDecoder::FormatError, message)); +} + +static QDrWavDecodeResult makeResourceError(const QString &message) +{ + return q23::unexpected(std::pair(QAudioDecoder::ResourceError, message)); +} + +QDrWavDecodeResult loadWaveAndDecodeData(QSpan data, + const QAudioFormat &requestedFormat) +{ + using namespace QtPrivate; + + drwav wav; + if (!drwav_init_memory(&wav, data.data(), data.size(), nullptr)) { + qCDebug(qLcDrWavDecoder) << "Failed to initialize dr_wav decoder"; + return makeFormatError(QAudioDecoder::tr("Unable to decode audio file")); + } + + auto cleanup = qScopeGuard([&] { + drwav_uninit(&wav); + }); + + // Determine output format + QAudioFormat outputFormat; + size_t bytesPerFrame; + + if (requestedFormat.isValid()) { + // User set a format - check compatibility with file + if (requestedFormat.sampleRate() != static_cast(wav.sampleRate)) + return makeFormatError( + QAudioDecoder::tr("Audio file sample rate does not match requested format")); + if (requestedFormat.channelCount() != static_cast(wav.channels)) + return makeFormatError( + QAudioDecoder::tr("Audio file channel count does not match requested format")); + outputFormat = requestedFormat; + + // Determine bytes per frame based on requested format + switch (requestedFormat.sampleFormat()) { + case QAudioFormat::UInt8: + bytesPerFrame = wav.channels * sizeof(uint8_t); + break; + case QAudioFormat::Int16: + bytesPerFrame = wav.channels * sizeof(int16_t); + break; + case QAudioFormat::Int32: + bytesPerFrame = wav.channels * sizeof(int32_t); + break; + case QAudioFormat::Float: + bytesPerFrame = wav.channels * sizeof(float); + break; + default: + return makeFormatError(QAudioDecoder::tr("Unsupported sample format")); + } + } else { + // Infer format from file header - use native format heuristic + QAudioFormat::SampleFormat sampleFormat; + + switch (wav.bitsPerSample) { + case 8: + sampleFormat = QAudioFormat::UInt8; + bytesPerFrame = wav.channels * sizeof(uint8_t); + break; + case 16: + sampleFormat = QAudioFormat::Int16; + bytesPerFrame = wav.channels * sizeof(int16_t); + break; + case 24: // 24-bit → read as Int32 + sampleFormat = QAudioFormat::Int32; + bytesPerFrame = wav.channels * sizeof(int32_t); + break; + case 32: + sampleFormat = QAudioFormat::Int32; + bytesPerFrame = wav.channels * sizeof(int32_t); + break; + default: // unsupported → fallback Float + sampleFormat = QAudioFormat::Float; + bytesPerFrame = wav.channels * sizeof(float); + break; + } + + outputFormat.setChannelCount(wav.channels); + outputFormat.setSampleFormat(sampleFormat); + outputFormat.setSampleRate(wav.sampleRate); + outputFormat.setChannelConfig( + QAudioFormat::defaultChannelConfigForChannelCount(wav.channels)); + } + + qCDebug(qLcDrWavDecoder) << "Decoded WAV:" + << "channels=" << wav.channels << "sampleRate=" << wav.sampleRate + << "bitsPerSample=" << wav.bitsPerSample + << "totalPCMFrameCount=" << wav.totalPCMFrameCount + << "outputFormat=" << outputFormat.sampleFormat(); + + const QAudioFormat::SampleFormat readFormat = outputFormat.sampleFormat(); + switch (readFormat) { + case QAudioFormat::UInt8: + case QAudioFormat::Int16: + case QAudioFormat::Int32: + case QAudioFormat::Float: + break; + default: + return makeFormatError(QAudioDecoder::tr("Unsupported sample format")); + } + + std::optional decoded = readFramesInChunks( + wav.totalPCMFrameCount, bytesPerFrame, [&](uint64_t frameCount, char *out) -> uint64_t { + switch (readFormat) { + case QAudioFormat::UInt8: + return drwav_read_pcm_frames(&wav, frameCount, out); + case QAudioFormat::Int16: + return drwav_read_pcm_frames_s16(&wav, frameCount, reinterpret_cast(out)); + case QAudioFormat::Int32: + return drwav_read_pcm_frames_s32(&wav, frameCount, reinterpret_cast(out)); + case QAudioFormat::Float: + return drwav_read_pcm_frames_f32(&wav, frameCount, reinterpret_cast(out)); + default: + Q_UNREACHABLE_RETURN(0); + } + }); + + if (!decoded) { + qCDebug(qLcDrWavDecoder) << "Failed to read all frames:" + << "expected" << wav.totalPCMFrameCount; + return makeFormatError(QAudioDecoder::tr("Unable to read audio data")); + } + + const QByteArray &pcmData = *decoded; + + QAudioBuffer buffer(pcmData, outputFormat); + if (!buffer.isValid()) { + return makeFormatError(QAudioDecoder::tr("Failed to create audio buffer")); + } + + qCDebug(qLcDrWavDecoder) << "Successfully decoded:" << buffer.sampleCount() << "samples"; + + return buffer; +} + +} // namespace QtMultimediaPrivate + +QDrWavAudioDecoder::QDrWavAudioDecoder(QAudioDecoder *parent) + : QPlatformAudioDecoder(parent) +{ +} + +QDrWavAudioDecoder::~QDrWavAudioDecoder() +{ + stop(); +} + +void QDrWavAudioDecoder::setSource(const QUrl &fileName) +{ + stop(); + m_sourceDevice = nullptr; + if (std::exchange(m_source, fileName) != fileName) + sourceChanged(); +} + +void QDrWavAudioDecoder::setSourceDevice(QIODevice *device) +{ + stop(); + m_source.clear(); + if (std::exchange(m_sourceDevice, device) != device) + sourceChanged(); +} + +void QDrWavAudioDecoder::setAudioFormat(const QAudioFormat &format) +{ + if (isDecoding()) + return; + m_audioFormat = format; +} + + +void QDrWavAudioDecoder::start() +{ + if (isDecoding()) + return; + + if (m_source.isEmpty() && !m_sourceDevice) { + error(QAudioDecoder::ResourceError, tr("No audio source specified")); + return; + } + + m_decodingStopped = std::make_shared(false); + + auto threadPool = QThreadPool::globalInstance(); + threadPool->start([source = m_source, sourceDevice = m_sourceDevice, + requestedFormat = m_audioFormat, decodingStopped = m_decodingStopped, this] { + auto state = loadAndDecodeFile(source, sourceDevice, requestedFormat, decodingStopped); + + QMetaObject::invokeMethod(this, + [this, decodingStopped, state = std::move(state)]() mutable { + if (*decodingStopped) { + qCDebug(qLcDrWavDecoder) << "Decoding was stopped, discarding result"; + return; + } + onDecodeFinished(std::move(state), *decodingStopped); + }); + }); +} + +void QDrWavAudioDecoder::stop() +{ + if (!isDecoding()) + return; + + qCDebug(qLcDrWavDecoder) << "stop() called"; + + // Prevent the continuation from delivering the buffer + if (m_decodingStopped) { + *m_decodingStopped = true; + m_decodingStopped.reset(); + } + + m_buffer = QAudioBuffer(); + finished(); +} + +QAudioBuffer QDrWavAudioDecoder::read() +{ + if (m_buffer.isValid()) { + QAudioBuffer buffer = std::exchange(m_buffer, QAudioBuffer()); + positionChanged(duration()); + bufferAvailableChanged(false); + return buffer; + } + return QAudioBuffer(); +} + +auto QDrWavAudioDecoder::loadAndDecodeFile(const QUrl &source, QIODevice *sourceDevice, + const QAudioFormat &requestedFormat, + std::shared_ptr decodingStopped) + -> QDrWavDecodeResult +{ + using namespace QtMultimediaPrivate; + + QByteArray fileData; + + // Load file data based on source type + if (!source.isEmpty()) { + QString scheme = source.scheme(); + + if (scheme.isEmpty() || scheme == u"file") { + // Local file + QString filePath = source.isLocalFile() ? source.toLocalFile() + : source.path(); + QFile file(filePath); + if (!file.open(QFile::ReadOnly)) + return makeResourceError(QAudioDecoder::tr("Cannot open audio file")); + fileData = file.readAll(); + } else if (scheme == u"qrc") { + // QRC resource + QString filePath = u":" + source.toString(QUrl::RemoveScheme); + QFile file(filePath); + if (!file.open(QFile::ReadOnly)) + return makeResourceError(QAudioDecoder::tr("Cannot open audio resource")); + fileData = file.readAll(); + } +#if QT_CONFIG(network) + else { + // Network URL + QNetworkAccessManager networkAccessManager; + QNetworkReply *reply = networkAccessManager.get(QNetworkRequest(source)); + + if (reply->error() != QNetworkReply::NoError) { + reply->deleteLater(); + return makeResourceError(QAudioDecoder::tr("Failed to download audio file")); + } + + // Wait for network reply to finish + QEventLoop loop; + QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); + QObject::connect(reply, &QNetworkReply::errorOccurred, &loop, &QEventLoop::quit); + + loop.exec(); + + if (reply->error() != QNetworkReply::NoError) { + reply->deleteLater(); + return makeResourceError(QAudioDecoder::tr("Network error while downloading audio")); + } + + if (*decodingStopped) { + reply->deleteLater(); + return QAudioBuffer{}; + } + + fileData = reply->readAll(); + reply->deleteLater(); + } +#endif + } else if (sourceDevice) { + if (!sourceDevice->isOpen()) { + if (!sourceDevice->open(QIODevice::ReadOnly)) + return makeResourceError(QAudioDecoder::tr("Cannot open audio device")); + } + fileData = sourceDevice->readAll(); + } else { + return makeResourceError(QAudioDecoder::tr("No audio source specified")); + } + + if (fileData.isEmpty()) + return makeResourceError(QAudioDecoder::tr("Audio file is empty")); + + if (*decodingStopped) + return QAudioBuffer{}; + + QMetaObject::invokeMethod(this, [this, decodingStopped] { + if (!*decodingStopped) + setIsDecoding(true); + }, Qt::QueuedConnection); + + return QtMultimediaPrivate::loadWaveAndDecodeData( + as_bytes(QSpan{ fileData.constData(), fileData.size() }), requestedFormat); +} + +void QDrWavAudioDecoder::onDecodeFinished(QDrWavDecodeResult result, + const std::atomic_bool &decodingStopped) +{ + using namespace std::chrono; + if (!result.has_value()) { + auto [errorCode, errorString] = result.error(); + error(errorCode, errorString); + setIsDecoding(false); + return; + } + + m_buffer = std::move(*result); + // QAudioBuffer::duration() is in microseconds; convert to milliseconds + durationChanged(duration_cast(microseconds{ m_buffer.duration() })); + positionChanged(0ms); + + bufferAvailableChanged(true); + bufferReady(); + if (decodingStopped) + return; + + finished(); +} + +QT_END_NAMESPACE +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) diff --git a/src/multimedia/audio/qdrawavaudiodecoder_p.h b/src/multimedia/audio/qdrawavaudiodecoder_p.h new file mode 100644 index 0000000..5a67d09 --- /dev/null +++ b/src/multimedia/audio/qdrawavaudiodecoder_p.h @@ -0,0 +1,147 @@ +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) +======= +// Copyright (C) 2026 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef QDRAWAVAUDIODECODER_P_H +#define QDRAWAVAUDIODECODER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QAudioDecoder; +class QIODevice; + +namespace QtMultimediaPrivate { + +using QDrWavDecodeResult = q23::expected>; +QDrWavDecodeResult loadWaveAndDecodeData(QSpan, + const QAudioFormat &requestedFormat); + +#ifdef __cpp_concepts +template +concept FrameReader = std::is_invocable_v + && std::is_convertible_v, uint64_t>; +#endif + +#ifdef __cpp_concepts +template +#else +template +#endif +std::optional readFramesInChunks(uint64_t declaredFrameCount, size_t bytesPerFrame, + Reader &&readFrames) +{ + constexpr size_t chunkBytes = 10 * 1024 * 1024; // 10 MB + if (bytesPerFrame == 0) + return std::nullopt; + + const uint64_t chunkFrames = std::max(1, chunkBytes / bytesPerFrame); + + QT_TRY + { + QByteArray result; + uint64_t totalFramesRead = 0; + while (totalFramesRead < declaredFrameCount) { + const uint64_t framesToRead = + std::min(chunkFrames, declaredFrameCount - totalFramesRead); + const uint64_t bytesToRead = framesToRead * bytesPerFrame; + const qsizetype oldSize = result.size(); + if (bytesToRead > uint64_t(QByteArray::maxSize() - oldSize)) + return std::nullopt; + + result.resizeForOverwrite(oldSize + qsizetype(bytesToRead)); + const uint64_t framesRead = readFrames(framesToRead, result.data() + oldSize); + Q_ASSERT(framesRead <= framesToRead); + result.resize(oldSize + qsizetype(framesRead * bytesPerFrame)); + + totalFramesRead += framesRead; + if (framesRead < framesToRead) + break; + } + if (totalFramesRead != declaredFrameCount) + return std::nullopt; + return result; + } + QT_CATCH(const std::bad_alloc &) + { + return std::nullopt; + } +} + +} // namespace QtMultimediaPrivate + +class QDrWavAudioDecoder final : public QPlatformAudioDecoder +{ +public: + explicit QDrWavAudioDecoder(QAudioDecoder *parent); + ~QDrWavAudioDecoder() override; + + // Source management + QUrl source() const override { return m_source; } + void setSource(const QUrl &) override; + + QIODevice *sourceDevice() const override { return m_sourceDevice; } + void setSourceDevice(QIODevice *) override; + + // Lifecycle + void start() override; + void stop() override; + + // Format + QAudioFormat audioFormat() const override { return m_audioFormat; } + void setAudioFormat(const QAudioFormat &) override; + + // Buffer pull model + QAudioBuffer read() override; + + // Metadata + bool canReadQrc() const override { return true; } + +private: + using QDrWavDecodeResult = QtMultimediaPrivate::QDrWavDecodeResult; + + QDrWavDecodeResult loadAndDecodeFile(const QUrl &, QIODevice *, const QAudioFormat &, + std::shared_ptr decodingStopped); + + // Handle decode completion + void onDecodeFinished(QDrWavDecodeResult, const std::atomic_bool &decodingStopped); + + QUrl m_source; + QIODevice *m_sourceDevice = nullptr; + QAudioFormat m_audioFormat; + + // Decoded result + QAudioBuffer m_buffer; + + std::shared_ptr m_decodingStopped; +}; + +QT_END_NAMESPACE + +#endif // QDRAWAVAUDIODECODER_P_H +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) diff --git a/src/multimedia/audio/qsamplecache_p.cpp b/src/multimedia/audio/qsamplecache_p.cpp index 4f6cb61..8186bb3 100644 --- a/src/multimedia/audio/qsamplecache_p.cpp +++ b/src/multimedia/audio/qsamplecache_p.cpp @@ -3,6 +3,12 @@ #include "qsamplecache_p.h" +#include +#include +#include +#include +#include +#include #include #include #include @@ -10,7 +16,11 @@ #include #include #include +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) #include +======= +#include +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) #if QT_CONFIG(network) # include @@ -116,6 +126,7 @@ audioFormat.setChannelConfig( QAudioFormat::defaultChannelConfigForChannelCount(wavParser.channels)); +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) QByteArray sampleData; sampleData.resizeForOverwrite(sizeof(float) * wavParser.channels * wavParser.totalPCMFrameCount); @@ -124,9 +135,18 @@ if (framesRead != wavParser.totalPCMFrameCount) return std::nullopt; +======= + std::optional sampleData = QtMultimediaPrivate::readFramesInChunks( + wavParser.totalPCMFrameCount, sizeof(float) * wavParser.channels, + [&](uint64_t frameCount, char *out) -> uint64_t { + return drwav_read_pcm_frames_f32(&wavParser, frameCount, reinterpret_cast(out)); + }); + if (!sampleData) + return q23::unexpected(QSampleLoadError::FormatError); +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) return std::pair{ - std::move(sampleData), + std::move(*sampleData), audioFormat, }; } diff --git a/tests/auto/unit/multimedia/qsamplecache/tst_qsamplecache.cpp b/tests/auto/unit/multimedia/qsamplecache/tst_qsamplecache.cpp index b62add9..3a4de01 100644 --- a/tests/auto/unit/multimedia/qsamplecache/tst_qsamplecache.cpp +++ b/tests/auto/unit/multimedia/qsamplecache/tst_qsamplecache.cpp @@ -1,10 +1,28 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) +======= +#include + +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) #include +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) #include +======= +#include +#include +#include +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) #include +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) +======= +#include + +Q_ENABLE_MOCK_MULTIMEDIA_PLUGIN + +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) class tst_QSampleCache : public QObject { Q_OBJECT @@ -31,7 +49,72 @@ void testDRwavIntegerUnderflow_data() { generateTestData(); } void testDRwavIntegerUnderflow(); +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) +======= + void testLoadSampleFromSpan_valid(); + void testLoadSampleFromSpan_invalid(); + void testLoadSampleFromSpan_declaredFrameCountMismatch_data(); + void testLoadSampleFromSpan_declaredFrameCountMismatch(); + void testLoadSampleFromSpan_multiChannel(); + void testLoadSampleViaDecoderBuffer_declaredFrameCountMismatch_data() + { + testLoadSampleFromSpan_declaredFrameCountMismatch_data(); + } + void testLoadSampleViaDecoderBuffer_declaredFrameCountMismatch(); + void testLoadSampleViaDecoder_valid(); + void testLoadSampleViaDecoder_fallbackToDrWav(); + void testLoadSampleViaDecoderBuffer_valid(); + void testLoadSampleViaDecoderBuffer_fallbackToDrWav(); + void testFallbackToDecoder_nonWav(); + void testForcedDecoderPath(); + void testFallbackToDecoder_notSupported(); + void testMP3FallbackViaDecoder(); + void testMP3FallbackViaDecoderBuffer(); + void testLoadSampleAsyncViaDecoder_valid(); + void testLoadSampleAsyncViaDecoder_fallbackToDrWav(); + void testForcedDecoderPathAsync(); + +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) private: + template + static void appendLittleEndian(QByteArray &out, T value) + { + const T le = qToLittleEndian(value); + out.append(reinterpret_cast(&le), sizeof(le)); + } + + static QByteArray makeRf64Wav(uint64_t declaredFrameCount, uint16_t channelCount, + qsizetype dataBytes) + { + const uint16_t bytesPerFrame = channelCount * sizeof(int16_t); + + QByteArray wav; + wav.append("RF64"); + appendLittleEndian(wav, 0xFFFFFFFF); + wav.append("WAVE"); + + wav.append("ds64"); + appendLittleEndian(wav, 28); + appendLittleEndian(wav, 0); // RIFF size, ignored + appendLittleEndian(wav, uint64_t(dataBytes)); + appendLittleEndian(wav, declaredFrameCount); + appendLittleEndian(wav, 0); // table length + + wav.append("fmt "); + appendLittleEndian(wav, 16); + appendLittleEndian(wav, 1); // PCM + appendLittleEndian(wav, channelCount); + appendLittleEndian(wav, 8000); + appendLittleEndian(wav, 8000 * bytesPerFrame); + appendLittleEndian(wav, bytesPerFrame); + appendLittleEndian(wav, 16); + + wav.append("data"); + appendLittleEndian(wav, 0xFFFFFFFF); + wav.append(QByteArray(dataBytes, '\x7f')); + return wav; + } + void generateTestData() { QTest::addColumn("sampleSourceType"); @@ -141,6 +224,238 @@ QVERIFY(!sample); // bad file } +<<<<<<< HEAD (f5e165a352803899cf58a06dfb5ad7efe8e7670e tests: skip CI tests of QAudioSink) +======= +void tst_QSampleCache::testLoadSampleFromSpan_valid() +{ + QFile file(QFINDTESTDATA("testdata/test.wav")); + QVERIFY(file.open(QFile::ReadOnly)); + QByteArray data = file.readAll(); + QVERIFY(!data.isEmpty()); + + auto result = QSampleCache::loadSample(data); + QVERIFY(result.has_value()); + QCOMPARE(result->second.sampleFormat(), QAudioFormat::Float); + QVERIFY(result->second.sampleRate() > 0); + QVERIFY(!result->first.isEmpty()); +} + +void tst_QSampleCache::testLoadSampleFromSpan_invalid() +{ + QByteArray garbage(100, '\xFF'); + auto result = QSampleCache::loadSample(garbage); + QVERIFY(!result.has_value()); + QCOMPARE(result.error(), QSampleLoadError::FormatError); +} + +void tst_QSampleCache::testLoadSampleFromSpan_declaredFrameCountMismatch_data() +{ + QTest::addColumn("declaredFrameCount"); + + // 4 * (2^62 + 256) wraps to 1024 in 64-bit arithmetic + QTest::newRow("wrapping") << ((uint64_t(1) << 62) + 256); + QTest::newRow("huge") << (uint64_t(1) << 40); + QTest::newRow("more-than-data") << uint64_t(1024 * 1024); +} + +void tst_QSampleCache::testLoadSampleFromSpan_declaredFrameCountMismatch() +{ + QFETCH(const uint64_t, declaredFrameCount); + + const QByteArray wav = makeRf64Wav(declaredFrameCount, 1, 1024 * 1024); + auto result = QSampleCache::loadSample(wav); + QVERIFY(!result.has_value()); + QCOMPARE(result.error(), QSampleLoadError::FormatError); +} + +void tst_QSampleCache::testLoadSampleFromSpan_multiChannel() +{ + constexpr uint16_t channelCount = 2; + constexpr uint64_t frameCount = 3'000'000; // spans multiple decode chunks + + const QByteArray wav = + makeRf64Wav(frameCount, channelCount, qsizetype(frameCount * channelCount * 2)); + auto result = QSampleCache::loadSample(wav); + QVERIFY(result.has_value()); + QCOMPARE_EQ(result->second.channelCount(), int(channelCount)); + QCOMPARE_EQ(result->first.size(), qsizetype(frameCount * channelCount * sizeof(float))); +} + +void tst_QSampleCache::testLoadSampleViaDecoderBuffer_declaredFrameCountMismatch() +{ + QFETCH(const uint64_t, declaredFrameCount); + + QMockIntegration::instance()->setFlags(QMockIntegration::NoAudioDecoderInterface); + + const QByteArray wav = makeRf64Wav(declaredFrameCount, 1, 1024 * 1024); + auto result = QSampleCache::loadSampleViaDecoder(wav); + QVERIFY(!result.has_value()); +} + +void tst_QSampleCache::testLoadSampleViaDecoder_valid() +{ + const QUrl url = QUrl::fromLocalFile(QFINDTESTDATA("testdata/test.wav")); + auto result = QSampleCache::loadSampleViaDecoder(url); + QVERIFY(result.has_value()); + QCOMPARE(result->second.sampleFormat(), QAudioFormat::Float); + QVERIFY(!result->first.isEmpty()); + QVERIFY(result->second.sampleRate() > 0); + QVERIFY(result->second.channelCount() > 0); +} + +void tst_QSampleCache::testLoadSampleViaDecoder_fallbackToDrWav() +{ + QMockIntegration::instance()->setFlags(QMockIntegration::NoAudioDecoderInterface); + + const QUrl url = QUrl::fromLocalFile(QFINDTESTDATA("testdata/nokia-tune.mp3")); + auto result = QSampleCache::loadSampleViaDecoder(url); + QVERIFY(!result.has_value()); + QCOMPARE(result.error(), QSampleLoadError::DecoderError); +} + +void tst_QSampleCache::testLoadSampleViaDecoderBuffer_valid() +{ + QFile file(QFINDTESTDATA("testdata/test.wav")); + QVERIFY(file.open(QFile::ReadOnly)); + QByteArray data = file.readAll(); + QVERIFY(!data.isEmpty()); + + auto result = QSampleCache::loadSampleViaDecoder(data); + QVERIFY(result.has_value()); + QCOMPARE(result->second.sampleFormat(), QAudioFormat::Float); + QVERIFY(!result->first.isEmpty()); + QVERIFY(result->second.sampleRate() > 0); + QVERIFY(result->second.channelCount() > 0); +} + +void tst_QSampleCache::testLoadSampleViaDecoderBuffer_fallbackToDrWav() +{ + QMockIntegration::instance()->setFlags(QMockIntegration::NoAudioDecoderInterface); + + QFile file(QFINDTESTDATA("testdata/nokia-tune.mp3")); + QVERIFY(file.open(QFile::ReadOnly)); + QByteArray data = file.readAll(); + + auto result = QSampleCache::loadSampleViaDecoder(data); + QVERIFY(!result.has_value()); + QCOMPARE(result.error(), QSampleLoadError::DecoderError); +} + +void tst_QSampleCache::testFallbackToDecoder_nonWav() +{ + // No sampleSourceType → fallback enabled + QSampleCache cache; + + const QUrl url = QUrl::fromLocalFile(QFINDTESTDATA("testdata/corrupted.wav")); + SharedSamplePtr sample = requestSample(cache, url); + // drwav fails, mock decoder succeeds → sample ready + QVERIFY(sample); + QCOMPARE(sample->state(), QSample::Ready); +} + +void tst_QSampleCache::testForcedDecoderPath() +{ + QSampleCache cache; + + const QUrl url = QUrl::fromLocalFile(QFINDTESTDATA("testdata/test.wav")); + SharedSamplePtr sample = requestSample(cache, url, QSampleCache::SampleSourceType::AudioDecoder); + // AudioDecoder skips drwav, uses mock decoder directly + QVERIFY(sample); + QCOMPARE(sample->state(), QSample::Ready); + QCOMPARE(sample->format().sampleFormat(), QAudioFormat::Float); +} + +void tst_QSampleCache::testFallbackToDecoder_notSupported() +{ + QMockIntegration::instance()->setFlags(QMockIntegration::NoAudioDecoderInterface); + + // No sampleSourceType → fallback enabled; drwav fallback via QAudioDecoder + // still fails because the file itself is corrupted, not because a + // platform decoder is unavailable. + QSampleCache cache; + + const QUrl url = QUrl::fromLocalFile(QFINDTESTDATA("testdata/corrupted.wav")); + SharedSamplePtr sample = requestSample(cache, url); + // drwav fails, decoder fallback also fails on the corrupted data → null + QVERIFY(!sample); +} + +void tst_QSampleCache::testMP3FallbackViaDecoder() +{ + // No sampleSourceType → fallback enabled + QSampleCache cache; + + const QUrl url = QUrl::fromLocalFile(QFINDTESTDATA("testdata/nokia-tune.mp3")); + SharedSamplePtr sample = requestSample(cache, url); + // drwav fails on MP3, mock decoder succeeds → sample ready + QVERIFY(sample); + QCOMPARE(sample->state(), QSample::Ready); + QCOMPARE(sample->format().sampleFormat(), QAudioFormat::Float); + // Verify decoder was actually invoked via the mock + QVERIFY(QMockIntegration::instance()->lastAudioDecoder() != nullptr); +} + +void tst_QSampleCache::testMP3FallbackViaDecoderBuffer() +{ + QFile file(QFINDTESTDATA("testdata/nokia-tune.mp3")); + QVERIFY(file.open(QFile::ReadOnly)); + QByteArray data = file.readAll(); + QVERIFY(!data.isEmpty()); + + auto result = QSampleCache::loadSampleViaDecoder(data); + // drwav fails, mock decoder succeeds via QBuffer + QVERIFY(result.has_value()); + QCOMPARE(result->second.sampleFormat(), QAudioFormat::Float); + QVERIFY(!result->first.isEmpty()); +} + +void tst_QSampleCache::testLoadSampleAsyncViaDecoder_valid() +{ + QFile file(QFINDTESTDATA("testdata/test.wav")); + QVERIFY(file.open(QFile::ReadOnly)); + QByteArray data = file.readAll(); + QVERIFY(!data.isEmpty()); + + auto future = QSampleCache::loadSampleAsyncViaDecoder(data); + QTRY_VERIFY(future.isFinished()); + + auto result = future.result(); + QVERIFY(result.has_value()); + QCOMPARE(result->second.sampleFormat(), QAudioFormat::Float); + QVERIFY(!result->first.isEmpty()); + QVERIFY(result->second.sampleRate() > 0); + QVERIFY(result->second.channelCount() > 0); + QVERIFY(QMockIntegration::instance()->lastAudioDecoder() != nullptr); +} + +void tst_QSampleCache::testLoadSampleAsyncViaDecoder_fallbackToDrWav() +{ + QMockIntegration::instance()->setFlags(QMockIntegration::NoAudioDecoderInterface); + + QFile file(QFINDTESTDATA("testdata/nokia-tune.mp3")); + QVERIFY(file.open(QFile::ReadOnly)); + QByteArray data = file.readAll(); + + auto future = QSampleCache::loadSampleAsyncViaDecoder(data); + QTRY_VERIFY(future.isFinished()); + + auto result = future.result(); + QVERIFY(!result.has_value()); + QCOMPARE(result.error(), QSampleLoadError::DecoderError); +} + +void tst_QSampleCache::testForcedDecoderPathAsync() +{ + QSampleCache cache; + + const QUrl url = QUrl::fromLocalFile(QFINDTESTDATA("testdata/test.wav")); + SharedSamplePtr sample = requestSample(cache, url, QSampleCache::SampleSourceType::AudioDecoder); + QVERIFY(sample); + QCOMPARE(sample->state(), QSample::Ready); + QCOMPARE(sample->format().sampleFormat(), QAudioFormat::Float); +} + +>>>>>>> CHANGE (52f1b58a3d2d959f29e1716ff8d971a1e0ef8fad Read WAV frames in chunks instead of trusting the header cou) QTEST_GUILESS_MAIN(tst_QSampleCache) #include "tst_qsamplecache.moc"