1/*
2 * Copyright (C) 2016 The Android Open Source Project
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#define LOG_TAG "AAudioService"
18//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
21#include <pthread.h>
22
23#include <aaudio/AAudio.h>
24#include <utility/AAudioUtilities.h>
25
26#include "AAudioThread.h"
27
28using namespace aaudio;
29
30
31AAudioThread::AAudioThread()
32    : mRunnable(nullptr)
33    , mHasThread(false) {
34    // mThread is a pthread_t of unknown size so we need memset().
35    memset(&mThread, 0, sizeof(mThread));
36}
37
38void AAudioThread::dispatch() {
39    if (mRunnable != nullptr) {
40        mRunnable->run();
41    } else {
42        run();
43    }
44}
45
46// This is the entry point for the new thread created by createThread().
47// It converts the 'C' function call to a C++ method call.
48static void * AAudioThread_internalThreadProc(void *arg) {
49    AAudioThread *aaudioThread = (AAudioThread *) arg;
50    aaudioThread->dispatch();
51    return nullptr;
52}
53
54aaudio_result_t AAudioThread::start(Runnable *runnable) {
55    if (mHasThread) {
56        ALOGE("AAudioThread::start() - mHasThread.load() already true");
57        return AAUDIO_ERROR_INVALID_STATE;
58    }
59    // mRunnable will be read by the new thread when it starts.
60    // pthread_create() forces a memory synchronization so mRunnable does not need to be atomic.
61    mRunnable = runnable;
62    int err = pthread_create(&mThread, nullptr, AAudioThread_internalThreadProc, this);
63    if (err != 0) {
64        ALOGE("AAudioThread::start() - pthread_create() returned %d %s", err, strerror(err));
65        return AAudioConvert_androidToAAudioResult(-err);
66    } else {
67        mHasThread = true;
68        return AAUDIO_OK;
69    }
70}
71
72aaudio_result_t AAudioThread::stop() {
73    if (!mHasThread) {
74        return AAUDIO_ERROR_INVALID_STATE;
75    }
76    int err = pthread_join(mThread, nullptr);
77    mHasThread = false;
78    if (err != 0) {
79        ALOGE("AAudioThread::stop() - pthread_join() returned %d %s", err, strerror(err));
80        return AAudioConvert_androidToAAudioResult(-err);
81    } else {
82        return AAUDIO_OK;
83    }
84}
85
86