/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "avfcamerasession_p.h"
#include "avfaudiopreviewdelegate_p.h"

QT_USE_NAMESPACE

@implementation AVFAudioPreviewDelegate
{
@private
    AVSampleBufferAudioRenderer *m_audioRenderer;
    AVFCameraSession *m_session;
    AVSampleBufferRenderSynchronizer *m_audioBufferSynchronizer;
    dispatch_queue_t m_audioPreviewQueue;
}

- (id)init
{
    if (self = [super init]) {
        m_session = nil;
        m_audioBufferSynchronizer = [[AVSampleBufferRenderSynchronizer alloc] init];
        m_audioRenderer = [[AVSampleBufferAudioRenderer alloc] init];
        [m_audioBufferSynchronizer addRenderer:m_audioRenderer];
        return self;
    }
    return nil;
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput
        didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
        fromConnection:(AVCaptureConnection *)connection
{
    Q_UNUSED(connection);
    Q_ASSERT(m_session);

    if (!CMSampleBufferDataIsReady(sampleBuffer)) {
        qWarning() << Q_FUNC_INFO << "sample buffer is not ready, skipping.";
        return;
    }

    CFRetain(sampleBuffer);

    dispatch_async(m_audioPreviewQueue, ^{
        [self renderAudioSampleBuffer:sampleBuffer];
        CFRelease(sampleBuffer);
    });
}

- (void)renderAudioSampleBuffer:(CMSampleBufferRef)sampleBuffer
{
    Q_ASSERT(sampleBuffer);
    Q_ASSERT(m_session);

    if (m_audioBufferSynchronizer && m_audioRenderer) {
        [m_audioRenderer enqueueSampleBuffer:sampleBuffer];
        if (m_audioBufferSynchronizer.rate == 0)
            [m_audioBufferSynchronizer setRate:1 time:CMSampleBufferGetPresentationTimeStamp(sampleBuffer)];
    }
}

- (void)resetAudioPreviewDelegate
{
    [m_session->audioOutput() setSampleBufferDelegate:self queue:m_audioPreviewQueue];
}

- (void)setupWithCaptureSession: (AVFCameraSession*)session
        audioOutputDevice: (NSString*)deviceId
{
    m_session = session;

    m_audioPreviewQueue = dispatch_queue_create("audio-preview-queue", nullptr);
    [m_session->audioOutput() setSampleBufferDelegate:self queue:m_audioPreviewQueue];
#ifdef Q_OS_MACOS
    m_audioRenderer.audioOutputDeviceUniqueID = deviceId;
#endif
}

- (void)setVolume: (float)volume
{
    m_audioRenderer.volume = volume;
}

- (void)setMuted: (bool)muted
{
    m_audioRenderer.muted = muted;
}

-(void)dealloc {
    m_session = nil;
    [m_audioRenderer release];
    [m_audioBufferSynchronizer release];
    dispatch_release(m_audioPreviewQueue);

    [super dealloc];
}

@end
