summaryrefslogtreecommitdiffstats
blob: dad252d5e484b93220353fdabe7be6675606dc99 (plain) (blame)
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
/*
 * Copyright (C) 2013 Texas Instruments
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// #define LOG_NDEBUG 0
// #define VERY_VERBOSE_LOGGING

#include <tiaudioutils/Log.h>
#include <tiaudioutils/Stream.h>
#include <tiaudioutils/Resampler.h>

namespace tiaudioutils {

BufferAdaptor::BufferAdaptor()
    : mStatus(0)
{
    sem_init(&mFill, 0, 0);
    sem_init(&mEmpty, 0, 1);
    sem_init(&mDone, 0, 0);
    mUnderRuns = 0;
}

BufferAdaptor::~BufferAdaptor()
{
    sem_destroy(&mFill);
    sem_destroy(&mEmpty);
    sem_destroy(&mDone);
}

int BufferAdaptor::read(void * const buffer, size_t frames)
{
    sem_wait(&mEmpty);

    mMutex.lock();
    mBuffer = buffer;
    mFrames = frames;
    mMutex.unlock();

    sem_post(&mFill);

    sem_wait(&mDone);

    return mStatus;
}

int BufferAdaptor::write(const void *buffer, size_t frames)
{
    sem_wait(&mEmpty);

    mMutex.lock();
    mBuffer = buffer;
    mFrames = frames;
    mMutex.unlock();

    sem_post(&mFill);

    sem_wait(&mDone);

    return mStatus;
}

int BufferAdaptor::getNextBuffer(BufferProvider::Buffer* buffer)
{
    timespec ts;

    /*
     * Set a 200ms timeout for the semaphore wait call. Waiting indefinitely
     * may result in a deadlock condition, and waiting for too short a period
     * can result in glitches in the audio. A value is chosen that is large
     * enough to give sufficient time to receive the next read/write call and
     * yet not so large as to noticably block the user in case of error. A
     * timeout of 200ms should be sufficient to receive the next audio buffer
     * during normal playback and record.
     */
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_nsec += (200 * 1000000); /* 200ms timeout */
    if (ts.tv_nsec > 1000000000) { /* check for wraparound */
        ts.tv_sec += 1;
        ts.tv_nsec -= 1000000000;
    }

    int ret = sem_timedwait(&mFill, &ts);

    mMutex.lock();
    if (ret) {
        ALOGW("getNextBuffer: failed to get buffer [%s]", strerror(errno));
        buffer->raw = NULL;
        buffer->frameCount = 0;
        mStatus = ret;
        mUnderRuns++;
    }
    else {
        buffer->raw = const_cast<void *>(mBuffer);
        if (buffer->frameCount > mFrames)
            buffer->frameCount = mFrames;
    }
    mMutex.unlock();

    return ret;
}

void BufferAdaptor::releaseBuffer(BufferProvider::Buffer* buffer)
{
    sem_post(&mEmpty);

    /*
     * Pass the number of read/written frames in case of success,
     * or the error code otherwise.
     *
     * NOTE: The rule is that the buffer's frame count doesn't change
     * between getNextBuffer() and releaseBuffer().
     * The exception to that rule is when the frame count is not known
     * at the time the buffer is acquired.
     * Specifically, that's the case of resampling with fractional ratio
     * where the "actual" resampled frame count might vary from one
     * iteration to another. So, if the resampler produced less frames
     * than we expected (and got the buffer for), simply update the amount
     * of frames here.
     * This is not fair for all providers (particularly write providers)
     * that would otherwise have to "rewind" to update the actual number
     * of frames. Read providers only provide a new empty buffer to be filled,
     * so the "rewind" operation has no side effect.
     */
    if (buffer->frameCount)
        mStatus = buffer->frameCount;
    else
        mStatus = (int)buffer->i32;

    sem_post(&mDone);
}

/* ---------------------------------------------------------------------------------------- */

InStream::InStream(const PcmParams &params,
                   BufferProvider *provider)
    : mBufferProvider(provider),
      mParams(params),
      mMap((1U << params.channels) - 1),
      mReader(NULL),
      mResampler(NULL),
      mStarted(false)
{
}

