summaryrefslogtreecommitdiff
path: root/src/multimedia/audio/qaudioinput_mac_p.cpp
blob: c3d2ae24dc846009718a7f965460233051828e59 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtMultimedia module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of other Qt classes.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtCore/qendian.h>
#include <QtCore/qtimer.h>
#include <QtCore/qdebug.h>

#include <QtMultimedia/qaudioinput.h>

#include "qaudio_mac_p.h"
#include "qaudioinput_mac_p.h"
#include "qaudiodeviceinfo_mac_p.h"

QT_BEGIN_NAMESPACE


namespace QtMultimediaInternal
{

static const int default_buffer_size = 4 * 1024;

class QAudioBufferList
{
public:
    QAudioBufferList(AudioStreamBasicDescription const& streamFormat):
        owner(false),
        sf(streamFormat)
    {
        const bool isInterleaved = (sf.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0;
        const int numberOfBuffers = isInterleaved ? 1 : sf.mChannelsPerFrame;

        dataSize = 0;

        bfs = reinterpret_cast<AudioBufferList*>(qMalloc(sizeof(AudioBufferList) +
                                                                (sizeof(AudioBuffer) * numberOfBuffers)));

        bfs->mNumberBuffers = numberOfBuffers;
        for (int i = 0; i < numberOfBuffers; ++i) {
            bfs->mBuffers[i].mNumberChannels = isInterleaved ? numberOfBuffers : 1;
            bfs->mBuffers[i].mDataByteSize = 0;
            bfs->mBuffers[i].mData = 0;
        }
    }

    QAudioBufferList(AudioStreamBasicDescription const& streamFormat, char* buffer, int bufferSize):
        owner(false),
        sf(streamFormat),
        bfs(0)
    {
        dataSize = bufferSize;

        bfs = reinterpret_cast<AudioBufferList*>(qMalloc(sizeof(AudioBufferList) + sizeof(AudioBuffer)));

        bfs->mNumberBuffers = 1;
        bfs->mBuffers[0].mNumberChannels = 1;
        bfs->mBuffers[0].mDataByteSize = dataSize;
        bfs->mBuffers[0].mData = buffer;
    }

    QAudioBufferList(AudioStreamBasicDescription const& streamFormat, int framesToBuffer):
        owner(true),
        sf(streamFormat),
        bfs(0)
    {
        const bool isInterleaved = (sf.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0;
        const int numberOfBuffers = isInterleaved ? 1 : sf.mChannelsPerFrame;

        dataSize = framesToBuffer * sf.mBytesPerFrame;

        bfs = reinterpret_cast<AudioBufferList*>(qMalloc(sizeof(AudioBufferList) +
                                                                (sizeof(AudioBuffer) * numberOfBuffers)));
        bfs->mNumberBuffers = numberOfBuffers;
        for (int i = 0; i < numberOfBuffers; ++i) {
            bfs->mBuffers[i].mNumberChannels = isInterleaved ? numberOfBuffers : 1;
            bfs->mBuffers[i].mDataByteSize = dataSize;
            bfs->mBuffers[i].mData = qMalloc(dataSize);
        }
    }

    ~QAudioBufferList()
    {
        if (owner) {
            for (UInt32 i = 0; i < bfs->mNumberBuffers; ++i)
                qFree(bfs->mBuffers[i].mData);
        }

        qFree(bfs);
    }

    AudioBufferList* audioBufferList() const
    {
        return bfs;
    }

    char* data(int buffer = 0) const
    {
        return static_cast<char*>(bfs->mBuffers[buffer].mData);
    }

    qint64 bufferSize(int buffer = 0) const
    {
        return bfs->mBuffers[buffer].mDataByteSize;
    }

    int frameCount(int buffer = 0) const
    {
        return bfs->mBuffers[buffer].mDataByteSize / sf.mBytesPerFrame;
    }

    int packetCount(int buffer = 0) const
    {
        return bfs->mBuffers[buffer].mDataByteSize / sf.mBytesPerPacket;
    }

    int packetSize() const
    {
        return sf.mBytesPerPacket;
    }

    void reset()
    {
        for (UInt32 i = 0; i < bfs->mNumberBuffers; ++i) {
            bfs->mBuffers[i].mDataByteSize = dataSize;
            bfs->mBuffers[i].mData = 0;
        }
    }

private:
    bool    owner;
    int     dataSize;
    AudioStreamBasicDescription sf;
    AudioBufferList* bfs;
};

class QAudioPacketFeeder
{
public:
    QAudioPacketFeeder(QAudioBufferList* abl):
        audioBufferList(abl)
    {
        totalPackets = audioBufferList->packetCount();
        position = 0;
    }

    bool feed(AudioBufferList& dst, UInt32& packetCount)
    {
        if (position == totalPackets) {
            dst.mBuffers[0].mDataByteSize = 0;
            packetCount = 0;
            return false;
        }

        if (totalPackets - position < packetCount)
            packetCount = totalPackets - position;

        dst.mBuffers[0].mDataByteSize = packetCount * audioBufferList->packetSize();
        dst.mBuffers[0].mData = audioBufferList->data() + (position * audioBufferList->packetSize());

        position += packetCount;

        return true;
    }

    bool empty() const
    {
        return position == totalPackets;
    }

private:
    UInt32 totalPackets;
    UInt32 position;
    QAudioBufferList*   audioBufferList;
};

class QAudioInputBuffer : public QObject
{
    Q_OBJECT

public:
    QAudioInputBuffer(int bufferSize,
                        int maxPeriodSize,
                        AudioStreamBasicDescription const& inputFormat,
                        AudioStreamBasicDescription const& outputFormat,
                        QObject* parent):
        QObject(parent),
        m_deviceError(false),
        m_audioConverter(0),
        m_inputFormat(inputFormat),
        m_outputFormat(outputFormat)
    {
        m_maxPeriodSize = maxPeriodSize;
        m_periodTime = m_maxPeriodSize / m_outputFormat.mBytesPerFrame * 1000 / m_outputFormat.mSampleRate;
        m_buffer = new QAudioRingBuffer(bufferSize + (bufferSize % maxPeriodSize == 0 ? 0 : maxPeriodSize - (bufferSize % maxPeriodSize)));
        m_inputBufferList = new QAudioBufferList(m_inputFormat);

        m_flushTimer = new QTimer(this);
        connect(m_flushTimer, SIGNAL(timeout()), SLOT(flushBuffer()));

        if (toQAudioFormat(inputFormat) != toQAudioFormat(outputFormat)) {
            if (AudioConverterNew(&m_inputFormat, &m_outputFormat, &m_audioConverter) != noErr) {
                qWarning() << "QAudioInput: Unable to create an Audio Converter";
                m_audioConverter = 0;
            }
        }
    }

    ~QAudioInputBuffer()
    {
        delete m_buffer;
    }

    qint64 renderFromDevice(AudioUnit audioUnit,
                             AudioUnitRenderActionFlags* ioActionFlags,
                             const AudioTimeStamp* inTimeStamp,
                             UInt32 inBusNumber,
                             UInt32 inNumberFrames)
    {
        const bool  pullMode = m_device == 0;

        OSStatus    err;
        qint64      framesRendered = 0;

        m_inputBufferList->reset();
        err = AudioUnitRender(audioUnit,
                                ioActionFlags,
                                inTimeStamp,
                                inBusNumber,
                                inNumberFrames,
                                m_inputBufferList->audioBufferList());

        if (m_audioConverter != 0) {
            QAudioPacketFeeder  feeder(m_inputBufferList);

            int     copied = 0;
            const int available = m_buffer->free();

            while (err == noErr && !feeder.empty()) {
                QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(available);

                if (region.second == 0)
                    break;

                AudioBufferList     output;
                output.mNumberBuffers = 1;
                output.mBuffers[0].mNumberChannels = 1;
                output.mBuffers[0].mDataByteSize = region.second;
                output.mBuffers[0].mData = region.first;

                UInt32  packetSize = region.second / m_outputFormat.mBytesPerPacket;
                err = AudioConverterFillComplexBuffer(m_audioConverter,
                                                      converterCallback,
                                                      &feeder,
                                                      &packetSize,
                                                      &output,
                                                      0);
                region.second = output.mBuffers[0].mDataByteSize;
                copied += region.second;

                m_buffer->releaseWriteRegion(region);
            }

            framesRendered += copied / m_outputFormat.mBytesPerFrame;
        }
        else {
            const int available = m_inputBufferList->bufferSize();
            bool    wecan = true;
            int     copied = 0;

            while (wecan && copied < available) {
                QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(available - copied);

                if (region.second > 0) {
                    memcpy(region.first, m_inputBufferList->data() + copied, region.second);
                    copied += region.second;
                }
                else
                    wecan = false;

                m_buffer->releaseWriteRegion(region);
            }

            framesRendered = copied / m_outputFormat.mBytesPerFrame;
        }

        if (pullMode && framesRendered > 0)
            emit readyRead();

        return framesRendered;
    }

    qint64 readBytes(char* data, qint64 len)
    {
        bool    wecan = true;
        qint64  bytesCopied = 0;

        len -= len % m_maxPeriodSize;
        while (wecan && bytesCopied < len) {
            QAudioRingBuffer::Region region = m_buffer->acquireReadRegion(len - bytesCopied);

            if (region.second > 0) {
                memcpy(data + bytesCopied, region.first, region.second);
                bytesCopied += region.second;
            }
            else
                wecan = false;

            m_buffer->releaseReadRegion(region);
        }

        return bytesCopied;
    }

    void setFlushDevice(QIODevice* device)
    {
        if (m_device != device)
            m_device = device;
    }

    void startFlushTimer()
    {
        if (m_device != 0) {
            m_flushTimer->start((m_buffer->size() - (m_maxPeriodSize * 2)) / m_maxPeriodSize * m_periodTime);
        }
    }

    void stopFlushTimer()
    {
        m_flushTimer->stop();
    }

    void flush(bool all = false)
    {
        if (m_device == 0)
            return;

        const int used = m_buffer->used();
        const int readSize = all ? used : used - (used % m_maxPeriodSize);

        if (readSize > 0) {
            bool    wecan = true;
            int     flushed = 0;

            while (!m_deviceError && wecan && flushed < readSize) {
                QAudioRingBuffer::Region region = m_buffer->acquireReadRegion(readSize - flushed);

                if (region.second > 0) {
                    int bytesWritten = m_device->write(region.first, region.second);
                    if (bytesWritten < 0) {
                        stopFlushTimer();
                        m_deviceError = true;
                    }
                    else {
                        region.second = bytesWritten;
                        flushed += bytesWritten;
                        wecan = bytesWritten != 0;
                    }
                }
                else
                    wecan = false;

                m_buffer->releaseReadRegion(region);
            }
        }
    }

    void reset()
    {
        m_buffer->reset();
        m_deviceError = false;
    }

    int available() const
    {
        return m_buffer->free();
    }

    int used() const
    {
        return m_buffer->used();
    }

signals:
    void readyRead();

private slots:
    void flushBuffer()
    {
        flush();
    }

private:
    bool        m_deviceError;
    int         m_maxPeriodSize;
    int         m_periodTime;
    QIODevice*  m_device;
    QTimer*     m_flushTimer;
    QAudioRingBuffer*   m_buffer;
    QAudioBufferList*   m_inputBufferList;
    AudioConverterRef   m_audioConverter;
    AudioStreamBasicDescription m_inputFormat;
    AudioStreamBasicDescription m_outputFormat;

    const static OSStatus as_empty = 'qtem';

    // Converter callback
    static OSStatus converterCallback(AudioConverterRef inAudioConverter,
                                UInt32* ioNumberDataPackets,
                                AudioBufferList* ioData,
                                AudioStreamPacketDescription** outDataPacketDescription,
                                void* inUserData)
    {
        Q_UNUSED(inAudioConverter);
        Q_UNUSED(outDataPacketDescription);

        QAudioPacketFeeder* feeder = static_cast<QAudioPacketFeeder*>(inUserData);

        if (!feeder->feed(*ioData, *ioNumberDataPackets))
            return as_empty;

        return noErr;
    }
};


class MacInputDevice : public QIODevice
{
    Q_OBJECT

public:
    MacInputDevice(QAudioInputBuffer* audioBuffer, QObject* parent):
        QIODevice(parent),
        m_audioBuffer(audioBuffer)
    {
        open(QIODevice::ReadOnly | QIODevice::Unbuffered);
        connect(m_audioBuffer, SIGNAL(readyRead()), SIGNAL(readyRead()));
    }

    qint64 readData(char* data, qint64 len)
    {
        return m_audioBuffer->readBytes(data, len);
    }

    qint64 writeData(const char* data, qint64 len)
    {
        Q_UNUSED(data);
        Q_UNUSED(len);

        return 0;
    }

    bool isSequential() const
    {
        return true;
    }

private:
    QAudioInputBuffer*   m_audioBuffer;
};

}


QAudioInputPrivate::QAudioInputPrivate(const QByteArray& device, QAudioFormat const& format):
    audioFormat(format)
{
    QDataStream ds(device);
    quint32 did, mode;

    ds >> did >> mode;

    if (QAudio::Mode(mode) == QAudio::AudioOutput)
        errorCode = QAudio::OpenError;
    else {
        audioDeviceInfo = new QAudioDeviceInfoInternal(device, QAudio::AudioInput);
        isOpen = false;
        audioDeviceId = AudioDeviceID(did);
        audioUnit = 0;
        startTime = 0;
        totalFrames = 0;
        audioBuffer = 0;
        internalBufferSize = QtMultimediaInternal::default_buffer_size;
        clockFrequency = AudioGetHostClockFrequency() / 1000;
        errorCode = QAudio::NoError;
        stateCode = QAudio::StoppedState;

        intervalTimer = new QTimer(this);
        intervalTimer->setInterval(1000);
        connect(intervalTimer, SIGNAL(timeout()), SIGNAL(notify()));
    }
}

QAudioInputPrivate::~QAudioInputPrivate()
{
    close();
    delete audioDeviceInfo;
}

bool QAudioInputPrivate::open()
{
    UInt32  size = 0;

    if (isOpen)
        return true;

    ComponentDescription    cd;
    cd.componentType = kAudioUnitType_Output;
    cd.componentSubType = kAudioUnitSubType_HALOutput;
    cd.componentManufacturer = kAudioUnitManufacturer_Apple;
    cd.componentFlags = 0;
    cd.componentFlagsMask = 0;

    // Open
    Component cp = FindNextComponent(NULL, &cd);
    if (cp == 0) {
        qWarning() << "QAudioInput: Failed to find HAL Output component";
        return false;
    }

    if (OpenAComponent(cp, &audioUnit) != noErr) {
        qWarning() << "QAudioInput: Unable to Open Output Component";
        return false;
    }

    // Set mode
    // switch to input mode
    UInt32 enable = 1;
    if (AudioUnitSetProperty(audioUnit,
                               kAudioOutputUnitProperty_EnableIO,
                               kAudioUnitScope_Input,
                               1,
                               &enable,
                               sizeof(enable)) != noErr) {
        qWarning() << "QAudioInput: Unable to switch to input mode (Enable Input)";
        return false;
    }

    enable = 0;
    if (AudioUnitSetProperty(audioUnit,
                            kAudioOutputUnitProperty_EnableIO,
                            kAudioUnitScope_Output,
                            0,
                            &enable,
                            sizeof(enable)) != noErr) {
        qWarning() << "QAudioInput: Unable to switch to input mode (Disable output)";
        return false;
    }

    // register callback
    AURenderCallbackStruct cb;
    cb.inputProc = inputCallback;
    cb.inputProcRefCon = this;

    if (AudioUnitSetProperty(audioUnit,
                               kAudioOutputUnitProperty_SetInputCallback,
                               kAudioUnitScope_Global,
                               0,
                               &cb,
                               sizeof(cb)) != noErr) {
        qWarning() << "QAudioInput: Failed to set AudioUnit callback";
        return false;
    }

    // Set Audio Device
    if (AudioUnitSetProperty(audioUnit,
                                kAudioOutputUnitProperty_CurrentDevice,
                                kAudioUnitScope_Global,
                                0,
                                &audioDeviceId,
                                sizeof(audioDeviceId)) != noErr) {
        qWarning() << "QAudioInput: Unable to use configured device";
        return false;
    }

    // Set format
    // Wanted
    streamFormat = toAudioStreamBasicDescription(audioFormat);

    // Required on unit
    if (audioFormat == audioDeviceInfo->preferredFormat()) {
        deviceFormat = streamFormat;
        AudioUnitSetProperty(audioUnit,
                               kAudioUnitProperty_StreamFormat,
                               kAudioUnitScope_Output,
                               1,
                               &deviceFormat,
                               sizeof(deviceFormat));
    }
    else {
        size = sizeof(deviceFormat);
        if (AudioUnitGetProperty(audioUnit,
                                    kAudioUnitProperty_StreamFormat,
                                    kAudioUnitScope_Input,
                                    1,
                                    &deviceFormat,
                                    &size) != noErr) {
            qWarning() << "QAudioInput: Unable to retrieve device format";
            return false;
        }

        if (AudioUnitSetProperty(audioUnit,
                                   kAudioUnitProperty_StreamFormat,
                                   kAudioUnitScope_Output,
                                   1,
                                   &deviceFormat,
                                   sizeof(deviceFormat)) != noErr) {
            qWarning() << "QAudioInput: Unable to set device format";
            return false;
        }
    }

    // Setup buffers
    UInt32 numberOfFrames;
    size = sizeof(UInt32);
    if (AudioUnitGetProperty(audioUnit,
                                kAudioDevicePropertyBufferFrameSize,
                                kAudioUnitScope_Global,
                                0,
                                &numberOfFrames,
                                &size) != noErr) {
        qWarning() << "QAudioInput: Failed to get audio period size";
        return false;
    }

    // Allocate buffer
    periodSizeBytes = numberOfFrames * streamFormat.mBytesPerFrame;

    if (internalBufferSize < periodSizeBytes * 2)
        internalBufferSize = periodSizeBytes * 2;
    else
        internalBufferSize -= internalBufferSize % streamFormat.mBytesPerFrame;

    audioBuffer = new QtMultimediaInternal::QAudioInputBuffer(internalBufferSize,
                                        periodSizeBytes,
                                        deviceFormat,
                                        streamFormat,
                                        this);

    audioIO = new QtMultimediaInternal::MacInputDevice(audioBuffer, this);

    // Init
    if (AudioUnitInitialize(audioUnit) != noErr) {
        qWarning() << "QAudioInput: Failed to initialize AudioUnit";
        return false;
    }

    isOpen = true;

    return isOpen;
}

void QAudioInputPrivate::close()
{
    if (audioUnit != 0) {
        AudioOutputUnitStop(audioUnit);
        AudioUnitUninitialize(audioUnit);
        CloseComponent(audioUnit);
    }

    delete audioBuffer;
}

QAudioFormat QAudioInputPrivate::format() const
{
    return audioFormat;
}

QIODevice* QAudioInputPrivate::start(QIODevice* device)
{
    QIODevice*  op = device;

    if (!audioDeviceInfo->isFormatSupported(audioFormat) || !open()) {
        stateCode = QAudio::StoppedState;
        errorCode = QAudio::OpenError;
        return audioIO;
    }

    reset();
    audioBuffer->reset();
    audioBuffer->setFlushDevice(op);

    if (op == 0)
        op = audioIO;

    // Start
    startTime = AudioGetCurrentHostTime();
    totalFrames = 0;

    audioThreadStart();

    stateCode = QAudio::ActiveState;
    errorCode = QAudio::NoError;
    emit stateChanged(stateCode);

    return op;
}

void QAudioInputPrivate::stop()
{
    QMutexLocker    lock(&mutex);
    if (stateCode != QAudio::StoppedState) {
        audioThreadStop();
        audioBuffer->flush(true);

        errorCode = QAudio::NoError;
        stateCode = QAudio::StoppedState;
        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
    }
}

void QAudioInputPrivate::reset()
{
    QMutexLocker    lock(&mutex);
    if (stateCode != QAudio::StoppedState) {
        audioThreadStop();

        errorCode = QAudio::NoError;
        stateCode = QAudio::StoppedState;
        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
    }
}

void QAudioInputPrivate::suspend()
{
    QMutexLocker    lock(&mutex);
    if (stateCode == QAudio::ActiveState || stateCode == QAudio::IdleState) {
        audioThreadStop();

        errorCode = QAudio::NoError;
        stateCode = QAudio::SuspendedState;
        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
    }
}

void QAudioInputPrivate::resume()
{
    QMutexLocker    lock(&mutex);
    if (stateCode == QAudio::SuspendedState) {
        audioThreadStart();

        errorCode = QAudio::NoError;
        stateCode = QAudio::ActiveState;
        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
    }
}

int QAudioInputPrivate::bytesReady() const
{
    return audioBuffer->used();
}

int QAudioInputPrivate::periodSize() const
{
    return periodSizeBytes;
}

void QAudioInputPrivate::setBufferSize(int bs)
{
    internalBufferSize = bs;
}

int QAudioInputPrivate::bufferSize() const
{
    return internalBufferSize;
}

void QAudioInputPrivate::setNotifyInterval(int milliSeconds)
{
    if (intervalTimer->interval() == milliSeconds)
        return;

    if (milliSeconds <= 0)
        milliSeconds = 0;

    intervalTimer->setInterval(milliSeconds);
}

int QAudioInputPrivate::notifyInterval() const
{
    return intervalTimer->interval();
}

qint64 QAudioInputPrivate::processedUSecs() const
{
    return totalFrames * 1000000 / audioFormat.frequency();
}

qint64 QAudioInputPrivate::elapsedUSecs() const
{
    if (stateCode == QAudio::StoppedState)
        return 0;

    return (AudioGetCurrentHostTime() - startTime) / (clockFrequency / 1000);
}

QAudio::Error QAudioInputPrivate::error() const
{
    return errorCode;
}

QAudio::State QAudioInputPrivate::state() const
{
    return stateCode;
}

void QAudioInputPrivate::audioThreadStop()
{
    stopTimers();
    if (audioThreadState.testAndSetAcquire(Running, Stopped))
        threadFinished.wait(&mutex);
}

void QAudioInputPrivate::audioThreadStart()
{
    startTimers();
    audioThreadState = Running;
    AudioOutputUnitStart(audioUnit);
}

void QAudioInputPrivate::audioDeviceStop()
{
    AudioOutputUnitStop(audioUnit);
    audioThreadState = Stopped;
    threadFinished.wakeOne();
}

void QAudioInputPrivate::audioDeviceFull()
{
    QMutexLocker    lock(&mutex);
    if (stateCode == QAudio::ActiveState) {
        audioDeviceStop();

        errorCode = QAudio::UnderrunError;
        stateCode = QAudio::IdleState;
        QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection);
    }
}

void QAudioInputPrivate::audioDeviceError()
{
    QMutexLocker    lock(&mutex);
    if (stateCode == QAudio::ActiveState) {
        audioDeviceStop();

        errorCode = QAudio::IOError;
        stateCode = QAudio::StoppedState;
        QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection);
    }
}

