Enable dummy write on streamCb only for async mode backward compatibility
[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     /* Check invalid AudioType */
151     CAudioInfo::EAudioType audioType = mAudioInfo.getAudioType();
152     if (audioType < CAudioInfo::EAudioType::AUDIO_OUT_TYPE_MEDIA || audioType >= CAudioInfo::EAudioType::AUDIO_TYPE_MAX) {
153         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT,
154                                "The audioType is invalid [type:%d]", static_cast<int>(audioType));
155     }
156
157     try {
158         if (mpAudioSessionHandler->getId() < 0) {  // Did not registerSound()
159             if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false) {
160                 /* Register ASM Listener */
161                 AUDIO_IO_LOGD("Register ASM Listener");
162                 mpAudioSessionHandler->registerSound();
163             }
164         }
165
166         CAudioIO::setInternalStreamInfo();
167
168         if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false)
169             mpAudioSessionHandler->updatePlaying();
170     } catch (CAudioError& e) {
171         throw;
172     }
173
174     try {
175         /* Init StreamSpec */
176         CPulseStreamSpec::EStreamLatency streamSpec = CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT;
177 #ifndef DISABLE_MOBILE_BACK_COMP
178         if (!mStreamCallback.onStream) {
179             AUDIO_IO_LOGD("Set Stream Spec : CPulseStreamSpec::STREAM_LATENCY_OUTPUT_DEFAULT");
180             streamSpec = CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT;
181         } else {
182             AUDIO_IO_LOGD("Set Stream Spec : CPulseStreamSpec::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC");
183             streamSpec = CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC;
184         }
185 #endif
186         CPulseStreamSpec spec(streamSpec, mAudioInfo);
187
188         internalLock();
189
190         /* Create PulseAudio Handler */
191         mpPulseAudioClient = new CPulseAudioClient(CPulseAudioClient::EStreamDirection::STREAM_DIRECTION_PLAYBACK, spec, this);
192
193         /* Initialize PulseAudio Handler */
194         mpPulseAudioClient->initialize();
195 #ifndef DISABLE_MOBILE_BACK_COMP
196         /* Uncork stream which is created with CORKED flag */
197         mpPulseAudioClient->cork(false);
198 #endif
199         internalUnlock();
200
201         CAudioIO::prepare();
202     } catch (CAudioError& e) {
203         SAFE_FINALIZE(mpPulseAudioClient);
204         SAFE_DELETE(mpPulseAudioClient);
205         internalUnlock();
206         throw;
207     } catch (const std::bad_alloc&) {
208         internalUnlock();
209         THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed to allocate CPulseAudioClient object");
210     }
211 }
212
213 void CAudioOutput::unprepare() {
214     if (__IsInit() == false) {
215         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
216                         "Did not initialize CAudioOutput");
217     }
218
219     if (__IsReady() == false) {
220         AUDIO_IO_LOGD("Already unprepared");
221         return;
222     }
223
224     try {
225         if (mpAudioSessionHandler->getId() >= 0 && !mIsInterrupted) {
226             if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false) {
227                 if (mStreamCallback.onStream == NULL)
228                     CAudioIO::drain();
229             }
230         }
231         CAudioIO::unprepare();
232
233         internalLock();
234
235         SAFE_FINALIZE(mpPulseAudioClient);
236         SAFE_DELETE(mpPulseAudioClient);
237
238         internalUnlock();
239
240     } catch (CAudioError& e) {
241         internalUnlock();
242         throw;
243     }
244
245     try {
246         if (mpAudioSessionHandler->getId() >= 0) {
247             if (isForceIgnore() == false && mpAudioSessionHandler->isSkipSession() == false)
248                 mpAudioSessionHandler->updateStop();
249         }
250         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
251     } catch (CAudioError& e) {
252         internalUnlock();
253         throw;
254     }
255 }
256
257 void CAudioOutput::pause() {
258     if (__IsInit() == false || __IsReady() == false) {
259         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
260                         "Did not initialize or prepare CAudioOutput");
261     }
262
263     if (CAudioIO::getState() != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING) {
264         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_STATE,
265                         "Can't pause if not in Running state");
266     }
267
268     if (mpPulseAudioClient->isInThread() == true) {
269         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_OPERATION, "Can't pause in thread");
270     }
271
272     try {
273         CAudioIO::pause();
274
275         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED);
276     } catch (CAudioError& e) {
277         throw;
278     }
279 }
280
281 void CAudioOutput::resume() {
282     if (__IsInit() == false || __IsReady() == false) {
283         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
284                         "Did not initialize or prepare CAudioOutput");
285     }
286
287     if (CAudioIO::getState() != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED) {
288         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_STATE,
289                         "Can't resume if not in Paused state");
290     }
291
292     if (mpPulseAudioClient->isInThread() == true) {
293         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_OPERATION, "Can't resume in thread");
294     }
295
296     try {
297         CAudioIO::resume();
298
299         CAudioIO::onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
300     } catch (CAudioError& e) {
301         throw;
302     }
303 }
304
305 void CAudioOutput::drain() {
306     if (__IsInit() == false || __IsReady() == false) {
307         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
308                         "Did not initialize or prepare CAudioOutput");
309     }
310
311     if (mStreamCallback.onStream)
312         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION, "async type don't support drain");
313
314     try {
315         CAudioIO::drain();
316     } catch (CAudioError& e) {
317         throw;
318     }
319 }
320
321 void CAudioOutput::flush() {
322     if (__IsInit() == false || __IsReady() == false) {
323         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
324                         "Did not initialize or prepare CAudioOutput");
325     }
326
327     try {
328         CAudioIO::flush();
329     } catch (CAudioError& e) {
330         throw;
331     }
332 }
333
334 int CAudioOutput::getBufferSize() {
335     if (__IsInit() == false) {
336         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
337                         "Did not initialize or prepare CAudioOutput");
338     }
339
340     /* FIXME : return calculated size here to satisfy backward compatibility */
341     return (mAudioInfo.getSampleRate() * DEFAULT_PERIOD_SIZE) / 1000 * mAudioInfo.getSampleSize();
342 }
343
344 size_t CAudioOutput::write(const void* buffer, size_t length) {
345     if (__IsInit() == false || __IsReady() == false) {
346         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
347                         "Did not initialize or prepare CAudioOutput");
348     }
349
350     if (buffer == NULL) {
351         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT,
352                                "Parameters are invalid - buffer:%p, length:%zu", buffer, length);
353     }
354     if (CAudioIO::getState() != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING) {
355         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION,
356                         "Can't write if not in Running state");
357     }
358
359     /* When write() is called in PulseAudio callback, bypass a pcm data to CPulseAudioClient (For Asynchronous) */
360     if (mpPulseAudioClient && mpPulseAudioClient->isInThread() == true) {
361         int ret = mpPulseAudioClient->write(buffer, length);
362         if (ret < 0) {
363             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
364                                    "The written result is invalid ret:%d", ret);
365         }
366
367 #ifdef _AUDIO_IO_DEBUG_TIMING_
368         AUDIO_IO_LOGD("CPulseAudioClient->write(buffer:%p, length:%d)", buffer, length);
369 #endif
370
371         return length;
372     }
373
374     try {
375         /* For synchronization */
376         internalLock();
377         if (mIsInterrupted) {
378             THROW_ERROR_MSG(CAudioError::EError::ERROR_POLICY_BLOCKED, "audio io is interrupted");
379         }
380
381         // If another thread did call unprepare, do not write
382         if (mpPulseAudioClient == NULL)
383             THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED,
384                             "Did not initialize CPulseAudioClient");
385
386         // Sets synchronous flag
387         __mIsUsedSyncWrite = true;
388
389         size_t lengthIter = length;
390
391         while (lengthIter > 0) {
392             size_t l;
393
394             while ((l = mpPulseAudioClient->getWritableSize()) == 0) {
395 #ifdef _AUDIO_IO_DEBUG_TIMING_
396                 AUDIO_IO_LOGD("writableSize is [%d].. wait", l);
397 #endif
398                 internalWait();
399             }
400
401             if (l > lengthIter) {
402                 l = lengthIter;
403             }
404
405 #ifdef _AUDIO_IO_DEBUG_TIMING_
406             AUDIO_IO_LOGD("CPulseAudioClient->write(buffer:%p, length:%d)", buffer, l);
407 #endif
408
409             int ret = mpPulseAudioClient->write(buffer, l);
410             if (ret < 0) {
411                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
412                                        "The written result is invalid ret:%d", ret);
413             }
414
415             buffer = static_cast<const uint8_t*>(buffer) + l;
416             lengthIter -= l;
417         }  // End of while (length > 0)
418
419         __mIsUsedSyncWrite = false;
420         internalUnlock();
421         sched_yield();
422     } catch (CAudioError& e) {
423         __mIsUsedSyncWrite = false;
424         internalUnlock();
425         throw;
426     }
427
428     return length;
429 }