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#import <AVFoundation/AVFoundation.h>
19Q_STATIC_LOGGING_CATEGORY(qLcAVFAudioDecoder,
"qt.multimedia.darwin.AVFAudioDecoder");
21using namespace Qt::Literals;
24 const QCFType<CMSampleBufferRef> &sampleBuffer)
30 auto validateFormat = [&] {
31 CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer);
32 if (!formatDescription)
34 const AudioStreamBasicDescription *
const asbd =
35 CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription);
38 return qtFormat == QCoreAudioUtils::toPreferredQAudioFormat(*asbd);
41 Q_ASSERT(validateFormat());
44 size_t audioBufferListSize = 0;
45 OSStatus err = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer,
51 kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
56 QCFType<CMBlockBufferRef> blockBuffer;
57 AudioBufferList* audioBufferList = (AudioBufferList*) malloc(audioBufferListSize);
59 err = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer,
65 kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
68 free(audioBufferList);
73 for (UInt32 i = 0; i < audioBufferList->mNumberBuffers; i++)
75 AudioBuffer audioBuffer = audioBufferList->mBuffers[i];
76 abuf.push_back(QByteArray((
const char*)audioBuffer.mData, audioBuffer.mDataByteSize));
79 free(audioBufferList);
81 CMTime sampleStartTime = (CMSampleBufferGetPresentationTimeStamp(sampleBuffer));
82 float sampleStartTimeSecs = CMTimeGetSeconds(sampleStartTime);
84 return QAudioBuffer(abuf, qtFormat, qint64(sampleStartTimeSecs * 1000000));
87@interface AVFResourceReaderDelegate : NSObject <AVAssetResourceLoaderDelegate> {
88 AVFAudioDecoder *m_decoder;
92- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader
93 shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest;
99@implementation AVFResourceReaderDelegate
101- (id)initWithDecoder:(AVFAudioDecoder *)decoder
103 if (!(self = [super init]))
111-(BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader
112 shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest
114 Q_UNUSED(resourceLoader);
116 if (![loadingRequest.request.URL.scheme isEqualToString:@
"iodevice"])
119 std::lock_guard locker(m_mutex);
121 QIODevice *device = m_decoder ? m_decoder->sourceDevice() :
nullptr;
125 device->seek(loadingRequest.dataRequest.requestedOffset);
126 if (loadingRequest.contentInformationRequest) {
127 loadingRequest.contentInformationRequest.contentLength = device->size();
128 loadingRequest.contentInformationRequest.byteRangeAccessSupported = YES;
131 if (loadingRequest.dataRequest) {
132 NSInteger requestedLength = loadingRequest.dataRequest.requestedLength;
133 int maxBytes = qMin(32 * 1024,
int(requestedLength));
135 buffer.resize(maxBytes);
136 NSInteger submitted = 0;
137 while (submitted < requestedLength) {
138 qint64 len = device->read(buffer.data(), maxBytes);
142 [loadingRequest.dataRequest respondWithData:[NSData dataWithBytes:buffer.constData()
148 [loadingRequest finishLoading];
156 std::lock_guard locker(m_mutex);
164NSDictionary *av_audio_settings_for_format(
const QAudioFormat &format)
166 float sampleRate = format.sampleRate();
167 int nChannels = format.channelCount();
168 int sampleSize = format.bytesPerSample() * 8;
169 BOOL isFloat = format.sampleFormat() == QAudioFormat::Float;
171 NSDictionary *audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
172 [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
173 [NSNumber numberWithFloat:sampleRate], AVSampleRateKey,
174 [NSNumber numberWithInt:nChannels], AVNumberOfChannelsKey,
175 [NSNumber numberWithInt:sampleSize], AVLinearPCMBitDepthKey,
176 [NSNumber numberWithBool:isFloat], AVLinearPCMIsFloatKey,
177 [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
178 [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
181 return audioSettings;
184QAudioFormat qt_format_for_audio_track(AVAssetTrack *track)
186 CMFormatDescriptionRef desc = (__bridge CMFormatDescriptionRef)track.formatDescriptions[0];
187 const AudioStreamBasicDescription*
const asbd =
188 CMAudioFormatDescriptionGetStreamBasicDescription(desc);
189 return QCoreAudioUtils::toPreferredQAudioFormat(*asbd);
202 [m_reader cancelReading];
206 [m_readerOutput release];
210AVFAudioDecoder::AVFAudioDecoder(QAudioDecoder *parent)
211 : QPlatformAudioDecoder(parent)
213 m_readingQueue = dispatch_queue_create(
"reader_queue", DISPATCH_QUEUE_SERIAL);
214 m_decodingQueue = dispatch_queue_create(
"decoder_queue", DISPATCH_QUEUE_SERIAL);
216 m_readerDelegate = [[AVFResourceReaderDelegate alloc] initWithDecoder:
this];
217 Q_ASSERT(m_readerDelegate);
220AVFAudioDecoder::~AVFAudioDecoder()
224 [m_readerDelegate clearDecoder];
225 [m_readerDelegate release];
229 dispatch_release(m_readingQueue);
230 dispatch_release(m_decodingQueue);
233QUrl AVFAudioDecoder::source()
const
238void AVFAudioDecoder::setSource(
const QUrl &fileName)
240 if (!m_device && m_source == fileName)
250 if (!m_source.isEmpty()) {
251 NSURL *nsURL = m_source.toNSURL();
252 m_asset = [[AVURLAsset alloc] initWithURL:nsURL options:nil];
258QIODevice *AVFAudioDecoder::sourceDevice()
const
263void AVFAudioDecoder::setSourceDevice(QIODevice *device)
265 if (m_device == device && m_source.isEmpty())
276 const QString ext = QMimeDatabase().mimeTypeForData(m_device).preferredSuffix();
277 const QString url = u"iodevice:///iodevice."_s + ext;
278 NSString *
_Nonnull urlString = url.toNSString();
279 NSURL *nsURL = [NSURL URLWithString:urlString];
282 processInvalidMedia(QAudioDecoder::FormatError,
283 tr(
"Failed to create URL for the device"));
286 m_asset = [[AVURLAsset alloc] initWithURL:nsURL options:nil];
290 [m_asset.resourceLoader setDelegate:m_readerDelegate queue:m_decodingQueue];
296void AVFAudioDecoder::start()
298 if (m_decodingContext) {
299 qCDebug(qLcAVFAudioDecoder()) <<
"AVFAudioDecoder has been already started";
305 if (m_device && (!m_device->isOpen() || !m_device->isReadable())) {
306 processInvalidMedia(QAudioDecoder::ResourceError, tr(
"Unable to read from specified device"));
310 m_decodingContext = std::make_shared<DecodingContext>();
311 std::weak_ptr<DecodingContext> weakContext(m_decodingContext);
313 auto handleLoadingResult = [=,
this]() {
314 NSError *error = nil;
315 AVKeyValueStatus status = [m_asset statusOfValueForKey:@
"tracks" error:&error];
317 if (status == AVKeyValueStatusFailed) {
318 if (error.domain == NSURLErrorDomain)
319 processInvalidMedia(QAudioDecoder::ResourceError,
320 QString::fromNSString(error.localizedDescription));
322 processInvalidMedia(QAudioDecoder::FormatError,
323 tr(
"Could not load media source's tracks"));
324 }
else if (status != AVKeyValueStatusLoaded) {
325 qWarning() <<
"Unexpected AVKeyValueStatus:" << status;
333 [m_asset loadValuesAsynchronouslyForKeys:@[ @
"tracks" ]
334 completionHandler:[=,
this]() {
335 invokeWithDecodingContext(weakContext, handleLoadingResult);
339void AVFAudioDecoder::decBuffersCounter(uint val)
342 QMutexLocker locker(&m_buffersCounterMutex);
343 m_buffersCounter -= val;
346 Q_ASSERT(m_buffersCounter >= 0);
348 m_buffersCounterCondition.wakeAll();
351void AVFAudioDecoder::stop()
353 qCDebug(qLcAVFAudioDecoder()) <<
"stop decoding";
355 m_decodingContext.reset();
356 decBuffersCounter(m_cachedBuffers.size());
357 m_cachedBuffers.clear();
359 bufferAvailableChanged(
false);
366QAudioFormat AVFAudioDecoder::audioFormat()
const
371void AVFAudioDecoder::setAudioFormat(
const QAudioFormat &format)
373 if (m_format != format) {
375 formatChanged(m_format);
379QAudioBuffer AVFAudioDecoder::read()
381 if (m_cachedBuffers.empty())
382 return QAudioBuffer();
384 Q_ASSERT(m_cachedBuffers.size() > 0);
385 QAudioBuffer buffer = m_cachedBuffers.dequeue();
386 decBuffersCounter(1);
388 positionChanged(buffer.startTime() / 1000);
389 bufferAvailableChanged(!m_cachedBuffers.empty());
393void AVFAudioDecoder::processInvalidMedia(QAudioDecoder::Error errorCode,
394 const QString &errorString)
396 qCDebug(qLcAVFAudioDecoder()) <<
"Invalid media. Error code:" << errorCode
397 <<
"Description:" << errorString;
399 Q_ASSERT(QThread::currentThread() == thread());
401 error(
int(errorCode), errorString);
410void AVFAudioDecoder::onFinished()
412 m_decodingContext.reset();
418void AVFAudioDecoder::initAssetReaderImpl(AVAssetTrack *track, NSError *error)
420 Q_ASSERT(track !=
nullptr);
423 processInvalidMedia(QAudioDecoder::ResourceError, QString::fromNSString(error.localizedDescription));
427 QAudioFormat format = m_format.isValid() ? m_format : qt_format_for_audio_track(track);
428 if (!format.isValid()) {
429 processInvalidMedia(QAudioDecoder::FormatError, tr(
"Unsupported source format"));
433 durationChanged(CMTimeGetSeconds(track.timeRange.duration) * 1000);
435 NSDictionary *audioSettings = av_audio_settings_for_format(format);
437 AVAssetReaderTrackOutput *readerOutput =
438 [[AVAssetReaderTrackOutput alloc] initWithTrack:track outputSettings:audioSettings];
439 AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:m_asset error:&error];
440 auto cleanup = qScopeGuard([&] {
441 [readerOutput release];
446 processInvalidMedia(QAudioDecoder::ResourceError, QString::fromNSString(error.localizedDescription));
449 if (![reader canAddOutput:readerOutput]) {
450 processInvalidMedia(QAudioDecoder::ResourceError, tr(
"Failed to add asset reader output"));
454 [reader addOutput:readerOutput];
456 Q_ASSERT(m_decodingContext);
459 m_decodingContext->m_reader = reader;
460 m_decodingContext->m_readerOutput = readerOutput;
465void AVFAudioDecoder::initAssetReader()
467 qCDebug(qLcAVFAudioDecoder()) <<
"Init asset reader";
470 Q_ASSERT(QThread::currentThread() == thread());
472#if defined(Q_OS_VISIONOS)
473 [m_asset loadTracksWithMediaType:AVMediaTypeAudio completionHandler:[=](NSArray<AVAssetTrack *> *tracks, NSError *error) {
474 if (tracks && tracks.count > 0) {
475 if (AVAssetTrack *track = [tracks objectAtIndex:0])
476 QMetaObject::invokeMethod(
this, &AVFAudioDecoder::initAssetReaderImpl, Qt::QueuedConnection, track, error);
480 NSArray<AVAssetTrack *> *tracks = [m_asset tracksWithMediaType:AVMediaTypeAudio];
481 if (tracks && tracks.count > 0) {
482 if (AVAssetTrack *track = [tracks objectAtIndex:0])
483 initAssetReaderImpl(track,
nullptr );
489void AVFAudioDecoder::startReading(QAudioFormat format)
491 Q_ASSERT(m_decodingContext);
492 Q_ASSERT(m_decodingContext->m_reader);
493 Q_ASSERT(QThread::currentThread() == thread());
496 if (![m_decodingContext->m_reader startReading]) {
497 processInvalidMedia(QAudioDecoder::ResourceError, tr(
"Could not start reading"));
503 std::weak_ptr<DecodingContext> weakContext = m_decodingContext;
508 auto copyNextSampleBuffer = [=,
this]() {
509 auto decodingContext = weakContext.lock();
510 if (!decodingContext)
513 QCFType<CMSampleBufferRef> sampleBuffer{
514 [decodingContext->m_readerOutput copyNextSampleBuffer],
519 dispatch_async(m_decodingQueue, [=,
this]() {
520 if (!weakContext.expired() && CMSampleBufferDataIsReady(sampleBuffer)) {
521 auto audioBuffer = handleNextSampleBuffer(format, sampleBuffer);
523 if (audioBuffer.isValid())
524 invokeWithDecodingContext(weakContext, [=,
this]() {
525 handleNewAudioBuffer(audioBuffer);
533 dispatch_async(m_readingQueue, [=,
this]() {
534 qCDebug(qLcAVFAudioDecoder()) <<
"start reading thread";
540 waitUntilBuffersCounterLessMax();
541 }
while (copyNextSampleBuffer());
544 invokeWithDecodingContext(weakContext, [
this]() { onFinished(); });
548void AVFAudioDecoder::waitUntilBuffersCounterLessMax()
550 if (m_buffersCounter >= MAX_BUFFERS_IN_QUEUE) {
553 QMutexLocker locker(&m_buffersCounterMutex);
555 while (m_buffersCounter >= MAX_BUFFERS_IN_QUEUE)
556 m_buffersCounterCondition.wait(&m_buffersCounterMutex);
560void AVFAudioDecoder::handleNewAudioBuffer(QAudioBuffer buffer)
562 m_cachedBuffers.enqueue(std::move(buffer));
565 Q_ASSERT(m_cachedBuffers.size() == m_buffersCounter);
567 bufferAvailableChanged(
true);
572
573
574
575
577void AVFAudioDecoder::invokeWithDecodingContext(std::weak_ptr<DecodingContext> weakContext, F &&f)
579 if (!weakContext.expired())
580 QMetaObject::invokeMethod(
581 this, [
this, f = std::forward<F>(f), weakContext = std::move(weakContext)]() {
584 if (
auto context = weakContext.lock(); context && context == m_decodingContext)
589#include "moc_avfaudiodecoder_p.cpp"
static constexpr int MAX_BUFFERS_IN_QUEUE
static QAudioBuffer handleNextSampleBuffer(QAudioFormat qtFormat, const QCFType< CMSampleBufferRef > &sampleBuffer)
AVAssetReaderTrackOutput * m_readerOutput