6760f2e358ac1a963a52a1c96252c4cbbb8ff335
[platform/core/api/audio-io.git] / src / cpp / CAudioOutput.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 <new>
19
20 #include "CAudioIODef.h"
21 #include <sched.h>
22
23 using namespace std;
24 using namespace tizen_media_audio;
25
26 /**
27  * class CAudioOutput
28  */
29 CAudioOutput::CAudioOutput(CAudioInfo& info) :
30     CAudioIO(info),
31     __mIsUsedSyncWrite(false),
32     __mIsInit(false) {
33     mDirection = CAudioInfo::EAudioDirection::AUDIO_DIRECTION_OUT;
34 }
35
36 CAudioOutput::CAudioOutput(
37         unsigned int            sampleRate,
38         CAudioInfo::EChannel    channel,
39         CAudioInfo::ESampleType sampleType,
40         CAudioInfo::EAudioType  audioType) :
41     __mIsUsedSyncWrite(false),
42     __mIsInit(false) {
43     mDirection = CAudioInfo::EAudioDirection::AUDIO_DIRECTION_OUT;
44     mAudioInfo = CAudioInfo(sampleRate, channel, sampleType, audioType, -1);
45 }
46
47 CAudioOutput::~CAudioOutput() {
48 }
49
50 void CAudioOutput::onStream(CPulseAudioClient* pClient, size_t length) {
51     assert(pClient);
52
53     /*
54      * Does not call CAudioIO::onStream() for synchronization
55      * if a user is using write()
56      */
57     if (__mIsUsedSyncWrite == true) {
58 #ifdef _AUDIO_IO_DEBUG_TIMING_
59         AUDIO_IO_LOGD("Sync Write Mode! - signal! - pClient:[%p], length:[%d]", pClient, length);
60 #endif
61         internalSignal();
62         return;
63     }
64
65     /*
66      * Accrues callback function
67      */
68 #ifdef _AUDIO_IO_DEBUG_TIMING_
69     AUDIO_IO_LOGD("pClient:[%p], length:[%d]", pClient, length);
70 #endif
71     CAudioIO::onStream(pClient, length);
72 }
73
74 void CAudioOutput::onInterrupt(CAudioSessionHandler* pHandler, int id, mm_sound_focus_type_e focus_type,
75                                mm_sound_focus_state_e state, const char *reason_for_change, const char *additional_info) {
76     assert(pHandler);
77     AUDIO_IO_LOGD("[pHandler:%p], [focus_type:%d], [state:%d], [reason_for_change:%s], [additional_info:%s]",
78                    pHandler, focus_type, state, reason_for_change, additional_info);
79     CAudioIO::onInterrupt(pHandler, id, focus_type, state, reason_for_change, additional_info);
80 }
81
82 void CAudioOutput::onSignal(CAudioSessionHandler* pHandler, mm_sound_signal_name_t signal, int value) {
83     assert(pHandler);
84     AUDIO_IO_LOGD("[pHandler:%p], [signal:%d], [value:%d]", pHandler, signal, value);
85     CAudioIO::onSignal(pHandler, signal, value);
86 }
87
88 void CAudioOutput::__setInit(bool flag) {
89     __mIsInit = flag;
90 }
91
92 bool CAudioOutput::__IsInit() {
93     return (CAudioIO::isInit() == true && __mIsInit == true);
94 }
95
96 bool CAudioOutput::__IsReady() {
97     return CAudioIO::IsReady();
98 }
99
100 void CAudioOutput::initialize() {
101     if (__IsInit() == true) {
102         return;
103     }
104
105     try {
106         CAudioIO::initialize();
107
108         // Create ASM Handler
109         mpAudioSessionHandler = new CAudioSessionHandler(CAudioSessionHandler::EAudioSessionType::AUDIO_SESSION_TYPE_PLAYBACK, mAudioInfo, this);
110
111         // Initialize ASM Handler
112         mpAudioSessionHandler->initialize();
113
114         __setInit(true);
115         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
116     } catch (CAudioError& e) {
117         finalize();
118         throw;
119     } catch (const std::bad_alloc&) {
120         finalize();
121         THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed to allocate CAudioSessionHandler object");
122     }
123 }
124
125 void CAudioOutput::finalize() {
126     if (__IsInit() == false) {
127         AUDIO_IO_LOGD("Did not initialize");
128         return;
129     }
130
131     SAFE_FINALIZE(mpAudioSessionHandler);
132     SAFE_DELETE(mpAudioSessionHandler);
133
134     CAudioIO::finalize();
135
136     __setInit(false);
137 }
138
139 void CAudioOutput::prepare() {
140     if (__IsInit() == false) {
141         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CAudioOutput");
142     }
143
144     if (__IsReady() == true) {
145         AUDIO_IO_LOGD("Already prepared CAudioOutput");
146         CAudioIO::prepare();
147         return;
148     }
149
150     try {
151         internalLock();
152
153         // Check to invalid AudioType
154         CAudioInfo::EAudioType audioType = mAudioInfo.getAudioType();
155         if (audioType < CAudioInfo::EAudioType::AUDIO_OUT_TYPE_MEDIA || audioType >= CAudioInfo::EAudioType::AUDIO_TYPE_MAX) {
156             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT,
157                                    "The audioType is invalid [type:%d]", static_cast<int>(audioType));
158         }
159
160         if (mpAudioSessionHandler->getId() < 0) {  // Did not registerSound()
161             if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false) {
162                 // Register ASM Listener
163                 AUDIO_IO_LOGD("Register ASM Listener");
164                 mpAudioSessionHandler->registerSound();
165             }
166         }
167
168         CAudioIO::setInternalStreamInfo();
169
170         // Init StreamSpec
171         CPulseStreamSpec::EStreamLatency streamSpec = CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT;
172 #ifndef DISABLE_MOBILE_BACK_COMP
173         if (!mStreamCallback.onStream) {
174             AUDIO_IO_LOGD("Set Stream Spec : CPulseStreamSpec::STREAM_LATENCY_OUTPUT_DEFAULT");
175             streamSpec = CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT;
176         } else {
177             AUDIO_IO_LOGD("Set Stream Spec : CPulseStreamSpec::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC");
178             streamSpec = CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC;
179         }
180 #endif
181         CPulseStreamSpec spec(streamSpec, mAudioInfo);
182
183         // Create PulseAudio Handler
184         mpPulseAudioClient = new CPulseAudioClient(CPulseAudioClient::EStreamDirection::STREAM_DIRECTION_PLAYBACK, spec, this);
185
186         // Initialize PulseAudio Handler
187         mpPulseAudioClient->initialize();
188
189         if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false)
190             mpAudioSessionHandler->updatePlaying();
191
192 #ifndef DISABLE_MOBILE_BACK_COMP
193         // Uncork stream which is created with CORKED flag */
194         mpPulseAudioClient->cork(false);
195 #endif
196         internalUnlock();
197
198         CAudioIO::prepare();
199     } catch (CAudioError& e) {
200         SAFE_FINALIZE(mpPulseAudioClient);
201         SAFE_DELETE(mpPulseAudioClient);
202         internalUnlock();
203         throw;
204     } catch (const std::bad_alloc&) {
205         internalUnlock();
206         THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed to allocate CPulseAudioClient object");
207     }
208 }
209
210 void CAudioOutput::unprepare() {
211     if (__IsInit() == false) {
212         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
213                         "Did not initialize CAudioOutput");
214     }
215
216     if (__IsReady() == false) {
217         AUDIO_IO_LOGD("Already unprepared");
218         return;
219     }
220
221     try {
222         if (mpAudioSessionHandler->getId() >= 0 && !mIsInterrupted) {
223             if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false) {
224                 CPulseStreamSpec::EStreamLatency streamSpec;
225                 streamSpec = mpPulseAudioClient->getStreamSpec().getStreamLatency();
226                 if (CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC != streamSpec)
227                     CAudioIO::drain();
228             }
229         }
230         CAudioIO::unprepare();
231
232         internalLock();
233
234         SAFE_FINALIZE(mpPulseAudioClient);
235         SAFE_DELETE(mpPulseAudioClient);
236
237         internalUnlock();
238
239         if (mpAudioSessionHandler->getId() >= 0) {
240             if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false)
241                 mpAudioSessionHandler->updateStop();
242         }
243
244         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
245     } catch (CAudioError& e) {
246         internalUnlock();
247         throw;
248     }
249 }
250
251 void CAudioOutput::pause() {
252     if (__IsInit() == false || __IsReady() == false) {
253         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
254                         "Did not initialize or prepare CAudioOutput");
255     }
256
257     if (CAudioIO::getState() != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING) {
258         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_STATE,
259                         "Can't pause if not in Running state");
260     }
261
262     if (mpPulseAudioClient->isInThread() == true) {
263         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_OPERATION, "Can't pause in thread");
264     }
265
266     try {
267         CAudioIO::pause();
268
269         internalLock();
270
271         /* Updates ASM to STOP */
272         if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false)
273             mpAudioSessionHandler->updateStop();
274
275         internalUnlock();
276
277         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED);
278     } catch (CAudioError& e) {
279         internalUnlock();
280         throw;
281     }
282 }
283
284 void CAudioOutput::resume() {
285     if (__IsInit() == false || __IsReady() == false) {
286         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
287                         "Did not initialize or prepare CAudioOutput");
288     }
289
290     if (CAudioIO::getState() != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED) {
291         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_STATE,
292                         "Can't resume if not in Paused state");
293     }
294
295     if (mpPulseAudioClient->isInThread() == true) {
296         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_OPERATION, "Can't resume in thread");
297     }
298
299     try {
300         internalLock();
301
302         if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false)
303             mpAudioSessionHandler->updatePlaying();
304
305         internalUnlock();
306
307         CAudioIO::resume();
308
309         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
310     } catch (CAudioError& e) {
311         internalUnlock();
312         throw;
313     }
314 }
315
316 void CAudioOutput::drain() {
317     CPulseStreamSpec::EStreamLatency streamSpec;
318
319     if (__IsInit() == false || __IsReady() == false) {
320         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
321                         "Did not initialize or prepare CAudioOutput");
322     }
323
324     streamSpec = mpPulseAudioClient->getStreamSpec().getStreamLatency();
325     if (CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC == streamSpec)
326         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION, "async type don't support drain");
327
328     try {
329         CAudioIO::drain();
330     } catch (CAudioError& e) {
331         throw;
332     }
333 }
334
335 void CAudioOutput::flush() {
336     if (__IsInit() == false || __IsReady() == false) {
337         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
338                         "Did not initialize or prepare CAudioOutput");
339     }
340
341     try {
342         CAudioIO::flush();
343     } catch (CAudioError& e) {
344         throw;
345     }
346 }
347
348 int CAudioOutput::getBufferSize() {
349     if (__IsInit() == false) {
350         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
351                         "Did not initialize or prepare CAudioOutput");
352     }
353
354     /* FIXME : return calculated size here to satisfy backward compatibility */
355     return (mAudioInfo.getSampleRate() * DEFAULT_PERIOD_SIZE) / 1000 * mAudioInfo.getSampleSize();
356 }
357
358 size_t CAudioOutput::write(const void* buffer, size_t length) {
359     if (__IsInit() == false || __IsReady() == false) {
360         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
361                         "Did not initialize or prepare CAudioOutput");
362     }
363
364     if (buffer == NULL) {
365         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT,
366                                "Parameters are invalid - buffer:%p, length:%zu", buffer, length);
367     }
368     if (CAudioIO::getState() != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING) {
369         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION,
370                         "Can't write if not in Running state");
371     }
372
373     /* When write() is called in PulseAudio callback, bypass a pcm data to CPulseAudioClient (For Asynchronous) */
374     if (mpPulseAudioClient && mpPulseAudioClient->isInThread() == true) {
375         int ret = mpPulseAudioClient->write(buffer, length);
376         if (ret < 0) {
377             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
378                                    "The written result is invalid ret:%d", ret);
379         }
380
381 #ifdef _AUDIO_IO_DEBUG_TIMING_
382         AUDIO_IO_LOGD("CPulseAudioClient->write(buffer:%p, length:%d)", buffer, length);
383 #endif
384
385         return length;
386     }
387
388     try {
389         /* For synchronization */
390         internalLock();
391         if (mIsInterrupted) {
392             THROW_ERROR_MSG(CAudioError::EError::ERROR_POLICY_BLOCKED, "audio io is interrupted");
393         }
394
395         // If another thread did call unprepare, do not write
396         if (mpPulseAudioClient == NULL)
397             THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
398                             "Did not initialize CPulseAudioClient");
399
400         // Sets synchronous flag
401         __mIsUsedSyncWrite = true;
402
403         size_t lengthIter = length;
404
405         while (lengthIter > 0) {
406             size_t l;
407
408             while ((l = mpPulseAudioClient->getWritableSize()) == 0) {
409 #ifdef _AUDIO_IO_DEBUG_TIMING_
410                 AUDIO_IO_LOGD("writableSize is [%d].. wait", l);
411 #endif
412                 internalWait();
413             }
414
415             if (l > lengthIter) {
416                 l = lengthIter;
417             }
418
419 #ifdef _AUDIO_IO_DEBUG_TIMING_
420             AUDIO_IO_LOGD("CPulseAudioClient->write(buffer:%p, length:%d)", buffer, l);
421 #endif
422
423             int ret = mpPulseAudioClient->write(buffer, l);
424             if (ret < 0) {
425                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
426                                        "The written result is invalid ret:%d", ret);
427             }
428
429             buffer = static_cast<const uint8_t*>(buffer) + l;
430             lengthIter -= l;
431         }  // End of while (length > 0)
432
433         __mIsUsedSyncWrite = false;
434         internalUnlock();
435         sched_yield();
436     } catch (CAudioError& e) {
437         __mIsUsedSyncWrite = false;
438         internalUnlock();
439         throw;
440     }
441
442     return length;
443 }