Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwasmaudiodecoder.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
6
7#include <emscripten.h>
8#include <emscripten/val.h>
9
10#include <QtCore/qfile.h>
11#include <QtCore/qscopedvaluerollback.h>
12#include <QtCore/qspan.h>
13
14#include <private/qstdweb_p.h>
15#include <QtMultimedia/private/qaudio_parsing_support_p.h>
16
17#include <chrono>
18#include <optional>
19
20QT_BEGIN_NAMESPACE
21
22namespace AudioParsing = QtMultimediaPrivate::ParsingSupport;
23
24// ---------------------------------------------------------------------------
25// EM_JS. Only the decoder constructor stays here because it creates JS
26// closures that are impractical to express with emscripten::val.
27// Everything else is implemented directly in C++ using emscripten::val.
28// ---------------------------------------------------------------------------
29
30// Creates an AudioDecoder. The output callback stores each decoded AudioData
31// object directly in decoder._qtOutputs so C++ can allocate the receive buffer
32// and call copyTo() itself, with no Module._malloc dependency. Error outputs
33// are stored as plain {_error} objects.
34//
35// Caller must close all AudioData entries and call decoder.close() when done.
36EM_JS(emscripten::EM_VAL, qt_wc_create_decoder, (), {
37 var outputs = [];
38 var decoder = new AudioDecoder({
39 output: function(audioData) {
40 outputs.push(audioData);
41 },
42 error: function(err) {
43 outputs.push({ _error: err.message || String(err) });
44 }
45 });
46 decoder._qtOutputs = outputs;
47 return Emval.toHandle(decoder);
48});
49
50// ---------------------------------------------------------------------------
51// Private helpers
52// ---------------------------------------------------------------------------
53
54namespace {
55
56// How often decoded outputs are drained while decoding. Short enough that
57// buffers arrive steadily, long enough that each drain handles a batch.
58constexpr std::chrono::milliseconds outputDrainInterval{ 10 };
59
60QSpan<const std::byte> asBytes(const QByteArray &data)
61{
62 return as_bytes(QSpan{ data.constData(), data.size() });
63}
64
65// Returns the WebCodecs codec identifier string for a sniffed codec.
66// Only meaningful for codecs that can actually be configured on an
67// AudioDecoder (i.e. not Unknown or Wav).
68const char *codecString(AudioParsing::AudioCodec codec)
69{
70 switch (codec) {
71 case AudioParsing::AudioCodec::Mp3: return "mp3";
72 case AudioParsing::AudioCodec::Aac: return "mp4a.40.2";
73 case AudioParsing::AudioCodec::Flac: return "flac";
74 case AudioParsing::AudioCodec::Opus: return "opus";
75 case AudioParsing::AudioCodec::Unknown:
76 case AudioParsing::AudioCodec::Vorbis: // no WebCodecs decoder; decodeAudioData handles it
77 case AudioParsing::AudioCodec::Wav:
78 break;
79 }
80 return "";
81}
82
83// Builds the WebCodecs AudioDecoderConfig.description field for a FLAC stream,
84// which is mandatory for FLAC - isConfigSupported rejects without it. Chrome
85// requires all metadata blocks in the description, not just STREAMINFO, so the
86// blob spans everything between the "fLaC" marker and the first audio frame.
87// Also fills sampleRate and numChannels from the STREAMINFO block.
88// Returns an empty array if the data is too short or malformed.
89QByteArray flacDescription(const QByteArray &data, int &sampleRate, int &numChannels)
90{
91 const std::optional<AudioParsing::FlacStreamInfo> info =
92 AudioParsing::flacStreamInfo(asBytes(data));
93 if (!info)
94 return {};
95
96 sampleRate = info->sampleRate;
97 numChannels = info->numChannels;
98
99 const std::optional<qsizetype> audioOffset = AudioParsing::flacAudioOffset(asBytes(data));
100 if (!audioOffset)
101 return {}; // metadata not fully buffered yet
102 return data.mid(4, *audioOffset - 4);
103}
104
105// Returns the stream duration recorded in the FLAC STREAMINFO block, or
106// std::nullopt when the block is missing or the encoder did not record the
107// total sample count. Like the other backends, the decoder reports duration
108// from container metadata before decoding starts.
109std::optional<std::chrono::milliseconds> flacDuration(const QByteArray &data)
110{
111 const std::optional<AudioParsing::FlacStreamInfo> info =
112 AudioParsing::flacStreamInfo(asBytes(data));
113 if (!info || info->sampleRate <= 0 || info->totalSamples <= 0)
114 return std::nullopt;
115 return std::chrono::milliseconds{ info->totalSamples * 1000 / info->sampleRate };
116}
117
118// Returns the sample rate the browser will decode this stream at, or 0 when it
119// is unknown. Only Ogg Vorbis is reported: decodeAudioData resamples to the
120// AudioContext rate, so pinning the context to the Vorbis rate keeps the
121// source's own rate. Opus is deliberately excluded because it always decodes
122// at 48000 Hz regardless of the encoder's input rate.
123int nativeSampleRate(AudioParsing::AudioCodec codec, const QByteArray &data)
124{
125 if (codec != AudioParsing::AudioCodec::Vorbis)
126 return 0;
127
128 const std::optional<AudioParsing::OggStreamInfo> info =
129 AudioParsing::oggStreamInfo(asBytes(data));
130 if (!info || info->codec != AudioParsing::AudioCodec::Vorbis)
131 return 0;
132
133 // AudioContext rejects rates outside the range it supports, so anything
134 // unusual is left to the default context rather than risking a throw.
135 constexpr int minimumRate = 8000;
136 constexpr int maximumRate = 96000;
137 return info->sampleRate >= minimumRate && info->sampleRate <= maximumRate ? info->sampleRate
138 : 0;
139}
140
141// Returns a short, human-readable description of the first bytes of a stream.
142// Included in fallback error messages so that a source which is not audio at
143// all, such as a truncated download or an HTML error page saved with an
144// audio file name, is obvious from the message alone.
145QString dataPrefixHint(const QByteArray &data)
146{
147 constexpr qsizetype maxHintBytes = 16;
148 const QByteArray head = data.left(maxHintBytes);
149 if (head.isEmpty())
150 return QStringLiteral("no data");
151
152 bool textLike = true;
153 for (char character : head) {
154 const auto value = static_cast<unsigned char>(character);
155 const bool isWhitespace = value == '\t' || value == '\n' || value == '\r';
156 if (!isWhitespace && (value < 0x20 || value > 0x7e)) {
157 textLike = false;
158 break;
159 }
160 }
161
162 if (textLike) {
163 return QStringLiteral("data starts with \"%1\"")
164 .arg(QString::fromLatin1(head).simplified());
165 }
166 return QStringLiteral("data starts with %1")
167 .arg(QString::fromLatin1(head.toHex(' ')));
168}
169
170} // namespace
171
172// ---------------------------------------------------------------------------
173// QWasmAudioDecoder
174// ---------------------------------------------------------------------------
175
176QWasmAudioDecoder::QWasmAudioDecoder(QAudioDecoder *parent)
177 : QPlatformAudioDecoder(parent)
178{
179 m_outputDrainTimer.setInterval(outputDrainInterval);
180 connect(&m_outputDrainTimer, &QTimer::timeout, this, &QWasmAudioDecoder::deliverOutputs);
181}
182
183QWasmAudioDecoder::~QWasmAudioDecoder()
184{
185 ++(*m_generationPtr);
186 if (m_sourceDevice)
187 disconnect(m_sourceDevice, nullptr, this, nullptr);
188 closeDecoder();
189}
190
191QUrl QWasmAudioDecoder::source() const
192{
193 return m_source;
194}
195
196void QWasmAudioDecoder::setSource(const QUrl &url)
197{
198 stop();
199 m_source = url;
200 m_sourceDevice = nullptr;
201 sourceChanged();
202}
203
204QIODevice *QWasmAudioDecoder::sourceDevice() const
205{
206 return m_sourceDevice;
207}
208
209void QWasmAudioDecoder::setSourceDevice(QIODevice *device)
210{
211 stop();
212 m_sourceDevice = device;
213 m_source = QUrl{};
214 sourceChanged();
215}
216
217QAudioFormat QWasmAudioDecoder::audioFormat() const
218{
219 return m_audioFormat;
220}
221
222void QWasmAudioDecoder::setAudioFormat(const QAudioFormat &format)
223{
224 if (m_audioFormat == format)
225 return;
226 m_audioFormat = format;
227 formatChanged(m_audioFormat);
228}
229
230QAudioBuffer QWasmAudioDecoder::read()
231{
232 if (m_pendingBuffers.isEmpty())
233 return {};
234
235 QAudioBuffer buffer = m_pendingBuffers.dequeue();
236 if (m_pendingBuffers.isEmpty())
237 bufferAvailableChanged(false);
238
239 // QAudioBuffer::startTime is in microseconds. Convert to milliseconds
240 positionChanged(std::chrono::round<std::chrono::milliseconds>(
241 std::chrono::microseconds{ buffer.startTime() }));
242 return buffer;
243}
244
245void QWasmAudioDecoder::start()
246{
247 if (isDecoding())
248 return;
249
250 if (emscripten::val::global("AudioDecoder").isUndefined()) {
251 handleError(QAudioDecoder::FormatError,
252 QStringLiteral("WebCodecs AudioDecoder is not available in this browser"));
253 return;
254 }
255
256 m_pendingBuffers.clear();
257 bufferAvailableChanged(false);
258 ++(*m_generationPtr);
259 resetDecodingState();
260 m_formatEmitted = false;
261 setIsDecoding(true);
262
263 if (m_sourceDevice) {
264 // STREAMING PATH. Configure the decoder once we peek the codec header,
265 // then feed compressed bytes as they arrive via readyRead.
266 if (!m_sourceDevice->isReadable()) {
267 handleError(QAudioDecoder::ResourceError,
268 QStringLiteral("Source device is not readable"));
269 return;
270 }
271 m_decoder = emscripten::val::take_ownership(qt_wc_create_decoder());
272 connect(m_sourceDevice, &QIODevice::readyRead,
273 this, &QWasmAudioDecoder::onSourceReadyRead);
274 connect(m_sourceDevice, &QIODevice::aboutToClose,
275 this, &QWasmAudioDecoder::onSourceDone);
276 onSourceReadyRead(); // drain any bytes already buffered in the device
277 } else if (!m_source.isEmpty()) {
278
279 // FILE / QRC PATH. Read everything synchronously, then chunk-feed.
280 const QString scheme = m_source.scheme();
281
282 QByteArray data;
283 if (scheme == QStringLiteral("qrc") || scheme.isEmpty()) {
284 const QString path = QLatin1Char(':') + m_source.path();
285 QFile file(path);
286 if (!file.open(QIODevice::ReadOnly)) {
287 handleError(QAudioDecoder::ResourceError,
288 QStringLiteral("Cannot open Qt resource: ") + path);
289 return;
290 }
291 data = file.readAll();
292 } else if (scheme == QStringLiteral("file")) {
293 QFile file(m_source.toLocalFile());
294 if (!file.open(QIODevice::ReadOnly)) {
295 handleError(QAudioDecoder::ResourceError,
296 QStringLiteral("Cannot open file: ") + m_source.toLocalFile());
297 return;
298 }
299 data = file.readAll();
300 } else {
301 handleError(QAudioDecoder::ResourceError,
302 QStringLiteral("http/https sources are not supported with WebCodecs; "
303 "use a local file or QIODevice"));
304 return;
305 }
306
307 if (data.isEmpty()) {
308 handleError(QAudioDecoder::ResourceError,
309 QStringLiteral("Audio source data is empty"));
310 return;
311 }
312
313 // Save raw data before any early returns so tryDecodeAudioData() has it
314 // available as a fallback for any format WebCodecs cannot handle.
315 m_rawData = data;
316
317 const Codec codec = AudioParsing::sniffCodec(asBytes(data));
318 if (codec == Codec::Unknown) {
319 // Unrecognized by our sniffer (e.g. M4A, WebM), so let the browser
320 // try to decode it via AudioContext.decodeAudioData.
321 m_fallbackReason = QStringLiteral("no known audio codec signature (%1)")
322 .arg(dataPrefixHint(data));
323 tryDecodeAudioData();
324 return;
325 }
326 if (codec == Codec::Wav) {
327 handleError(QAudioDecoder::FormatError,
328 QStringLiteral("WAV is uncompressed; use QWaveDecoder directly"));
329 return;
330 }
331 if (codec == Codec::Vorbis) {
332 // WebCodecs has no Vorbis decoder, and isConfigSupported() only
333 // validates the codec string, so configuring one would succeed and
334 // then fail on the first chunk. Go straight to decodeAudioData.
335 m_codec = codec;
336 m_fallbackReason = QStringLiteral("WebCodecs has no Vorbis decoder");
337 tryDecodeAudioData();
338 return;
339 }
340
341 // Check browser codec support before creating the decoder.
342 // For FLAC, extract real sampleRate/numChannels and the mandatory description
343 // from the STREAMINFO block, since isConfigSupported rejects without it.
344 int sampleRate = m_audioFormat.isValid() ? m_audioFormat.sampleRate() : 0;
345 int numChannels = m_audioFormat.isValid() ? m_audioFormat.channelCount() : 0;
346 QByteArray flacDesc;
347 if (codec == Codec::Flac) {
348 flacDesc = flacDescription(data, sampleRate, numChannels);
349 if (const std::optional<std::chrono::milliseconds> duration = flacDuration(data))
350 durationChanged(*duration);
351 }
352 if (sampleRate <= 0)
353 sampleRate = 48000;
354 if (numChannels <= 0)
355 numChannels = 2;
356
357 m_checkingSupport = true;
358 m_decoder = emscripten::val::take_ownership(qt_wc_create_decoder());
359
360 auto generationPtr = m_generationPtr;
361 const int generation = *generationPtr;
362
363 emscripten::val supportConfig = emscripten::val::object();
364 supportConfig.set("codec", codecString(codec));
365 supportConfig.set("sampleRate", sampleRate);
366 supportConfig.set("numberOfChannels", numChannels);
367 if (!flacDesc.isEmpty()) {
368 emscripten::val descView = emscripten::val(emscripten::typed_memory_view(
369 static_cast<size_t>(flacDesc.size()),
370 reinterpret_cast<const uint8_t *>(flacDesc.constData())));
371 supportConfig.set("description", descView.call<emscripten::val>("slice"));
372 }
373 emscripten::val supportPromise = emscripten::val::global("AudioDecoder")
374 .call<emscripten::val>("isConfigSupported", supportConfig);
375
376 qstdweb::Promise(supportPromise)
377 .addThenFunction([this, generationPtr, generation, codec, data, sampleRate, numChannels, flacDesc]
378 (emscripten::val result) {
379 if (*generationPtr != generation)
380 return;
381 m_checkingSupport = false;
382 if (!result["supported"].as<bool>()) {
383 m_fallbackReason = QStringLiteral("WebCodecs does not support codec \"%1\"")
384 .arg(QLatin1StringView(codecString(codec)));
385 qWarning() << "QWasmAudioDecoder:" << m_fallbackReason
386 << "— falling back to decodeAudioData";
387 closeDecoder();
388 tryDecodeAudioData();
389 return;
390 }
391 m_codec = codec;
392 emscripten::val decoderConfig = emscripten::val::object();
393 decoderConfig.set("codec", codecString(codec));
394 decoderConfig.set("sampleRate", sampleRate);
395 decoderConfig.set("numberOfChannels", numChannels);
396 if (!flacDesc.isEmpty()) {
397 emscripten::val descView = emscripten::val(emscripten::typed_memory_view(
398 static_cast<size_t>(flacDesc.size()),
399 reinterpret_cast<const uint8_t *>(flacDesc.constData())));
400 decoderConfig.set("description", descView.call<emscripten::val>("slice"));
401 }
402 m_decoder.call<void>("configure", decoderConfig);
403 m_outputDrainTimer.start();
404 // For codecs with parseable frame sizes, feed frame-by-frame so
405 // every EncodedAudioChunk contains complete access units.
406 // Other codecs (Opus) go as one chunk.
407 m_inputBuffer = data;
408 m_inputPos = 0;
409 if (AudioParsing::hasFrameParser(m_codec))
410 feedAvailableFrames(true);
411 else if (m_inputPos < m_inputBuffer.size())
412 feedChunk(QByteArray(m_inputBuffer.constData() + m_inputPos,
413 m_inputBuffer.size() - m_inputPos));
414 m_inputBuffer.clear();
415 m_inputPos = 0;
416 startFlush();
417 })
418 .addCatchFunction([this, generationPtr, generation, codec](emscripten::val) {
419 if (*generationPtr != generation)
420 return;
421 m_checkingSupport = false;
422 m_fallbackReason =
423 QStringLiteral("WebCodecs isConfigSupported rejected codec \"%1\"")
424 .arg(QLatin1StringView(codecString(codec)));
425 qWarning() << "QWasmAudioDecoder:" << m_fallbackReason
426 << "— falling back to decodeAudioData";
427 closeDecoder();
428 tryDecodeAudioData();
429 });
430 } else {
431 handleError(QAudioDecoder::ResourceError,
432 QStringLiteral("No audio source specified"));
433 }
434}
435
436void QWasmAudioDecoder::stop()
437{
438 ++(*m_generationPtr);
439 if (m_sourceDevice)
440 disconnect(m_sourceDevice, nullptr, this, nullptr);
441 closeDecoder();
442 m_pendingBuffers.clear();
443 bufferAvailableChanged(false);
444 resetDecodingState();
445 setIsDecoding(false);
446 positionChanged(kInvalidPosition);
447 durationChanged(kInvalidDuration);
448}
449
450// ---------------------------------------------------------------------------
451
452// Parses and feeds as many complete encoded frames as possible from
453// m_inputBuffer starting at m_inputPos, advancing m_inputPos past each
454// consumed frame. Any trailing partial frame is left for the next call.
455// endOfInput says no more bytes will arrive, which is what lets the final FLAC
456// frame, the one with no following frame header to bound it, be emitted.
457void QWasmAudioDecoder::feedAvailableFrames(bool endOfInput)
458{
459 // FLAC audio frames follow the container header and the metadata blocks,
460 // which must be skipped rather than scanned, because a PICTURE block can
461 // hold arbitrary bytes that look like a frame header.
462 if (m_codec == Codec::Flac && !m_flacHeaderSkipped) {
463 const std::optional<qsizetype> audioStart =
464 AudioParsing::flacAudioOffset(asBytes(m_inputBuffer));
465 if (!audioStart)
466 return; // the metadata chain is incomplete, wait for more data
467 m_inputPos = qMax(m_inputPos, *audioStart);
468 m_flacHeaderSkipped = true;
469 }
470
471 while (true) {
472 std::optional<qsizetype> syncPos;
473 qsizetype frameSize = 0;
474 qsizetype syncWordSize = 4;
475
476 if (m_codec == Codec::Mp3) {
477 syncPos = AudioParsing::findMpegSync(asBytes(m_inputBuffer), m_inputPos);
478 if (syncPos)
479 frameSize = AudioParsing::mpegFrameSize(asBytes(m_inputBuffer), *syncPos);
480 } else if (m_codec == Codec::Aac) {
481 syncPos = AudioParsing::findAdtsSync(asBytes(m_inputBuffer), m_inputPos);
482 if (syncPos)
483 frameSize = AudioParsing::adtsFrameSize(asBytes(m_inputBuffer), *syncPos);
484 } else if (m_codec == Codec::Flac) {
485 // A FLAC frame has no length field, so it runs from one frame
486 // header to the next, and the last one runs to the end of input.
487 syncWordSize = 16; // the largest a FLAC frame header can be
488 syncPos = AudioParsing::findFlacSync(asBytes(m_inputBuffer), m_inputPos);
489 if (syncPos) {
490 const std::optional<qsizetype> nextSync =
491 AudioParsing::findFlacSync(asBytes(m_inputBuffer), *syncPos + 2);
492 if (nextSync) {
493 frameSize = *nextSync - *syncPos;
494 } else if (endOfInput) {
495 frameSize = m_inputBuffer.size() - *syncPos;
496 } else {
497 // The next frame header bounds this frame, so wait for it.
498 m_inputPos = *syncPos;
499 break;
500 }
501 }
502 }
503
504 if (!syncPos) {
505 // No sync in the remaining buffer, so keep back the bytes a header
506 // needs, in case it is split across two readyRead deliveries.
507 m_inputPos = qMax(m_inputPos, m_inputBuffer.size() - (syncWordSize - 1));
508 break;
509 }
510
511 if (frameSize <= 0) {
512 // Sync word found but header is invalid, so skip past it and retry.
513 m_inputPos = *syncPos + 1;
514 continue;
515 }
516
517 if (*syncPos + frameSize > m_inputBuffer.size()) {
518 // Header found but the full frame hasn't arrived yet.
519 m_inputPos = *syncPos;
520 break;
521 }
522
523 feedChunk(QByteArray(m_inputBuffer.constData() + *syncPos, frameSize));
524 m_inputPos = *syncPos + frameSize;
525
526 // Compact the buffer every megabyte to keep memory bounded for
527 // long-running or large-file streams.
528 if (m_inputPos > 1024 * 1024) {
529 m_inputBuffer.remove(0, m_inputPos);
530 m_inputPos = 0;
531 }
532 }
533}
534
535// Feeds one chunk of compressed data to the decoder.
536// m_byteOffset is used as the monotonically increasing chunk timestamp.
537void QWasmAudioDecoder::feedChunk(const QByteArray &chunk)
538{
539 // typed_memory_view creates a Uint8Array view into the WASM heap.
540 // slice() with no arguments copies it into a new ArrayBuffer, which is
541 // required because EncodedAudioChunk may hold a reference beyond this call.
542 emscripten::val dataView = emscripten::val(emscripten::typed_memory_view(
543 static_cast<size_t>(chunk.size()),
544 reinterpret_cast<const uint8_t *>(chunk.constData())));
545
546 emscripten::val chunkInit = emscripten::val::object();
547 chunkInit.set("type", emscripten::val("key"));
548 chunkInit.set("timestamp", m_byteOffset);
549 chunkInit.set("data", dataView.call<emscripten::val>("slice")["buffer"]);
550
551 m_decoder.call<void>("decode", emscripten::val::global("EncodedAudioChunk").new_(chunkInit));
552 m_byteOffset += chunk.size();
553}
554
555// Checks browser support for codec, then configures the decoder and starts
556// feeding chunks from the source device. Data that arrives in the device
557// while the async check is in flight stays buffered and is drained afterwards.
558// rawHeader is the peeked bytes used to extract the FLAC STREAMINFO description.
559void QWasmAudioDecoder::beginDecoding(Codec codec, const QByteArray &rawHeader)
560{
561 m_checkingSupport = true;
562
563 int sampleRate = m_audioFormat.isValid() ? m_audioFormat.sampleRate() : 0;
564 int numChannels = m_audioFormat.isValid() ? m_audioFormat.channelCount() : 0;
565 QByteArray flacDesc;
566 if (codec == Codec::Flac) {
567 flacDesc = flacDescription(rawHeader, sampleRate, numChannels);
568 if (const std::optional<std::chrono::milliseconds> duration = flacDuration(rawHeader))
569 durationChanged(*duration);
570 }
571 if (sampleRate <= 0)
572 sampleRate = 48000;
573 if (numChannels <= 0)
574 numChannels = 2;
575
576 auto generationPtr = m_generationPtr;
577 const int generation = *generationPtr;
578
579 emscripten::val supportConfig = emscripten::val::object();
580 supportConfig.set("codec", codecString(codec));
581 supportConfig.set("sampleRate", sampleRate);
582 supportConfig.set("numberOfChannels", numChannels);
583 if (!flacDesc.isEmpty()) {
584 emscripten::val descView = emscripten::val(emscripten::typed_memory_view(
585 static_cast<size_t>(flacDesc.size()),
586 reinterpret_cast<const uint8_t *>(flacDesc.constData())));
587 supportConfig.set("description", descView.call<emscripten::val>("slice"));
588 }
589 emscripten::val supportPromise = emscripten::val::global("AudioDecoder")
590 .call<emscripten::val>("isConfigSupported", supportConfig);
591
592 qstdweb::Promise(supportPromise)
593 .addThenFunction([this, generationPtr, generation, codec, sampleRate, numChannels, flacDesc](emscripten::val result) {
594 if (*generationPtr != generation)
595 return;
596 m_checkingSupport = false;
597 if (!result["supported"].as<bool>()) {
598 m_fallbackReason = QStringLiteral("WebCodecs does not support codec \"%1\"")
599 .arg(QLatin1StringView(codecString(codec)));
600 qWarning() << "QWasmAudioDecoder:" << m_fallbackReason
601 << "— will fall back to decodeAudioData";
602 m_useDecodeAudioData = true;
603 closeDecoder();
604 return;
605 }
606 m_codec = codec;
607 emscripten::val decoderConfig = emscripten::val::object();
608 decoderConfig.set("codec", codecString(codec));
609 decoderConfig.set("sampleRate", sampleRate);
610 decoderConfig.set("numberOfChannels", numChannels);
611 if (!flacDesc.isEmpty()) {
612 emscripten::val descView = emscripten::val(emscripten::typed_memory_view(
613 static_cast<size_t>(flacDesc.size()),
614 reinterpret_cast<const uint8_t *>(flacDesc.constData())));
615 decoderConfig.set("description", descView.call<emscripten::val>("slice"));
616 }
617 m_decoder.call<void>("configure", decoderConfig);
618 m_outputDrainTimer.start();
619 m_configured = true;
620 // Drain any bytes that arrived while the support check was in flight.
621 onSourceReadyRead();
622 })
623 .addCatchFunction([this, generationPtr, generation, codec](emscripten::val) {
624 if (*generationPtr != generation)
625 return;
626 m_checkingSupport = false;
627 m_fallbackReason = QStringLiteral("WebCodecs isConfigSupported rejected codec \"%1\"")
628 .arg(QLatin1StringView(codecString(codec)));
629 qWarning() << "QWasmAudioDecoder:" << m_fallbackReason
630 << "— will fall back to decodeAudioData";
631 m_useDecodeAudioData = true;
632 closeDecoder();
633 });
634}
635
636// Called whenever the source QIODevice signals that new bytes are available,
637// and also immediately from start() to drain bytes already buffered.
638void QWasmAudioDecoder::onSourceReadyRead()
639{
640 if (m_flushing || m_checkingSupport || !m_sourceDevice)
641 return;
642
643 // On the first call, peek the first bytes to identify the codec without
644 // consuming them. 42 bytes covers "fLaC" + STREAMINFO block header + data,
645 // which is needed to extract the FLAC description for isConfigSupported.
646 // If too few bytes have arrived yet, wait for the next signal.
647 if (!m_configured && !m_useDecodeAudioData) {
648 // Peek generously to capture all metadata blocks (STREAMINFO, SEEKTABLE,
649 // VORBIS_COMMENT, etc.) needed for the FLAC description field.
650 // For non-FLAC codecs 4 bytes is enough to sniff, so we over-peek harmlessly.
651 const QByteArray header = m_sourceDevice->peek(65536);
652 if (header.size() < 4)
653 return;
654
655 const Codec codec = AudioParsing::sniffCodec(asBytes(header));
656
657 if (codec == Codec::Unknown) {
658 // Unknown container. Accumulate everything and fall back to
659 // decodeAudioData.
660 m_fallbackReason = QStringLiteral("no known audio codec signature (%1)")
661 .arg(dataPrefixHint(header));
662 m_useDecodeAudioData = true;
663 return;
664 }
665 if (codec == Codec::Wav) {
666 handleError(QAudioDecoder::FormatError,
667 QStringLiteral("WAV is uncompressed; use QWaveDecoder directly"));
668 return;
669 }
670 if (codec == Codec::Vorbis) {
671 // No WebCodecs Vorbis decoder, so accumulate and use decodeAudioData.
672 m_codec = codec;
673 m_fallbackReason = QStringLiteral("WebCodecs has no Vorbis decoder");
674 m_useDecodeAudioData = true;
675 return;
676 }
677
678 // For FLAC, wait until all metadata blocks have arrived before proceeding.
679 if (codec == Codec::Flac && !AudioParsing::flacAudioOffset(asBytes(header)))
680 return;
681
682 // Verify codec support asynchronously. Data stays buffered in the device.
683 beginDecoding(codec, header);
684 return;
685 }
686
687 // Accumulate newly available bytes.
688 while (m_sourceDevice->bytesAvailable() > 0)
689 m_inputBuffer.append(m_sourceDevice->read(65536));
690
691 // For frame-parsed codecs (MP3, AAC), feed complete frames immediately as
692 // they arrive so the decoder makes progress without waiting for the source
693 // to close. For other codecs the buffer is fed all at once in onSourceDone().
694 if (AudioParsing::hasFrameParser(m_codec))
695 feedAvailableFrames(false);
696
697 // If the device is already at end, finalize without waiting for aboutToClose.
698 if (m_sourceDevice->atEnd())
699 onSourceDone();
700}
701
702// Called when the source device signals aboutToClose, or when atEnd() is
703// detected inside onSourceReadyRead().
704void QWasmAudioDecoder::onSourceDone()
705{
706 if (m_flushing || m_checkingSupport)
707 return;
708
709 // Disconnect before flushing so no further readyRead calls arrive.
710 if (m_sourceDevice)
711 disconnect(m_sourceDevice, nullptr, this, nullptr);
712
713 // Drain any bytes that arrived between the last readyRead and now.
714 if (m_sourceDevice) {
715 while (m_sourceDevice->bytesAvailable() > 0)
716 m_inputBuffer.append(m_sourceDevice->read(65536));
717 }
718
719 // Save the full compressed data before clearing, so tryDecodeAudioData()
720 // has it available whether we fall back now or later (from startFlush catch).
721 m_rawData = m_inputBuffer;
722
723 if (m_useDecodeAudioData) {
724 m_inputBuffer.clear();
725 m_inputPos = 0;
726 tryDecodeAudioData();
727 return;
728 }
729
730 if (AudioParsing::hasFrameParser(m_codec)) {
731 // Process any remaining complete frames. A trailing partial frame
732 // (e.g. truncated file) is silently discarded.
733 feedAvailableFrames(true);
734 } else {
735 // Opus, etc.: feed the accumulated buffer as one chunk.
736 if (m_inputPos < m_inputBuffer.size())
737 feedChunk(QByteArray(m_inputBuffer.constData() + m_inputPos,
738 m_inputBuffer.size() - m_inputPos));
739 }
740
741 m_inputBuffer.clear();
742 m_inputPos = 0;
743 startFlush();
744}
745
746// Calls decoder.flush() and, when the returned Promise resolves, delivers all
747// accumulated output buffers and signals completion.
748void QWasmAudioDecoder::startFlush()
749{
750 if (m_flushing || m_decoder.isUndefined())
751 return;
752 m_flushing = true;
753
754 auto generationPtr = m_generationPtr;
755 const int generation = *generationPtr;
756
757 qstdweb::Promise(m_decoder.call<emscripten::val>("flush"))
758 .addThenFunction([this, generationPtr, generation](emscripten::val) {
759 if (*generationPtr != generation)
760 return;
761 deliverOutputs();
762 // A bufferReady() slot may have stopped or restarted the decoder.
763 if (*generationPtr != generation)
764 return;
765 closeDecoder();
766 setIsDecoding(false);
767 finished();
768 })
769 .addCatchFunction([this, generationPtr, generation](emscripten::val err) {
770 if (*generationPtr != generation)
771 return;
772 QString errMsg;
773 if (err.isString())
774 errMsg = QString::fromStdString(err.as<std::string>());
775 else if (!err["message"].isUndefined())
776 errMsg = QString::fromStdString(err["message"].as<std::string>());
777 m_fallbackReason = QStringLiteral("WebCodecs decode failed")
778 + (errMsg.isEmpty() ? QString() : QStringLiteral(": ") + errMsg);
779 qWarning() << "QWasmAudioDecoder:" << m_fallbackReason
780 << "— falling back to decodeAudioData";
781 closeDecoder();
782 tryDecodeAudioData();
783 });
784}
785
786void QWasmAudioDecoder::deliverOutputs()
787{
788 if (m_decoder.isUndefined() || m_deliveringOutputs)
789 return;
790
791 emscripten::val outputs = m_decoder["_qtOutputs"];
792 const int count = outputs["length"].as<int>();
793 if (count == 0)
794 return;
795
796 const QScopedValueRollback deliveringGuard(m_deliveringOutputs, true);
797 // A slot connected to bufferReady() may call stop(), which closes every
798 // remaining AudioData, or stop() and start(), which also creates a new
799 // decoder. Either way the outputs below must not be touched again.
800 const int generation = *m_generationPtr;
801
802 for (int i = 0; i < count; ++i) {
803 emscripten::val output = outputs[i];
804
805 // Error entries have an _error string property. AudioData objects do not.
806 emscripten::val errorProp = output["_error"];
807 if (errorProp.isString()) {
808 handleError(QAudioDecoder::FormatError,
809 QStringLiteral("Decode error: ")
810 + QString::fromStdString(errorProp.as<std::string>()));
811 // handleError() called closeDecoder() which sets m_decoder to
812 // undefined, so stop iterating to avoid use-after-free.
813 return;
814 }
815
816 const int numChannels = output["numberOfChannels"].as<int>();
817 const int numFrames = output["numberOfFrames"].as<int>();
818 const int sampleRate = output["sampleRate"].as<int>();
819 // output["timestamp"] echoes back the synthetic byte offset given to
820 // the EncodedAudioChunk, so compute the real start time from the
821 // frames decoded so far.
822 const qint64 startTimeUs =
823 sampleRate > 0 ? m_decodedFrames * 1000000LL / sampleRate : 0;
824
825 // Allocate the receive buffer in C++, with no Module._malloc from JS.
826 const qint64 totalSamples = static_cast<qint64>(numChannels) * numFrames;
827 const qint64 totalBytes = totalSamples * static_cast<qint64>(sizeof(float));
828 QByteArray pcm(static_cast<qsizetype>(totalBytes), Qt::Uninitialized);
829
830 // typed_memory_view creates a Float32Array view directly into the WASM
831 // heap so copyTo() writes the decoded PCM without an extra copy.
832 emscripten::val destView = emscripten::val(emscripten::typed_memory_view(
833 static_cast<size_t>(totalSamples), // totalSamples fits size_t on wasm32
834 reinterpret_cast<float *>(pcm.data())));
835 emscripten::val copyConfig = emscripten::val::object();
836 copyConfig.set("planeIndex", 0);
837 copyConfig.set("format", emscripten::val("f32"));
838 output.call<void>("copyTo", destView, copyConfig);
839 output.call<void>("close");
840
841 QAudioFormat outputFormat;
842 outputFormat.setChannelCount(numChannels);
843 outputFormat.setSampleRate(sampleRate);
844 outputFormat.setSampleFormat(QAudioFormat::Float);
845
846 if (!m_formatEmitted) {
847 m_formatEmitted = true;
848 m_audioFormat = outputFormat;
849 formatChanged(outputFormat);
850 }
851
852 QAudioBuffer buffer(pcm, outputFormat, startTimeUs);
853 m_decodedFrames += numFrames;
854
855 const bool wasEmpty = m_pendingBuffers.isEmpty();
856 m_pendingBuffers.enqueue(std::move(buffer));
857 if (wasEmpty)
858 bufferAvailableChanged(true);
859 bufferReady();
860 if (*m_generationPtr != generation || m_decoder.isUndefined())
861 return;
862 }
863
864 // Remove only the entries handled above. The decoder can append more
865 // while signals are emitted if a slot runs a nested event loop.
866 outputs.call<void>("splice", 0, count);
867}
868
869// Falls back to Web Audio API AudioContext.decodeAudioData() when WebCodecs
870// fails or is unsupported. Takes m_rawData as input and delivers one
871// QAudioBuffer with the fully decoded interleaved PCM.
872void QWasmAudioDecoder::tryDecodeAudioData()
873{
874 if (m_rawData.isEmpty()) {
875 handleError(QAudioDecoder::FormatError,
876 decorateWithFallbackReason(
877 QStringLiteral("no data available for the decodeAudioData fallback")));
878 return;
879 }
880
881 // Copy compressed bytes into a JS ArrayBuffer.
882 emscripten::val uint8View = emscripten::val(emscripten::typed_memory_view(
883 static_cast<size_t>(m_rawData.size()),
884 reinterpret_cast<const uint8_t *>(m_rawData.constData())));
885 emscripten::val arrayBuffer = uint8View.call<emscripten::val>("slice")["buffer"];
886
887 // decodeAudioData resamples to the context's sample rate, which otherwise
888 // defaults to the output device's rate. Pin the context to the stream's own
889 // rate where it is known, so the decoded buffers keep the source's sample
890 // rate instead of silently becoming whatever the device runs at.
891 const int nativeRate = nativeSampleRate(m_codec, m_rawData);
892 emscripten::val audioCtx = emscripten::val::undefined();
893 if (nativeRate > 0) {
894 emscripten::val contextOptions = emscripten::val::object();
895 contextOptions.set("sampleRate", nativeRate);
896 audioCtx = emscripten::val::global("AudioContext").new_(contextOptions);
897 } else {
898 audioCtx = emscripten::val::global("AudioContext").new_();
899 }
900
901 auto generationPtr = m_generationPtr;
902 const int generation = *generationPtr;
903
904 qstdweb::Promise(audioCtx.call<emscripten::val>("decodeAudioData", arrayBuffer))
905 .addThenFunction([this, generationPtr, generation, audioCtx](emscripten::val audioBuffer) {
906 if (*generationPtr != generation) {
907 audioCtx.call<emscripten::val>("close");
908 return;
909 }
910
911 const int numChannels = audioBuffer["numberOfChannels"].as<int>();
912 const int numFrames = audioBuffer["length"].as<int>();
913 const int sampleRate = audioBuffer["sampleRate"].as<int>();
914
915 // Interleave per-channel Float32Arrays into one QByteArray.
916 const qint64 totalSamples = static_cast<qint64>(numChannels) * numFrames;
917 QByteArray pcm(totalSamples * static_cast<qint64>(sizeof(float)), Qt::Uninitialized);
918 auto *out = reinterpret_cast<float *>(pcm.data());
919
920 for (int ch = 0; ch < numChannels; ++ch) {
921 emscripten::val channelData = audioBuffer.call<emscripten::val>("getChannelData", ch);
922 // Copy the Float32Array into a temporary WASM buffer, then interleave.
923 QByteArray chanBuf(numFrames * static_cast<int>(sizeof(float)), Qt::Uninitialized);
924 emscripten::val destView = emscripten::val(emscripten::typed_memory_view(
925 static_cast<size_t>(numFrames),
926 reinterpret_cast<float *>(chanBuf.data())));
927 destView.call<void>("set", channelData);
928 const float *src = reinterpret_cast<const float *>(chanBuf.constData());
929 for (int i = 0; i < numFrames; ++i)
930 out[i * numChannels + ch] = src[i];
931 }
932
933 audioCtx.call<emscripten::val>("close");
934
935 QAudioFormat outputFormat;
936 outputFormat.setChannelCount(numChannels);
937 outputFormat.setSampleRate(sampleRate);
938 outputFormat.setSampleFormat(QAudioFormat::Float);
939
940 if (!m_formatEmitted) {
941 m_formatEmitted = true;
942 m_audioFormat = outputFormat;
943 formatChanged(outputFormat);
944 }
945
946 QAudioBuffer buffer(pcm, outputFormat, 0);
947 m_pendingBuffers.enqueue(std::move(buffer));
948 bufferAvailableChanged(true);
949 bufferReady();
950 durationChanged(std::chrono::milliseconds{ numFrames * 1000LL / sampleRate });
951
952 m_rawData.clear();
953 setIsDecoding(false);
954 finished();
955 })
956 .addCatchFunction([this, generationPtr, generation, audioCtx](emscripten::val err) {
957 if (*generationPtr != generation) {
958 audioCtx.call<emscripten::val>("close");
959 return;
960 }
961 audioCtx.call<emscripten::val>("close");
962 QString errMsg = QStringLiteral("decodeAudioData failed");
963 if (!err["message"].isUndefined())
964 errMsg += QStringLiteral(": ") + QString::fromStdString(err["message"].as<std::string>());
965 handleError(QAudioDecoder::FormatError, decorateWithFallbackReason(errMsg));
966 });
967}
968
969void QWasmAudioDecoder::closeDecoder()
970{
971 m_outputDrainTimer.stop();
972 if (!m_decoder.isUndefined()) {
973 // Close any AudioData objects that were never consumed (error paths).
974 emscripten::val outputs = m_decoder["_qtOutputs"];
975 const int length = outputs["length"].as<int>();
976 for (int i = 0; i < length; ++i) {
977 emscripten::val output = outputs[i];
978 if (!output["close"].isUndefined())
979 output.call<void>("close");
980 }
981 outputs.set("length", 0);
982
983 // Guard against closing an already-closed decoder (its error callback
984 // transitions the state to 'closed' before we get here).
985 if (m_decoder["state"].as<std::string>() != "closed")
986 m_decoder.call<void>("close");
987
988 m_decoder = emscripten::val::undefined();
989 }
990}
991
992// Returns the per-decode members to their initial values. Signals are left to
993// the caller, and decoded buffers already queued stay readable.
994void QWasmAudioDecoder::resetDecodingState()
995{
996 m_inputBuffer.clear();
997 m_inputPos = 0;
998 m_rawData.clear();
999 m_codec = Codec::Unknown;
1000 m_byteOffset = 0.0;
1001 m_decodedFrames = 0;
1002 m_checkingSupport = false;
1003 m_flushing = false;
1004 m_configured = false;
1005 m_useDecodeAudioData = false;
1006 m_flacHeaderSkipped = false;
1007 m_fallbackReason.clear();
1008}
1009
1010// Prefixes an error message from the decodeAudioData fallback with the reason
1011// the fallback was taken, so the reported error names the actual problem
1012// instead of only the last step that failed.
1013QString QWasmAudioDecoder::decorateWithFallbackReason(const QString &message) const
1014{
1015 if (m_fallbackReason.isEmpty())
1016 return message;
1017 return m_fallbackReason + QStringLiteral(", and ") + message;
1018}
1019
1020void QWasmAudioDecoder::handleError(QAudioDecoder::Error code, const QString &message)
1021{
1022 qWarning() << "QWasmAudioDecoder:" << message;
1023 // Invalidate pending promise and drain callbacks, so nothing from this
1024 // decode, such as finished() or a fallback result, arrives after error().
1025 ++(*m_generationPtr);
1026 if (m_sourceDevice)
1027 disconnect(m_sourceDevice, nullptr, this, nullptr);
1028 closeDecoder();
1029 resetDecodingState();
1030 // error() also clears isDecoding. Like the FFmpeg backend, the duration
1031 // and position of the failed decode are reset afterwards.
1032 error(code, message);
1033 durationChanged(kInvalidDuration);
1034 positionChanged(kInvalidPosition);
1035}
1036
1037QT_END_NAMESPACE