InStream::InStream(const PcmParams &params,
                   const SlotMap &map,
                   BufferProvider *provider)
    : mBufferProvider(provider),
      mParams(params),
      mMap(map),
      mReader(NULL),
      mResampler(NULL),
      mStarted(false)
{
}

InStream::~InStream()
{
    if (mReader) {
        ALOGW("InStream: automatically unregistered");
        if (isStarted())
            stop();
        sp<InStream> stream = this;
        mReader->unregisterStream(stream);
    }
}

bool InStream::initCheck() const
{
    if (mBufferProvider == NULL) {
        ALOGE("InStream: buffer provider is invalid");
        return false;
    }

    if (!mMap.isValid()) {
        ALOGE("InStream: slot map is invalid");
        return false;
    }

    if (!mParams.isValid()) {
        ALOGE("InStream: params are invalid");
        return false;
    }

    if (!mParams.frameCount) {
        ALOGE("InStream: params.frameCount is invalid");
        return false;
    }

    if (mMap.getDstMask() >= (1U << mParams.channels)) {
        ALOGE("InStream: dest mask is invalid (too many channels %u)",
              mMap.getChannelCount());
        return false;
    }

    return true;
}

int InStream::start()
{
    if (!mReader) {
        ALOGE("InStream: not registered to reader, cannot start");
        return -EINVAL;
    }

    AutoMutex lock(mLock);
    if (mStarted) {
        ALOGE("InStream: stream is already started");
        return -EBUSY;
    }

    int ret = mReader->open();
    if (!ret)
        mStarted = true;
    else
        ALOGE("InStream: failed to open %d", ret);

    return ret;
}

void InStream::stop()
{
    if (!mReader) {
        ALOGE("InStream: not registered to reader, cannot stop");
        return;
    }

    AutoMutex lock(mLock);
    if (!mStarted) {
        ALOGE("InStream: stream is already stopped");
        return;
    }

    mStarted = false;
    mReader->close();
}

bool InStream::isStarted() const
{
    AutoMutex lock(mLock);
    return mStarted;
}

int InStream::read(void *buffer, size_t frames)
{
    ALOGE("InStream: not supported by the stream type");
    return -ENOTSUP;
}

int InStream::getNextBuffer(BufferProvider::Buffer *buffer)
{
    int ret;

    if (canResample())
        ret = getNextBufferForResample(buffer);
    else
        ret = mBufferProvider->getNextBuffer(buffer);

    return ret;
}

void InStream::releaseBuffer(BufferProvider::Buffer *buffer)
{
    if (canResample())
        releaseResampledBuffer(buffer);
    else
        mBufferProvider->releaseBuffer(buffer);
}

int InStream::getNextBufferForResample(BufferProvider::Buffer *buffer)
{
    /*
     * The buffer requested to this method is in the native sample rate
     * (at which PcmReader or UnMerge operate). We pass our internal
     * temporary buffer from which we resample after it has been filled up.
     */
    buffer->raw = mRsmpBuffer.raw;
    buffer->frameCount = mRsmpBuffer.frameCount;

    return 0;
}

void InStream::releaseResampledBuffer(BufferProvider::Buffer *buffer)
{
    BufferProvider::Buffer outBuffer;
    int8_t *curBuffer = buffer->i8;
    int32_t pending = buffer->frameCount;
    uint32_t ratioNum;
    uint32_t ratioDen;

    mResampler->getRatio(ratioNum, ratioDen);

    /* resample all frames in the released output buffer */
    while (pending > 0) {
        /*
         * Request a buffer to our internal provider, whose size is proportional
         * to the resampling ratio.
         */
        outBuffer.frameCount = (pending * ratioDen) / ratioNum + 1;
        int ret = mBufferProvider->getNextBuffer(&outBuffer);
        if (ret) {
            ALOGE("InStream: failed to get buffer from provider %d", ret);
            return;
        }

        uint32_t inFrames = pending;
        uint32_t outFrames = outBuffer.frameCount;
        ret = mResampler->resample(curBuffer, inFrames, outBuffer.raw, outFrames);
        if (ret) {
            ALOGW("InStream: failed to resample %d", ret);
            outBuffer.i32 = (int32_t*)ret;
            outBuffer.frameCount = 0;
        } else {
            /*
             * NOTE: Consciously change the frame count of the acquired buffer.
             * This is an exception for read providers, otherwise we would have
             * to resample in a temporary buffer and once the "produced" number
             * of samples is known, acquire the buffer and copy the audio frames.
             */
            outBuffer.frameCount = outFrames;
            pending -= inFrames;
            curBuffer += mParams.framesToBytes(inFrames);
        }

        mBufferProvider->releaseBuffer(&outBuffer);
    }

    ALOGW_IF(pending, "InStream: unexpected pending frame count %d", pending);
}

