AAudioThread.cpp revision 5ed503c7a66c90f93759c90237a9b432dbd93f9f
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/AAudioDefinitions.h>
24
25#include "AAudioThread.h"
26
27using namespace aaudio;
28
29
30AAudioThread::AAudioThread() {
31    // mThread is a pthread_t of unknown size so we need memset.
32    memset(&mThread, 0, sizeof(mThread));
33}
34
35void AAudioThread::dispatch() {
36    if (mRunnable != nullptr) {
37        mRunnable->run();
38    } else {
39        run();
40    }
41}
42
43// This is the entry point for the new thread created by createThread().
44// It converts the 'C' function call to a C++ method call.
45static void * AAudioThread_internalThreadProc(void *arg) {
46    AAudioThread *aaudioThread = (AAudioThread *) arg;
47    aaudioThread->dispatch();
48    return nullptr;
49}
50
51aaudio_result_t AAudioThread::start(Runnable *runnable) {
52    if (mHasThread) {
53        return AAUDIO_ERROR_INVALID_STATE;
54    }
55    mRunnable = runnable; // TODO use atomic?
56    int err = pthread_create(&mThread, nullptr, AAudioThread_internalThreadProc, this);
57    if (err != 0) {
58        ALOGE("AAudioThread::pthread_create() returned %d", err);
59        // TODO convert errno to aaudio_result_t
60        return AAUDIO_ERROR_INTERNAL;
61    } else {
62        mHasThread = true;
63        return AAUDIO_OK;
64    }
65}
66
67aaudio_result_t AAudioThread::stop() {
68    if (!mHasThread) {
69        return AAUDIO_ERROR_INVALID_STATE;
70    }
71    int err = pthread_join(mThread, nullptr);
72    mHasThread = false;
73    // TODO convert errno to aaudio_result_t
74    return err ? AAUDIO_ERROR_INTERNAL : AAUDIO_OK;
75}
76
77