6#include <QtCore/qiodevice.h>
7#include <QtCore/qloggingcategory.h>
8#include <QtCore/qmimedatabase.h>
9#include <QtCore/qmutex.h>
10#include <QtCore/qthread.h>
11#include <QtCore/private/qcore_mac_p.h>
13#include "private/qcoreaudioutils_p.h"
15#include <AVFoundation/AVFoundation.h>
19Q_STATIC_LOGGING_CATEGORY(qLcAVFAudioDecoder,
"qt.multimedia.darwin.AVFAudioDecoder");
21using namespace Qt::Literals;
29 CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer);
30 if (!formatDescription)
32 const AudioStreamBasicDescription*
const asbd = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription);
33 QAudioFormat qtFormat = QCoreAudioUtils::toQAudioFormat(*asbd);
34 if (qtFormat.sampleFormat() == QAudioFormat::Unknown && asbd->mBitsPerChannel == 8)
35 qtFormat.setSampleFormat(QAudioFormat::UInt8);
36 if (!qtFormat.isValid())
40 size_t audioBufferListSize = 0;
41 OSStatus err = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer,
47 kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
52 CMBlockBufferRef blockBuffer =
nullptr;
53 AudioBufferList* audioBufferList = (AudioBufferList*) malloc(audioBufferListSize);
55 err = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer,
61 kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
64 free(audioBufferList);
69 for (UInt32 i = 0; i < audioBufferList->mNumberBuffers; i++)
71 AudioBuffer audioBuffer = audioBufferList->mBuffers[i];
72 abuf.push_back(QByteArray((
const char*)audioBuffer.mData, audioBuffer.mDataByteSize));
75 free(audioBufferList);
76 CFRelease(blockBuffer);
78 CMTime sampleStartTime = (CMSampleBufferGetPresentationTimeStamp(sampleBuffer));
79 float sampleStartTimeSecs = CMTimeGetSeconds(sampleStartTime);
81 return QAudioBuffer(abuf, qtFormat, qint64(sampleStartTimeSecs * 1000000));
84@interface AVFResourceReaderDelegate : NSObject <AVAssetResourceLoaderDelegate> {
85 AVFAudioDecoder *m_decoder;
89- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader
90 shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest;
94@implementation AVFResourceReaderDelegate
96- (id)initWithDecoder:(AVFAudioDecoder *)decoder
98 if (!(self = [super init]))
106-(BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader
107 shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest
109 Q_UNUSED(resourceLoader);
111 if (![loadingRequest.request.URL.scheme isEqualToString:@
"iodevice"])
114 QMutexLocker locker(&m_mutex);
116 QIODevice *device = m_decoder->sourceDevice();
120 device->seek(loadingRequest.dataRequest.requestedOffset);
121 if (loadingRequest.contentInformationRequest) {
122 loadingRequest.contentInformationRequest.contentLength = device->size();
123 loadingRequest.contentInformationRequest.byteRangeAccessSupported = YES;
126 if (loadingRequest.dataRequest) {
127 NSInteger requestedLength = loadingRequest.dataRequest.requestedLength;
128 int maxBytes = qMin(32 * 1024,
int(requestedLength));
130 buffer.resize(maxBytes);
131 NSInteger submitted = 0;
132 while (submitted < requestedLength) {
133 qint64 len = device->read(buffer.data(), maxBytes);
137 [loadingRequest.dataRequest respondWithData:[NSData dataWithBytes:buffer length:len]];
142 [loadingRequest finishLoading];
152NSDictionary *av_audio_settings_for_format(
const QAudioFormat &format)
154 float sampleRate = format.sampleRate();
155 int nChannels = format.channelCount();
156 int sampleSize = format.bytesPerSample() * 8;
157 BOOL isFloat = format.sampleFormat() == QAudioFormat::Float;
159 NSDictionary *audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
160 [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
161 [NSNumber numberWithFloat:sampleRate], AVSampleRateKey,
162 [NSNumber numberWithInt:nChannels], AVNumberOfChannelsKey,
163 [NSNumber numberWithInt:sampleSize], AVLinearPCMBitDepthKey,
164 [NSNumber numberWithBool:isFloat], AVLinearPCMIsFloatKey,
165 [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
166 [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
169 return audioSettings;
172QAudioFormat qt_format_for_audio_track(AVAssetTrack *track)
175 CMFormatDescriptionRef desc = (__bridge CMFormatDescriptionRef)track.formatDescriptions[0];
176 const AudioStreamBasicDescription*
const asbd =
177 CMAudioFormatDescriptionGetStreamBasicDescription(desc);
178 format = QCoreAudioUtils::toQAudioFormat(*asbd);
181 if (asbd->mBitsPerChannel == 0)
182 format.setSampleFormat(QAudioFormat::Int16);
196 [m_reader cancelReading];
200 [m_readerOutput release];
204AVFAudioDecoder::AVFAudioDecoder(QAudioDecoder *parent)
205 : QPlatformAudioDecoder(parent)
207 m_readingQueue = dispatch_queue_create(
"reader_queue", DISPATCH_QUEUE_SERIAL);
208 m_decodingQueue = dispatch_queue_create(
"decoder_queue", DISPATCH_QUEUE_SERIAL);
210 m_readerDelegate = [[AVFResourceReaderDelegate alloc] initWithDecoder:
this];
213AVFAudioDecoder::~AVFAudioDecoder()
217 [m_readerDelegate release];
220 dispatch_release(m_readingQueue);
221 dispatch_release(m_decodingQueue);
224QUrl AVFAudioDecoder::source()
const
229void AVFAudioDecoder::setSource(
const QUrl &fileName)
231 if (!m_device && m_source == fileName)
241 if (!m_source.isEmpty()) {
242 NSURL *nsURL = m_source.toNSURL();
243 m_asset = [[AVURLAsset alloc] initWithURL:nsURL options:nil];
249QIODevice *AVFAudioDecoder::sourceDevice()
const
254void AVFAudioDecoder::setSourceDevice(QIODevice *device)
256 if (m_device == device && m_source.isEmpty())
267 const QString ext = QMimeDatabase().mimeTypeForData(m_device).preferredSuffix();
268 const QString url = u"iodevice:///iodevice."_s + ext;
269 NSString *urlString = url.toNSString();
270 NSURL *nsURL = [NSURL URLWithString:urlString];
272 m_asset = [[AVURLAsset alloc] initWithURL:nsURL options:nil];
276 [m_asset.resourceLoader setDelegate:m_readerDelegate queue:m_decodingQueue];
282void AVFAudioDecoder::start()
284 if (m_decodingContext) {
285 qCDebug(qLcAVFAudioDecoder()) <<
"AVFAudioDecoder has been already started";
291 if (m_device && (!m_device->isOpen() || !m_device->isReadable())) {
292 processInvalidMedia(QAudioDecoder::ResourceError, tr(
"Unable to read from specified device"));
296 m_decodingContext = std::make_shared<DecodingContext>();
297 std::weak_ptr<DecodingContext> weakContext(m_decodingContext);
299 auto handleLoadingResult = [=,
this]() {
300 NSError *error = nil;
301 AVKeyValueStatus status = [m_asset statusOfValueForKey:@
"tracks" error:&error];
303 if (status == AVKeyValueStatusFailed) {
304 if (error.domain == NSURLErrorDomain)
305 processInvalidMedia(QAudioDecoder::ResourceError,
306 QString::fromNSString(error.localizedDescription));
308 processInvalidMedia(QAudioDecoder::FormatError,
309 tr(
"Could not load media source's tracks"));
310 }
else if (status != AVKeyValueStatusLoaded) {
311 qWarning() <<
"Unexpected AVKeyValueStatus:" << status;
319 [m_asset loadValuesAsynchronouslyForKeys:@[ @
"tracks" ]
320 completionHandler:[=,
this]() {
321 invokeWithDecodingContext(weakContext, handleLoadingResult);
325void AVFAudioDecoder::decBuffersCounter(uint val)
328 QMutexLocker locker(&m_buffersCounterMutex);
329 m_buffersCounter -= val;
332 Q_ASSERT(m_buffersCounter >= 0);
334 m_buffersCounterCondition.wakeAll();
337void AVFAudioDecoder::stop()
339 qCDebug(qLcAVFAudioDecoder()) <<
"stop decoding";
341 m_decodingContext.reset();
342 decBuffersCounter(m_cachedBuffers.size());
343 m_cachedBuffers.clear();
345 bufferAvailableChanged(
false);
352QAudioFormat AVFAudioDecoder::audioFormat()
const
357void AVFAudioDecoder::setAudioFormat(
const QAudioFormat &format)
359 if (m_format != format) {
361 formatChanged(m_format);
365QAudioBuffer AVFAudioDecoder::read()
367 if (m_cachedBuffers.empty())
368 return QAudioBuffer();
370 Q_ASSERT(m_cachedBuffers.size() > 0);
371 QAudioBuffer buffer = m_cachedBuffers.dequeue();
372 decBuffersCounter(1);
374 positionChanged(buffer.startTime() / 1000);
375 bufferAvailableChanged(!m_cachedBuffers.empty());
379void AVFAudioDecoder::processInvalidMedia(QAudioDecoder::Error errorCode,
380 const QString &errorString)
382 qCDebug(qLcAVFAudioDecoder()) <<
"Invalid media. Error code:" << errorCode
383 <<
"Description:" << errorString;
385 Q_ASSERT(QThread::currentThread() == thread());
387 error(
int(errorCode), errorString);
396void AVFAudioDecoder::onFinished()
398 m_decodingContext.reset();
404void AVFAudioDecoder::initAssetReaderImpl(AVAssetTrack *track, NSError *error)
406 Q_ASSERT(track !=
nullptr);
409 processInvalidMedia(QAudioDecoder::ResourceError, QString::fromNSString(error.localizedDescription));
413 QAudioFormat format = m_format.isValid() ? m_format : qt_format_for_audio_track(track);
414 if (!format.isValid()) {
415 processInvalidMedia(QAudioDecoder::FormatError, tr(
"Unsupported source format"));
419 durationChanged(CMTimeGetSeconds(track.timeRange.duration) * 1000);
421 NSDictionary *audioSettings = av_audio_settings_for_format(format);
423 AVAssetReaderTrackOutput *readerOutput =
424 [[AVAssetReaderTrackOutput alloc] initWithTrack:track outputSettings:audioSettings];
425 AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:m_asset error:&error];
426 auto cleanup = qScopeGuard([&] {
427 [readerOutput release];
432 processInvalidMedia(QAudioDecoder::ResourceError, QString::fromNSString(error.localizedDescription));
435 if (![reader canAddOutput:readerOutput]) {
436 processInvalidMedia(QAudioDecoder::ResourceError, tr(
"Failed to add asset reader output"));
440 [reader addOutput:readerOutput];
442 Q_ASSERT(m_decodingContext);
445 m_decodingContext->m_reader = reader;
446 m_decodingContext->m_readerOutput = readerOutput;
451void AVFAudioDecoder::initAssetReader()
453 qCDebug(qLcAVFAudioDecoder()) <<
"Init asset reader";
456 Q_ASSERT(QThread::currentThread() == thread());
458#if defined(Q_OS_VISIONOS)
459 [m_asset loadTracksWithMediaType:AVMediaTypeAudio completionHandler:[=](NSArray<AVAssetTrack *> *tracks, NSError *error) {
460 if (tracks && tracks.count > 0) {
461 if (AVAssetTrack *track = [tracks objectAtIndex:0])
462 QMetaObject::invokeMethod(
this, &AVFAudioDecoder::initAssetReaderImpl, Qt::QueuedConnection, track, error);
466 NSArray<AVAssetTrack *> *tracks = [m_asset tracksWithMediaType:AVMediaTypeAudio];
467 if (tracks && tracks.count > 0) {
468 if (AVAssetTrack *track = [tracks objectAtIndex:0])
469 initAssetReaderImpl(track,
nullptr );
475void AVFAudioDecoder::startReading()
477 Q_ASSERT(m_decodingContext);
478 Q_ASSERT(m_decodingContext->m_reader);
479 Q_ASSERT(QThread::currentThread() == thread());
482 if (![m_decodingContext->m_reader startReading]) {
483 processInvalidMedia(QAudioDecoder::ResourceError, tr(
"Could not start reading"));
489 std::weak_ptr<DecodingContext> weakContext = m_decodingContext;
494 auto copyNextSampleBuffer = [=,
this]() {
495 auto decodingContext = weakContext.lock();
496 if (!decodingContext)
499 QCFType<CMSampleBufferRef> sampleBuffer{
500 [decodingContext->m_readerOutput copyNextSampleBuffer],
505 dispatch_async(m_decodingQueue, [=,
this]() {
506 if (!weakContext.expired() && CMSampleBufferDataIsReady(sampleBuffer)) {
507 auto audioBuffer = handleNextSampleBuffer(sampleBuffer);
509 if (audioBuffer.isValid())
510 invokeWithDecodingContext(weakContext, [=,
this]() {
511 handleNewAudioBuffer(audioBuffer);
519 dispatch_async(m_readingQueue, [=,
this]() {
520 qCDebug(qLcAVFAudioDecoder()) <<
"start reading thread";
526 waitUntilBuffersCounterLessMax();
527 }
while (copyNextSampleBuffer());
530 invokeWithDecodingContext(weakContext, [
this]() { onFinished(); });
534void AVFAudioDecoder::waitUntilBuffersCounterLessMax()
536 if (m_buffersCounter >= MAX_BUFFERS_IN_QUEUE) {
539 QMutexLocker locker(&m_buffersCounterMutex);
541 while (m_buffersCounter >= MAX_BUFFERS_IN_QUEUE)
542 m_buffersCounterCondition.wait(&m_buffersCounterMutex);
546void AVFAudioDecoder::handleNewAudioBuffer(QAudioBuffer buffer)
548 m_cachedBuffers.enqueue(std::move(buffer));
551 Q_ASSERT(m_cachedBuffers.size() == m_buffersCounter);
553 bufferAvailableChanged(
true);
558
559
560
561
563void AVFAudioDecoder::invokeWithDecodingContext(std::weak_ptr<DecodingContext> weakContext, F &&f)
565 if (!weakContext.expired())
566 QMetaObject::invokeMethod(
567 this, [
this, f = std::forward<F>(f), weakContext = std::move(weakContext)]() {
570 if (
auto context = weakContext.lock(); context && context == m_decodingContext)
575#include "moc_avfaudiodecoder_p.cpp"
static constexpr int MAX_BUFFERS_IN_QUEUE
static QAudioBuffer handleNextSampleBuffer(CMSampleBufferRef sampleBuffer)
AVAssetReaderTrackOutput * m_readerOutput