/* ---------------------------------------------------------------------------------------- */

AdaptedInStream::AdaptedInStream(const PcmParams &params)
    : InStream(params, &mAdaptor)
{
}

AdaptedInStream::AdaptedInStream(const PcmParams &params,
                                 const SlotMap &map)
    : InStream(params, map, &mAdaptor)
{
}

int AdaptedInStream::read(void *buffer, size_t frames)
{
    AutoMutex lock(mLock);
    if (!mStarted) {
        ALOGE("AdaptedInStream: stream is not started, cannot read");
        return -EPERM;
    }

    return mAdaptor.read(buffer, frames);
}

/* ---------------------------------------------------------------------------------------- */

BufferedInStream::BufferedInStream(const PcmParams &params,
                                   uint32_t frames)
    : InStream(params), mPipe(params, frames), mPipeWriter(&mPipe)
{
    mBufferProvider = &mPipeWriter;
}

BufferedInStream::BufferedInStream(const PcmParams &params,
                                   const SlotMap &map,
                                   uint32_t frames)
    : InStream(params, map), mPipe(params, frames), mPipeWriter(&mPipe)
{
    mBufferProvider = &mPipeWriter;
}

bool BufferedInStream::initCheck() const
{
    return (InStream::initCheck() &&
            mPipe.initCheck() &&
            mPipeWriter.initCheck());
}

int BufferedInStream::read(void *buffer, size_t frames)
{
    AutoMutex lock(mLock);
    if (!mStarted) {
        ALOGE("BufferedInStream: stream is not started, cannot read");
        return -EPERM;
    }

    return mPipe.read(buffer, frames);
}

/* ---------------------------------------------------------------------------------------- */

OutStream::OutStream(const PcmParams &params,
                     BufferProvider *provider)
    : mBufferProvider(provider),
      mParams(params),
      mMap((1U << params.channels) - 1),
      mWriter(NULL),
      mResampler(NULL),
      mStarted(false)
{
}

OutStream::OutStream(const PcmParams &params,
                     const SlotMap &map,
                     BufferProvider *provider)
    : mBufferProvider(provider),
      mParams(params),
      mMap(map),
      mWriter(NULL),
      mResampler(NULL),
      mStarted(false)
{
}

OutStream::~OutStream()
{
    if (mWriter) {
        ALOGW("OutStream: automatically unregistered");
        if (isStarted())
            stop();
        sp<OutStream> stream = this;
        mWriter->unregisterStream(stream);
    }
}

bool OutStream::initCheck() const
{
    if (mBufferProvider == NULL) {
        ALOGE("OutStream: buffer provider is invalid");
        return false;
    }

    if (!mMap.isValid()) {
        ALOGE("OutStream: slot map is invalid");
        return false;
    }

    if (!mParams.isValid()) {
        ALOGE("OutStream: params are invalid");
        return false;
    }

    if (!mParams.frameCount) {
        ALOGE("OutStream: params.frameCount is invalid");
        return false;
    }

    if (mMap.getSrcMask() >= (1U << mParams.channels)) {
        ALOGE("OutStream: source mask is invalid (too many channels %u)",
              mMap.getChannelCount());
        return false;
    }

    return true;
}

int OutStream::start()
{
    if (!mWriter) {
        ALOGE("OutStream: not registered to writer, cannot start");
        return -EINVAL;
    }

    AutoMutex lock(mLock);
    if (mStarted) {
        ALOGE("OutStream: stream is already started");
        return -EBUSY;
    }

    int ret = mWriter->open();
    if (!ret)
        mStarted = true;
    else
        ALOGE("OutStream: failed to open %d", ret);

    return ret;
}

