audio-io fixed sync problem while reads pcm data, code refactoring
[platform/core/api/audio-io.git] / src / cpp / CAudioInput.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17
18 #include "CAudioIODef.h"
19
20
21 using namespace std;
22 using namespace tizen_media_audio;
23
24
25 /**
26  * class CAudioInput inherited by CAudioIO
27  */
28 CAudioInput::CAudioInput(CAudioInfo& info) :
29     CAudioIO(info),
30     __mIsUsedSyncRead(true) {
31 }
32
33 CAudioInput::CAudioInput(
34         unsigned int            sampleRate,
35         CAudioInfo::EChannel    channel,
36         CAudioInfo::ESampleType type,
37         CAudioInfo::EAudioType  audioType) :
38     __mIsUsedSyncRead(true) {
39     mAudioInfo = CAudioInfo(sampleRate, channel, type, audioType, -1);
40 }
41
42 CAudioInput::~CAudioInput() {
43 }
44
45 void CAudioInput::onStream(CPulseAudioClient* pClient, size_t length) {
46     assert(pClient);
47
48     /*
49      * Does not call CAudioIO::onStream() for synchronization
50      * if a user is using read()
51      */
52     if (__mIsUsedSyncRead == true) {
53 #ifdef _AUDIO_IO_DEBUG_TIMING_
54         AUDIO_IO_LOGD("Sync Read Mode! - pClient:[%p], length:[%d]", pClient, length);
55 #endif
56         return;
57     }
58
59     /*
60      * Accrues callback function
61      */
62 #ifdef _AUDIO_IO_DEBUG_TIMING_
63     AUDIO_IO_LOGD("pClient:[%p], length:[%d]", pClient, length);
64 #endif
65     CAudioIO::onStream(pClient, length);
66 }
67
68 void CAudioInput::onInterrupt(CAudioSessionHandler* pHandler, int id, mm_sound_focus_type_e focus_type, mm_sound_focus_state_e state, const char *reason_for_change, const char *additional_info) {
69     assert(pHandler);
70     AUDIO_IO_LOGD("[pHandler:0x%x], [focus_type:%d], [state:%d], [reason_for_change:%s], [additional_info:%s]", pHandler, focus_type, state, reason_for_change, additional_info);
71     CAudioIO::onInterrupt(pHandler, id, focus_type, state, reason_for_change, additional_info);
72 }
73
74 void CAudioInput::onSignal(CAudioSessionHandler* pHandler, mm_sound_signal_name_t signal, int value) {
75     assert(pHandler);
76     AUDIO_IO_LOGD("[pHandler:0x%x], [signal:%d], [value:%d]", pHandler, signal, value);
77     CAudioIO::onSignal(pHandler, signal, value);
78 }
79
80 void CAudioInput::__setInit(bool flag) {
81     __mIsInit = flag;
82 }
83
84 bool CAudioInput::__IsInit() {
85     return (CAudioIO::isInit() == true && __mIsInit == true);
86 }
87
88 bool CAudioInput::__IsReady() {
89     return CAudioIO::IsReady();
90 }
91
92 void CAudioInput::initialize() throw (CAudioError) {
93     if (__IsInit() == true) {
94         return;
95     }
96
97     try {
98         CAudioIO::initialize();
99
100         // Create ASM Handler
101         mpAudioSessionHandler = new CAudioSessionHandler(CAudioSessionHandler::EAudioSessionType::AUDIO_SESSION_TYPE_CAPTURE, mAudioInfo, this);
102         if (mpAudioSessionHandler == NULL) {
103             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed to allocate CAudioSessionHandler object");
104         }
105
106         // Initialize ASM Handler
107         mpAudioSessionHandler->initialize();
108
109         __setInit(true);
110         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
111     } catch (CAudioError err) {
112         finalize();
113         throw err;
114     }
115 }
116
117 void CAudioInput::finalize() {
118     if (__IsInit() == false) {
119         AUDIO_IO_LOGD("Did not initialize");
120         return;
121     }
122
123     SAFE_FINALIZE(mpAudioSessionHandler);
124     SAFE_DELETE(mpAudioSessionHandler);
125
126     CAudioIO::finalize();
127
128     __setInit(false);
129 }
130
131 void CAudioInput::prepare() throw (CAudioError) {
132     if (__IsInit() == false) {
133         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CAudioInput");
134     }
135
136     if (__IsReady() == true) {
137         AUDIO_IO_LOGD("Already prepared CAudioInput");
138         return;
139     }
140
141     try {
142         internalLock();
143
144         // Check to invalid AudioType
145         CAudioInfo::EAudioType audioType = mAudioInfo.getAudioType();
146         if (audioType < CAudioInfo::EAudioType::AUDIO_IN_TYPE_MEDIA || audioType > CAudioInfo::EAudioType::AUDIO_IN_TYPE_LOOPBACK) {
147             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The audioType is invalid [type:%d]", static_cast<int>(audioType));
148         }
149
150         if (mpAudioSessionHandler->getId() < 0) {  //Did not registerSound()
151             // Check session to skip registration
152             if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSessionEvent() == false) {
153                 // Register ASM Listener
154                 AUDIO_IO_LOGD("Register ASM Listener");
155                 mpAudioSessionHandler->registerSound();
156             }
157         }
158
159         // Init StreamSpec
160         AUDIO_IO_LOGD("Set Stream Spec : CPulseStreamSpec::STREAM_LATENCY_INPUT_MID");
161         CPulseStreamSpec::EStreamLatency streamSpec = CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_INPUT_MID;
162         CPulseStreamSpec spec(streamSpec, mAudioInfo);
163
164         // Create PulseAudio Handler
165         mpPulseAudioClient = new CPulseAudioClient(CPulseAudioClient::EStreamDirection::STREAM_DIRECTION_RECORD, spec, this);
166         if (mpPulseAudioClient == NULL) {
167             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed to allocate CPulseAudioClient object");
168         }
169
170         // Initialize PulseAudio Handler
171         mpPulseAudioClient->initialize();
172
173         if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSessionEvent() == false) {
174             /* Updates ASM to PLAYING */
175             mpAudioSessionHandler->updatePlaying();
176         }
177
178         internalUnlock();
179
180         // Do Prepare
181         CAudioIO::prepare();
182     } catch (CAudioError e) {
183         internalUnlock();
184         throw e;
185     }
186 }
187
188 void CAudioInput::unprepare() throw (CAudioError) {
189     if (__IsInit() == false) {
190         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CAudioInput");
191     }
192
193     if (__IsReady() == false) {
194         AUDIO_IO_LOGD("Already unprepared");
195         return;
196     }
197
198     try{
199         // Do unprepare
200         CAudioIO::unprepare();
201
202         internalLock();
203
204         SAFE_FINALIZE(mpPulseAudioClient);
205         SAFE_DELETE(mpPulseAudioClient);
206
207         if (mpAudioSessionHandler->getId() >= 0) {
208             /* Updates ASM to STOP */
209             if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSessionEvent() == false) {
210                 mpAudioSessionHandler->updateStop();
211             }
212
213             bool isSkip = mpAudioSessionHandler->isSkipSessionEvent();
214             if (isSkip == false) {
215                 mpAudioSessionHandler->unregisterSound();
216             }
217         }
218
219         internalUnlock();
220
221         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
222     } catch (CAudioError e) {
223         internalUnlock();
224         throw e;
225     }
226 }
227
228 void CAudioInput::pause() throw (CAudioError) {
229     if (__IsInit() == false || __IsReady() == false) {
230         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioInput");
231     }
232
233     try{
234         CAudioIO::pause();
235
236         internalLock();
237
238         /* Updates ASM to STOP */
239         if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSessionEvent() == false) {
240             mpAudioSessionHandler->updateStop();
241         }
242
243         internalUnlock();
244
245         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED);
246     } catch (CAudioError e) {
247         internalUnlock();
248         throw e;
249     }
250 }
251
252 void CAudioInput::resume() throw (CAudioError) {
253     if (__IsInit() == false || __IsReady() == false) {
254         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioInput");
255     }
256
257     try {
258         internalLock();
259
260         if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSessionEvent() == false) {
261
262             /* Updates ASM to PLAYING */
263             mpAudioSessionHandler->updatePlaying();
264         }
265
266         internalUnlock();
267
268         CAudioIO::resume();
269
270         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
271     } catch (CAudioError e) {
272         internalUnlock();
273         throw e;
274     }
275 }
276
277 void CAudioInput::drain() throw (CAudioError) {
278     THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "Did not support drain of CAudioInput");
279 }
280
281 void CAudioInput::flush() throw (CAudioError) {
282     if (__IsInit() == false || __IsReady() == false) {
283         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioInput");
284     }
285
286     try {
287         CAudioIO::flush();
288     } catch (CAudioError e) {
289         throw e;
290     }
291 }
292
293 int CAudioInput::getBufferSize() throw (CAudioError) {
294     if (__IsInit() == false) {
295         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CAudioInput");
296     }
297
298     if (__IsReady() == false) {
299         AUDIO_IO_LOGD("Warning: Did not prepare CAudioInput, then return zero");
300         return 0;
301     }
302
303     int size = 0;
304
305     try {
306         size = mpPulseAudioClient->getBufferSize();
307     } catch (CAudioError err) {
308         throw err;
309     }
310
311     return size;
312 }
313
314 void CAudioInput::setStreamCallback(SStreamCallback callback) throw (CAudioError) {
315     if (__IsInit() == false) {
316         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CAudioInput");
317     }
318
319     if (callback.onStream == NULL) {
320         AUDIO_IO_LOGD("__mIsUsedSyncRead = true");
321         __mIsUsedSyncRead = true;
322     } else {
323         AUDIO_IO_LOGD("__mIsUsedSyncRead = false");
324         __mIsUsedSyncRead = false;
325     }
326
327     CAudioIO::setStreamCallback(callback);
328 }
329
330 size_t CAudioInput::read(void* buffer, size_t length) throw (CAudioError) {
331     if (__IsInit() == false || __IsReady() == false) {
332         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioInput");
333     }
334
335     if (buffer == NULL) {
336         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "Parameters are NULL buffer:%p", buffer);
337     }
338
339     /* Checks synchronous flag */
340     if (__mIsUsedSyncRead == false) {
341         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION, "Invalid operation of read() if receive stream callback");
342     }
343
344     int ret = 0;
345
346     try {
347         // Block until read done
348         ret = mpPulseAudioClient->read(buffer, length);
349     } catch (CAudioError e) {
350         throw e;
351     }
352
353     return ret;
354 }
355
356 int CAudioInput::peek(const void** buffer, size_t* length) throw (CAudioError) {
357     if (__IsInit() == false || __IsReady() == false) {
358         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioInput");
359     }
360
361     if (buffer == NULL || length == NULL) {
362         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "Parameters are NULL buffer:%p, length:%p", buffer, length);
363     }
364
365     /* Checks synchronous flag */
366     if (__mIsUsedSyncRead == true) {
367         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION, "Invalid operation of peek() if does not receive a stream callback");
368     }
369
370     int ret = 0;
371
372     try {
373         ret = mpPulseAudioClient->peek(buffer, length);
374     } catch (CAudioError e) {
375         throw e;
376     }
377
378     return ret;
379 }
380
381 int CAudioInput::drop() throw (CAudioError) {
382     if (__IsInit() == false || __IsReady() == false) {
383         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioInput");
384     }
385
386     /* Checks synchronous flag */
387     if (__mIsUsedSyncRead == true) {
388         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION, "Invalid operation of drop() if does not receive a stream callback");
389     }
390
391     int ret = 0;
392
393     try {
394         ret = mpPulseAudioClient->drop();
395     } catch (CAudioError e) {
396         throw e;
397     }
398
399     return ret;
400 }