/***************************************************************
 * Copyright (C) 2020, 2026, Val Doroshchuk <valbok@gmail.com> *
 *                                                             *
 * This file is part of QtAVPlayer.                            *
 * Free Qt Media Player based on FFmpeg.                       *
 ***************************************************************/

#ifndef QAVAUDIOOUTPUT_H
#define QAVAUDIOOUTPUT_H

#include <QtAVPlayer/qavaudioframe.h>
#include <QtAVPlayer/qtavplayerglobal.h>
#include <QAudioFormat>
#include <QObject>
#include <memory>
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
#include <QAudioSink>
#include <QAudioDevice>
#include <QMediaDevices>
using AudioOutput = QAudioSink;
using AudioDevice = QAudioDevice;
#else
#include <QAudioOutput>
using AudioOutput = QAudioOutput;
using AudioDevice = QAudioDeviceInfo;
#endif

QT_BEGIN_NAMESPACE

class QAVAudioOutputPrivate;
class Q_AVPLAYER_EXPORT QAVAudioOutput : public QObject
{
    Q_OBJECT
public:
    QAVAudioOutput(QObject *parent = nullptr);
    ~QAVAudioOutput();

    void setVolume(qreal v);
    qreal volume() const;
    // Sets the audio buffer size to value in bytes
    void setBufferSize(int bytes);
    int bufferSize() const;

    /**
     * Sets the audio device used for playback. Pass a default-constructed
     * AudioDevice to resume using the system default output device.
     */
    void setAudioDevice(const AudioDevice &device);
    AudioDevice audioDevice() const;

#if QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)
    void setChannelConfig(QAudioFormat::ChannelConfig);
    QAudioFormat::ChannelConfig channelConfig() const;
#endif

    /**
     * Adds the frame to the playing queue.
     * - If format of the frame has been changed,
     *   it will recreate internal audio output.
     * - If the format is not supported,
     *   it will use preferred one.
     * @return true if was successfully added to the queue.
     */
    bool play(const QAVAudioFrame &frame);

    // Clears playing queue
    void clearQueue();

    // Suspends reading from the queue
    void suspend();

    // Resumes reading from the queue
    void resume();

public Q_SLOTS:
    // No audio should be rendered if stopped even if play() is called
    void stop();

private:
    Q_DISABLE_COPY(QAVAudioOutput)
    Q_DECLARE_PRIVATE(QAVAudioOutput)
    std::unique_ptr<QAVAudioOutputPrivate> d_ptr;
};

QT_END_NAMESPACE

#endif