void OutStream::stop()
{
    if (!mWriter) {
        ALOGE("OutStream: not registered to writer, cannot stop");
        return;
    }

    AutoMutex lock(mLock);
    if (!mStarted) {
        ALOGE("OutStream: stream is already stopped");
        return;
    }

    mStarted = false;
    mWriter->close();
}

bool OutStream::isStarted() const
{
    AutoMutex lock(mLock);
    return mStarted;
}

int OutStream::write(const void *buffer, size_t frames)
{
    ALOGE("OutStream: not supported by the stream type");
    return -ENOTSUP;
}

int OutStream::getNextBuffer(BufferProvider::Buffer *buffer)
{
    int ret;

    if (canResample())
        ret = getNextResampledBuffer(buffer);
    else
        ret = mBufferProvider->getNextBuffer(buffer);

    return ret;
}

void OutStream::releaseBuffer(BufferProvider::Buffer *buffer)
{
    if (!canResample())
        mBufferProvider->releaseBuffer(buffer);
}

int OutStream::getNextResampledBuffer(BufferProvider::Buffer *buffer)
{
    int ret;

    if (buffer->frameCount > mRsmpBuffer.frameCount)
        buffer->frameCount = mRsmpBuffer.frameCount;

    ret = mResampler->resample(*mBufferProvider,
                               mRsmpBuffer.raw,
                               mRsmpBuffer.frameCount);
    if (ret) {
        ALOGE("OutStream: failed to resample %d", ret);
        return ret;
    }

    buffer->raw = mRsmpBuffer.raw;
    buffer->frameCount = mRsmpBuffer.frameCount;

    return ret;
}

/* ---------------------------------------------------------------------------------------- */

AdaptedOutStream::AdaptedOutStream(const PcmParams &params)
    : OutStream(params, &mAdaptor)
{
}

AdaptedOutStream::AdaptedOutStream(const PcmParams &params,
                                   const SlotMap &map)
    : OutStream(params, map, &mAdaptor)
{
}

int AdaptedOutStream::write(const void *buffer, size_t frames)
{
    AutoMutex lock(mLock);
    if (!mStarted) {
        ALOGE("AdaptedOutStream: stream is not started, cannot write");
        return -EPERM;
    }

    return mAdaptor.write(buffer, frames);
}

/* ---------------------------------------------------------------------------------------- */

BufferedOutStream::BufferedOutStream(const PcmParams &params,
                                     uint32_t frames)
    : OutStream(params), mPipe(params, frames), mPipeReader(&mPipe)
{
    mBufferProvider = &mPipeReader;
}

BufferedOutStream::BufferedOutStream(const PcmParams &params,
                                     const SlotMap &map,
                                     uint32_t frames)
    : OutStream(params, map), mPipe(params, frames), mPipeReader(&mPipe)
{
    mBufferProvider = &mPipeReader;
}

bool BufferedOutStream::initCheck() const
{
    return (OutStream::initCheck() &&
            mPipe.initCheck() &&
            mPipeReader.initCheck());
}

int BufferedOutStream::write(const void *buffer, size_t frames)
{
    AutoMutex lock(mLock);
    if (!mStarted) {
        ALOGE("BufferedOutStream: stream is not started, cannot write");
        return -EPERM;
    }

    return mPipe.write(buffer, frames);
}

/* ---------------------------------------------------------------------------------------- */

PcmReader::PcmReader(PcmInPort *port, const PcmParams &params)
    : ThreadBase("PcmReader"),
      mPort(port),
      mParams(params),
      mUnMerge(params),
      mUsers(0)
{
    mBuffer.i8 = new int8_t[mParams.bufferSize()];
    mBuffer.frameCount = mParams.frameCount;
}

PcmReader::~PcmReader()
{
    for (StreamSet::iterator i = mStreams.begin(); i != mStreams.end(); ++i) {
        sp<InStream> stream = (*i).promote();
        if (stream == 0)
            continue;
        ALOGW("PcmReader: automatically unregistering stream %p", stream.get());
        unregisterStream(stream);
    }

    if (mPort && mPort->isOpen())
        mPort->close();

    if (mBuffer.i8) {
        delete [] mBuffer.i8;
        mBuffer.i8 = NULL;
    }
}

