summaryrefslogtreecommitdiffstats
path: root/media/libstagefright/FMA2DPWriter.cpp
blob: 1bcec17df9d2542ed7b36efcdf61646909e5f990 (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
/*
 * Copyright (C) 2010 The Android Open Source Project
 * Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
 *
 * Not a Contribution, Apache license notifications and license are retained
 * for attribution purposes only
 *
 * 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 LOG_TAG "FMA2DPWriter"
#include <utils/Log.h>


#include <media/stagefright/FMA2DPWriter.h>
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MediaDebug.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaErrors.h>
#include <media/stagefright/MediaSource.h>
#include <media/stagefright/MetaData.h>
#include <media/mediarecorder.h>
#include <sys/prctl.h>
#include <sys/resource.h>

#include <media/AudioRecord.h>
#include <media/AudioTrack.h>
namespace android {

#define BUFFER_POOL_SIZE 5
static int kMaxBufferSize = 2048;

FMA2DPWriter::FMA2DPWriter()
    :mStarted(false),
    mAudioChannels(0),
    mSampleRate(0),
    mAudioFormat(AUDIO_FORMAT_PCM_16_BIT),
    mAudioSource(AUDIO_SOURCE_FM_RX_A2DP),
    mBufferSize(0){
    sem_init(&mReaderThreadWakeupsem,0,0);
    sem_init(&mWriterThreadWakeupsem,0,0);
}



FMA2DPWriter::~FMA2DPWriter() {
    if (mStarted) {
        stop();
    }
    sem_destroy(&mReaderThreadWakeupsem);
    sem_destroy(&mWriterThreadWakeupsem);
}

status_t FMA2DPWriter::initCheck() const {
// API not need for FMA2DPWriter
    return OK;
}


status_t FMA2DPWriter::addSource(const sp<MediaSource> &source) {
// API not need for FMA2DPWriter
    return OK;
}

status_t FMA2DPWriter::allocateBufferPool()
{
    Mutex::Autolock lock(mFreeQLock);

    for (int i = 0; i < BUFFER_POOL_SIZE; ++i) {
        int *buffer = (int*)malloc(mBufferSize);
        if(buffer){
            audioBufferstruct audioBuffer(buffer,mBufferSize);
            mFreeQ.push_back(audioBuffer);
        }
        else{
            ALOGE("fatal:failed to alloate buffer pool");
            return  NO_INIT;
        }
    }
    return OK;
}

status_t FMA2DPWriter::start(MetaData *params) {

    if (mStarted) {
        // Already started, does nothing
        return OK;
    }

    if(!mStarted){
        if(!params){
            ALOGE("fatal:params cannot be null");
            return NO_INIT;
        }
        CHECK( params->findInt32( kKeyChannelCount, &mAudioChannels ) );
        CHECK(mAudioChannels  == 1 || mAudioChannels  == 2);
        CHECK( params->findInt32( kKeySampleRate, &mSampleRate ) );

        if ( NO_ERROR != AudioSystem::getInputBufferSize(
                    mSampleRate, mAudioFormat, mAudioChannels, &mBufferSize) ){
            mBufferSize = kMaxBufferSize ;
        }
        ALOGV("mBufferSize = %d", mBufferSize);
    }

    status_t err = allocateBufferPool();

    if(err != OK)
        return err;

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    mDone = false;

    pthread_create(&mReaderThread, &attr, ReaderThreadWrapper, this);
    pthread_create(&mWriterThread, &attr, WriterThreadWrapper, this);

    pthread_attr_destroy(&attr);


    mStarted = true;

    return OK;
}

status_t FMA2DPWriter::pause() {
// API not need for FMA2DPWriter
    return OK;
}

status_t FMA2DPWriter::stop() {
    if (!mStarted) {
        return OK;
    }

    mDone = true;

    void *dummy;
    pthread_join(mReaderThread, &dummy);
    pthread_join(mWriterThread, &dummy);

    for ( List<audioBufferstruct>::iterator it = mDataQ.begin();
         it != mDataQ.end(); ++it){
            free(it->audioBuffer);
    }
    for ( List<audioBufferstruct>::iterator it = mFreeQ.begin();
         it != mFreeQ.end(); ++it){
            free(it->audioBuffer);
    }
    mStarted = false;

    return OK;
}

void *FMA2DPWriter::ReaderThreadWrapper(void *me) {
    return (void *) static_cast<FMA2DPWriter *>(me)->readerthread();
}

void *FMA2DPWriter::WriterThreadWrapper(void *me) {
    return (void *) static_cast<FMA2DPWriter *>(me)->writerthread();
}

status_t FMA2DPWriter::readerthread() {
    status_t err = OK;
    int framecount =((4*mBufferSize)/mAudioChannels)/sizeof(int16_t);
    //sizeof(int16_t) is frame size for PCM stream
    int inChannel =
        (mAudioChannels == 2) ? AUDIO_CHANNEL_IN_STEREO :
        AUDIO_CHANNEL_IN_MONO;

    prctl(PR_SET_NAME, (unsigned long)"FMA2DPReaderThread", 0, 0, 0);

    AudioRecord* record = new AudioRecord(
                     mAudioSource,
                     mSampleRate,
                     mAudioFormat,
                     inChannel,
                     framecount);
    if(!record){
        ALOGE("fatal:Not able to open audiorecord");
        return UNKNOWN_ERROR;
    }

    status_t res = record->initCheck();
    if (res == NO_ERROR)
        res = record->start();
    else{
        ALOGE("fatal:record init check failure");
        return UNKNOWN_ERROR;
    }


    while (!mDone) {

        mFreeQLock.lock();
        if(mFreeQ.empty()){
            mFreeQLock.unlock();
            ALOGV("FreeQ empty");
            sem_wait(&mReaderThreadWakeupsem);
            ALOGV("FreeQ filled up");
            continue;
        }
        List<audioBufferstruct>::iterator it = mFreeQ.begin();
        audioBufferstruct buff ( it->audioBuffer,it->bufferlen);
        mFreeQ.erase(it);
        mFreeQLock.unlock();

        buff.bufferlen = record->read(buff.audioBuffer, mBufferSize);
        ALOGV("read %d bytes", buff.bufferlen);
        if (buff.bufferlen <= 0){
            ALOGE("error in reading from audiorecord..bailing out.");
            this ->notify(MEDIA_RECORDER_EVENT_ERROR, MEDIA_RECORDER_ERROR_UNKNOWN,
                           ERROR_MALFORMED);
            err = INVALID_OPERATION ;
            break;
        }

        mDataQLock.lock();
        if(mDataQ.empty()){
            ALOGV("waking up reader");
            sem_post(&mWriterThreadWakeupsem);
        }
        mDataQ.push_back(buff);
        mDataQLock.unlock();
    }
    record->stop();
    delete record;

    return err;
}


status_t FMA2DPWriter::writerthread(){
    status_t err = OK;
    int framecount =(16*mBufferSize)/sizeof(int16_t);
    //sizeof(int16_t) is frame size for PCM stream
    int outChannel = (mAudioChannels== 2) ? AUDIO_CHANNEL_OUT_STEREO :
        AUDIO_CHANNEL_OUT_MONO;

    prctl(PR_SET_NAME, (unsigned long)"FMA2DPWriterThread", 0, 0, 0);

    AudioTrack *audioTrack= new AudioTrack(
                AUDIO_STREAM_FM,
                mSampleRate,
                mAudioFormat,
                outChannel,
                framecount, 0);

    if(!audioTrack){
        ALOGE("fatal:Not able to open audiotrack");
        return UNKNOWN_ERROR;
    }
    status_t res = audioTrack->initCheck();
    if (res == NO_ERROR) {
        audioTrack->setVolume(1, 1);
        audioTrack->start();
    }
    else{
        ALOGE("fatal:audiotrack init check failure");
        return UNKNOWN_ERROR;
    }


    while (!mDone) {

        mDataQLock.lock();
        if(mDataQ.empty()){
            mDataQLock.unlock();
            ALOGV("dataQ empty");
            sem_wait(&mWriterThreadWakeupsem);
            ALOGV("dataQ filled up");
            continue;
        }
        List<audioBufferstruct>::iterator it = mDataQ.begin();
        audioBufferstruct buff ( it->audioBuffer,it->bufferlen);
        mDataQ.erase(it);
        mDataQLock.unlock();

       size_t retval = audioTrack->write(buff.audioBuffer, buff.bufferlen);
       if(!retval){
            ALOGE("audio track write failure..bailing out");
            this ->notify(MEDIA_RECORDER_EVENT_ERROR, MEDIA_RECORDER_ERROR_UNKNOWN,
                           ERROR_MALFORMED);
            err = INVALID_OPERATION ;
            break;
        }
        ALOGV("wrote %d bytes", buff.bufferlen);

        mFreeQLock.lock();
        if(mFreeQ.empty()){
            ALOGV("WAKING UP READER");
            sem_post(&mReaderThreadWakeupsem);
        }
        mFreeQ.push_back(buff);
        mFreeQLock.unlock();
    }
    audioTrack->stop();
    delete audioTrack;

    return err;
}

bool FMA2DPWriter::reachedEOS() {
// API not need for FMA2DPWriter
    return OK;
}


}  // namespace android