void QAudioInputPrivate::startTimers()
{
    audioBuffer->startFlushTimer();
    if (intervalTimer->interval() > 0)
        intervalTimer->start();
}

void QAudioInputPrivate::stopTimers()
{
    audioBuffer->stopFlushTimer();
    intervalTimer->stop();
}

void QAudioInputPrivate::deviceStopped()
{
    stopTimers();
    emit stateChanged(stateCode);
}

// Input callback
OSStatus QAudioInputPrivate::inputCallback(void* inRefCon,
                                AudioUnitRenderActionFlags* ioActionFlags,
                                const AudioTimeStamp* inTimeStamp,
                                UInt32 inBusNumber,
                                UInt32 inNumberFrames,
                                AudioBufferList* ioData)
{
    Q_UNUSED(ioData);

    QAudioInputPrivate* d = static_cast<QAudioInputPrivate*>(inRefCon);

    const int threadState = d->audioThreadState.fetchAndAddAcquire(0);
    if (threadState == Stopped)
        d->audioDeviceStop();
    else {
        qint64      framesWritten;

        framesWritten = d->audioBuffer->renderFromDevice(d->audioUnit,
                                                         ioActionFlags,
                                                         inTimeStamp,
                                                         inBusNumber,
                                                         inNumberFrames);

        if (framesWritten > 0)
            d->totalFrames += framesWritten;
        else if (framesWritten == 0)
            d->audioDeviceFull();
        else if (framesWritten < 0)
            d->audioDeviceError();
    }

    return noErr;
}


QT_END_NAMESPACE

#include "qaudioinput_mac_p.moc"