1 /**
2  * Copyright (C) 2022 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 #include <IImsMediaThread.h>
18 #include <ImsMediaTrace.h>
19 #include <thread>
20 #include <mediautils/SchedulingPolicyService.h>
21 
22 #define MAX_THREAD_NAME_LEN 16
23 
24 extern void setAudioThreadPriority(int threadId);
25 
IImsMediaThread()26 IImsMediaThread::IImsMediaThread()
27 {
28     mThreadStopped = true;
29 }
30 
~IImsMediaThread()31 IImsMediaThread::~IImsMediaThread() {}
32 
runThread(void * arg)33 void* runThread(void* arg)
34 {
35     if (arg == nullptr)
36     {
37         IMLOGE0("[runThread] invalid argument");
38         return nullptr;
39     }
40 
41     IImsMediaThread* thread = reinterpret_cast<IImsMediaThread*>(arg);
42     return thread->run();
43 }
44 
StartThread(const char * name)45 bool IImsMediaThread::StartThread(const char* name)
46 {
47     IMLOGD1("[StartThread] name:%s", name);
48     std::lock_guard<std::mutex> guard(mThreadMutex);
49     mThreadStopped = false;
50 
51     std::thread t1(&runThread, this);
52     if (name)
53     {
54         if (strlen(name) >= MAX_THREAD_NAME_LEN)
55         {
56             char shortname[MAX_THREAD_NAME_LEN];
57             strncpy(shortname, name, MAX_THREAD_NAME_LEN - 1);
58             pthread_setname_np(t1.native_handle(), shortname);
59         }
60         else
61         {
62             pthread_setname_np(t1.native_handle(), name);
63         }
64     }
65     t1.detach();
66     return true;
67 }
68 
SetThreadPriority(pid_t pid,pid_t tid,int priority)69 void IImsMediaThread::SetThreadPriority(pid_t pid, pid_t tid, int priority)
70 {
71     const int err =
72             android::requestPriority(pid, tid, priority, false /*isForApp*/, true /*asynchronous*/);
73     IMLOGD3("[SetThreadPriority] tid:%u, returned:%d. Err: %s", tid, err, strerror(errno));
74 }
75 
StopThread()76 void IImsMediaThread::StopThread()
77 {
78     std::lock_guard<std::mutex> guard(mThreadMutex);
79     mThreadStopped = true;
80 }
81 
IsThreadStopped()82 bool IImsMediaThread::IsThreadStopped()
83 {
84     std::lock_guard<std::mutex> guard(mThreadMutex);
85     return mThreadStopped;
86 }
87