bool PcmReader::initCheck() const
{
    if (mPort == NULL) {
        ALOGE("PcmReader: invalid PCM input port");
        return false;
    }

    if (!mParams.isValid() || !mParams.frameCount) {
        ALOGE("PcmReader: params are not valid");
        return false;
    }

    if (mBuffer.raw == NULL) {
        ALOGE("PcmReader: intermediate buffer allocation failed");
        return false;
    }

    if (!mUnMerge.initCheck()) {
        ALOGE("PcmReader: un-merge failed to initialize");
        return false;
    }

    return true;
}

int PcmReader::registerStream(sp<InStream>& stream)
{
    if (stream == NULL) {
        ALOGE("PcmReader: stream is invalid, cannot register");
        return -EINVAL;
    }

    const PcmParams &outParams = stream->getParams();
    if (!outParams.isValid() || !outParams.frameCount) {
        ALOGE("PcmReader: stream has invalid params");
        return -EINVAL;
    }

    ALOGI("PcmReader: register stream %p src 0x%04x dst 0x%04x",
          stream.get(), stream->mMap.getSrcMask(), stream->mMap.getDstMask());

    AutoMutex lock(mLock);
    if (mStreams.find(stream) != mStreams.end()) {
        ALOGE("PcmReader: stream is already registered");
        return -EINVAL;
    }

    /*
     * Hardware parameters are not known when the stream is created. It's not
     * until stream registration that we have enough information to determine
     * if the stream needs resampling, and if so, what the resampling parameters
     * are. Speex-based resampler is supported only for 16-bits/sample.
     */
    if ((mParams.sampleRate != outParams.sampleRate) && (outParams.sampleBits == 16)) {
        int ret = attachResampler(stream.get());
        if (ret) {
            ALOGE("PcmReader: failed to create and attached resampler");
            return ret;
        }
    } else if ((mParams.sampleBits != outParams.sampleBits) ||
               (mParams.sampleRate != outParams.sampleRate)) {
        /* Channels of the reader and stream are different if un-merge is used */
        ALOGE("PcmReader: reader doesn't support stream's params");
        return -EINVAL;
    }

    int ret = mUnMerge.registerStream(stream);
    if (ret) {
        ALOGE("PcmReader: failed to register stream %d", ret);
        detachResampler(stream.get());
        return ret;
    }

    stream->mReader = this;

    mStreams.insert(stream);

    return 0;
}

void PcmReader::unregisterStream(sp<InStream>& stream)
{
    if (stream == NULL) {
        ALOGE("PcmReader: stream is invalid, cannot unregister");
        return;
    }

    if (stream->isStarted()) {
        ALOGE("PcmReader: stream %p is not stopped, cannot unregister",
              stream.get());
        return;
    }

    ALOGI("PcmReader: unregister stream %p src 0x%04x dst 0x%04x",
          stream.get(), stream->mMap.getSrcMask(), stream->mMap.getDstMask());

    AutoMutex lock(mLock);
    if (mStreams.find(stream) != mStreams.end()) {
        mUnMerge.unregisterStream(stream);
        detachResampler(stream.get());
        stream->mReader = NULL;
        mStreams.erase(stream);
    } else {
        ALOGE("PcmReader: stream is not registered or already unregistered");
    }
}

int PcmReader::open()
{
    AutoMutex lock(mLock);

    ALOGV("PcmReader: users %d->%d", mUsers, mUsers+1);
    if (mUsers++)
        return 0;

    ALOGV("PcmReader: open PCM port and start reader thread");
    int ret = mPort->open(mParams);
    if (ret) {
        ALOGE("PcmReader: failed to open PCM port %d", ret);
        return ret;
    }

    /* Start the reader thread */
    ret = run();
    if (ret)
        ALOGE("PcmReader: failed to start reader thread %d", ret);

    return ret;
}

void PcmReader::close()
{
    AutoMutex lock(mLock);

    ALOGV("PcmReader: users %d->%d", mUsers, mUsers-1);
    ALOG_ASSERT(mUsers);
    if (--mUsers)
        return;

    ALOGV("PcmReader: stop reader thread and close PCM port");
    stop();
    mPort->close();
}

int PcmReader::threadFunc()
{
    int ret = mPort->read(mBuffer.raw, mParams.frameCount);
    if (ret < 0) {
        ALOGE("PcmReader: failed to read PCM data %d", ret);
        /*
         * Set frameCount to 0, this will result in an error being returned to
         * the buffer adaptor read call after the unmerge process call
         */
        mBuffer.frameCount = 0;
    }
    else {
        if (ret != (int)mBuffer.frameCount) {
            ALOGW("PcmReader: read fewer PCM frames than requested %d", ret);
        }
        /* Set the frame count to the actual amount read */
        mBuffer.frameCount = (size_t)ret;
    }

    ret = mUnMerge.process(mBuffer);
    if (ret) {
        ALOGE("PcmReader: unmerge failed %d", ret);
    }

    return 0;
}

int PcmReader::attachResampler(InStream *stream)
{
    PcmParams inParams = mParams;
    const PcmParams &outParams = stream->getParams();

    inParams.channels = outParams.channels;

    /* Intermediate buffer for the frames to be resampled */
    stream->mRsmpBuffer.frameCount = inParams.frameCount;
    stream->mRsmpBuffer.i8 = new int8_t[inParams.frameCount * inParams.frameSize()];
    if (!stream->mRsmpBuffer.i8)
        return -ENOMEM;

    stream->mResampler = new Resampler(inParams, outParams);
    if (!stream->mResampler || !stream->mResampler->initCheck()) {
        detachResampler(stream);
        return -ENODEV;
    }

    return 0;
}

void PcmReader::detachResampler(InStream *stream)
{
    if (stream->mResampler) {
        delete stream->mResampler;
        stream->mResampler = NULL;
    }

    if (stream->mRsmpBuffer.i8) {
        delete [] stream->mRsmpBuffer.i8;
        stream->mRsmpBuffer.i8 = NULL;
    }
}

/* ---------------------------------------------------------------------------------------- */

PcmWriter::PcmWriter(PcmOutPort *port, const PcmParams &params)
    : ThreadBase("PcmWriter"),
      mPort(port),
      mParams(params),
      mMerge(params),
      mUsers(0)
{
    mBuffer.i8 = new int8_t[mParams.bufferSize()];
    mBuffer.frameCount = mParams.frameCount;
}

PcmWriter::~PcmWriter()
{
    for (StreamSet::iterator i = mStreams.begin(); i != mStreams.end(); ++i) {
        sp<OutStream> stream = (*i).promote();
        if (stream == 0)
            continue;
        ALOGW("PcmWriter: automatically unregistering stream %p", stream.get());
        unregisterStream(stream);
    }

    if (mPort && mPort->isOpen())
        mPort->close();

    if (mBuffer.i8) {
        delete [] mBuffer.i8;
        mBuffer.i8 = NULL;
    }
}

bool PcmWriter::initCheck() const
{
    if (mPort == NULL) {
        ALOGE("PcmWriter: invalid PCM input port");
        return false;
    }

    if (!mParams.isValid() || !mParams.frameCount) {
        ALOGE("PcmWriter: params are not valid");
        return false;
    }

    if (mBuffer.raw == NULL) {
        ALOGE("PcmWriter: intermediate buffer allocation failed");
        return false;
    }

    if (!mMerge.initCheck()) {
        ALOGE("PcmWriter: merge failed to initialize");
        return false;
    }

    return true;
}

int PcmWriter::registerStream(sp<OutStream>& stream)
{
    if (stream == NULL) {
        ALOGE("PcmWriter: stream is invalid, cannot register");
        return -EINVAL;
    }

    const PcmParams &inParams = stream->getParams();
    if (!inParams.isValid() || !inParams.frameCount) {
        ALOGE("PcmWriter: stream has invalid params");
        return -EINVAL;
    }

    ALOGI("PcmWriter: register stream %p src 0x%04x dst 0x%04x",
          stream.get(), stream->mMap.getSrcMask(), stream->mMap.getDstMask());

    AutoMutex lock(mLock);
    if (mStreams.find(stream) != mStreams.end()) {
        ALOGE("PcmWriter: stream is already registered");
        return -EINVAL;
    }

    /*
     * Hardware parameters are not known when the stream is created. It's not
     * until stream registration that we have enough information to determine if
     * the stream needs resampling, and if so, what the resampling parameters
     * are. Speex-based resampler is supported only for 16-bits/sample.
     */
    if ((mParams.sampleRate != inParams.sampleRate) && (inParams.sampleBits == 16)) {
        int ret = attachResampler(stream.get());
        if (ret) {
            ALOGE("PcmWriter: failed to create and attached resampler");
            return ret;
        }
    } else if ((mParams.sampleBits != inParams.sampleBits) ||
               (mParams.sampleRate != inParams.sampleRate)) {
        /* Channels of the writer and stream are different if merge is used */
        ALOGE("PcmWriter: writer doesn't support stream's params");
        return -EINVAL;
    }

    int ret = mMerge.registerStream(stream);
    if (ret) {
        ALOGE("PcmWriter: failed to register stream %d", ret);
        detachResampler(stream.get());
        return ret;
    }

    stream->mWriter = this;

    mStreams.insert(stream);

    return 0;
}

void PcmWriter::unregisterStream(sp<OutStream>& stream)
{
    if (stream == NULL) {
        ALOGE("PcmWriter: stream is invalid, cannot unregister");
        return;
    }

    if (stream->isStarted()) {
        ALOGE("PcmWriter: stream %p is not stopped, cannot unregister",
              stream.get());
        return;
    }

    ALOGI("PcmWriter: unregister stream %p src 0x%04x dst 0x%04x",
          stream.get(), stream->mMap.getSrcMask(), stream->mMap.getDstMask());

    AutoMutex lock(mLock);
    if (mStreams.find(stream) != mStreams.end()) {
        mMerge.unregisterStream(stream);
        detachResampler(stream.get());
        stream->mWriter = NULL;
        mStreams.erase(stream);
    } else {
        ALOGE("PcmWriter: stream is not registered or already unregistered");
    }
}

int PcmWriter::open()
{
    AutoMutex lock(mLock);

    ALOGV("PcmWriter: users %d->%d", mUsers, mUsers+1);
    if (mUsers++)
        return 0;

    ALOGV("PcmWriter: open PCM port and start writer thread");
    int ret = mPort->open(mParams);
    if (ret) {
        ALOGE("PcmWriter: failed to open PCM port %d", ret);
        return ret;
    }

    /* Start the writer thread */
    ret = run();
    if (ret)
        ALOGE("PcmWriter: failed to start writer thread %d", ret);

    return ret;
}

void PcmWriter::close()
{
    AutoMutex lock(mLock);

    ALOGV("PcmWriter: users %d->%d", mUsers, mUsers-1);
    ALOG_ASSERT(mUsers);
    if (--mUsers)
        return;

    ALOGV("PcmWriter: stop writer thread and close PCM port");
    stop();
    mPort->close();
}

int PcmWriter::threadFunc()
{
    int ret = mMerge.process(mBuffer);
    if (ret) {
        ALOGE("PcmWriter: error processing data from provider %d", ret);
    }

    ret = mPort->write(mBuffer.raw, mBuffer.frameCount);
    if (ret < 0) {
        ALOGE("PcmWriter: failed to write PCM data %d", ret);
        /*
         * mPort->write errors will not propagate to the user through the buffer
         * adaptor. So, perform the sleep here to lessen the number of errors.
         */
        uint32_t usecs = (mBuffer.frameCount * 1000) / mParams.sampleRate;
        usleep(usecs);
    }

    return 0;
}

int PcmWriter::attachResampler(OutStream *stream)
{
    const PcmParams &inParams = stream->getParams();
    PcmParams outParams = mParams;

    outParams.channels = inParams.channels;

    /* Intermediate buffer for the resampled frames */
    stream->mRsmpBuffer.frameCount = outParams.frameCount;
    stream->mRsmpBuffer.i8 = new int8_t[outParams.frameCount * outParams.frameSize()];
    if (!stream->mRsmpBuffer.i8)
        return -ENOMEM;

    stream->mResampler = new Resampler(inParams, outParams);
    if (!stream->mResampler || !stream->mResampler->initCheck()) {
        detachResampler(stream);
        return -ENODEV;
    }

    return 0;
}

void PcmWriter::detachResampler(OutStream *stream)
{
    if (stream->mResampler) {
        delete stream->mResampler;
        stream->mResampler = NULL;
    }

    if (stream->mRsmpBuffer.i8) {
        delete [] stream->mRsmpBuffer.i8;
        stream->mRsmpBuffer.i8 = NULL;
    }
}

} /* namespace tiaudioutils */