forked from albertz/music-player-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
musicplayer_utils.cpp
326 lines (272 loc) · 6.78 KB
/
musicplayer_utils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// ffmpeg_utils.cpp
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
#include "musicplayer.h"
#include "Protection.hpp"
#include "PyUtils.h"
#include <unistd.h>
// this is mostly safe to call.
// returns a newly allocated c-string.
char* objStrDup(PyObject* obj) {
PyGILState_STATE gstate = PyGILState_Ensure();
const char* str = NULL;
PyObject* earlierError = PyErr_Occurred();
if(!obj)
str = "<None>";
else if(PyString_Check(obj))
str = PyString_AsString(obj);
else {
PyObject* strObj = NULL;
if(PyUnicode_Check(obj))
strObj = PyUnicode_AsUTF8String(obj);
else {
PyObject* unicodeObj = PyObject_Unicode(obj);
if(unicodeObj) {
strObj = PyUnicode_AsUTF8String(unicodeObj);
Py_DECREF(unicodeObj);
}
}
if(strObj) {
str = PyString_AsString(strObj);
Py_DECREF(strObj);
}
else
str = "<CantConvertToString>";
}
if(!earlierError && PyErr_Occurred())
PyErr_Print();
assert(str);
char* str2 = strdup(str);
PyGILState_Release(gstate);
return str2;
}
// returns a newly allocated c-string.
char* objAttrStrDup(PyObject* obj, const char* attrStr) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject* attrObj = PyObject_GetAttrString(obj, attrStr);
char* str = objStrDup(attrObj);
Py_XDECREF(attrObj);
PyGILState_Release(gstate);
return str;
}
std::string objAttrStr(PyObject* obj, const std::string& attrStr) {
char* s = objAttrStrDup(obj, attrStr.c_str());
std::string s2(s);
free(s);
return s2;
}
std::string objStr(PyObject* obj) {
char* s = objStrDup(obj);
std::string s2(s);
free(s);
return s2;
}
#if defined(__APPLE__)
#include <execinfo.h>
__attribute__((noinline))
void* getStackPtr(int n) {
n += 1; // getStackPtr() itself
void* stack[20];
static const int Size = sizeof(stack)/sizeof(stack[0]);
if(n >= Size) return NULL;
int c = backtrace(stack, Size);
if(n >= c) return NULL;
return stack[n];
}
const char* getStackSymbol(void* pt) {
char** s_ = backtrace_symbols(&pt, 1);
if(!s_) return "?";
char* s = *s_;
free(s_);
if(!s) return "?";
// s = "<number> <filename> <interesting-part>"
// we only want the interesting part.
while(*s && *s != ' ') ++s; // advance the number
while(*s && *s == ' ') ++s; // advance the spaces
while(*s && *s != ' ') ++s; // advance the filename
while(*s && *s == ' ') ++s; // advance the spaces
return s;
}
#else
void* getStackPtr(int n) { return NULL; }
const char* getStackSymbol(void* pt) { return "?"; }
#endif
PyMutex::PyMutex() {
mlock(this, sizeof(*this));
l = PyThread_allocate_lock();
mlock(l, sizeof(int) /* some minimum size */);
enabled = true;
}
PyMutex::~PyMutex() {
PyThread_free_lock(l);
}
void PyMutex::lock() {
if(enabled)
PyThread_acquire_lock(l, WAIT_LOCK);
}
bool PyMutex::lock_nowait() {
if(enabled)
return PyThread_acquire_lock(l, NOWAIT_LOCK);
else
return true;
}
void PyMutex::unlock() {
if(enabled)
PyThread_release_lock(l);
}
PyScopedLock::PyScopedLock(PyMutex& m) : mutex(m) {
#ifdef MUTEX_DEBUG
printf("%p locks %p from %s\n", (void*)PyThread_get_thread_ident(), &mutex, getStackSymbol(getStackPtr(2)));
#endif
mutex.lock();
}
PyScopedLock::~PyScopedLock() {
#ifdef MUTEX_DEBUG
printf("%p unlocks %p from %s\n", (void*)PyThread_get_thread_ident(), &mutex, getStackSymbol(getStackPtr(2)));
#endif
mutex.unlock();
}
PyScopedUnlock::PyScopedUnlock(PyMutex& m) : mutex(m) {
mutex.unlock();
}
PyScopedUnlock::~PyScopedUnlock() {
mutex.lock();
}
PyThread::PyThread() {
running = false;
stopSignal = false;
ident = -1;
}
PyThread::~PyThread() {
stop();
}
static void PyThread_thread(void* p) {
PyThread* t = (PyThread*)p;
t->func(t->stopSignal);
{
PyScopedLock l(t->lock);
t->running = false;
}
}
bool PyThread::start() {
PyScopedLock l(lock);
if(running) return true;
stopSignal = false;
bool expectedRunning = false;
if(running.compare_exchange_strong(expectedRunning, true)) {
ident = PyThread_start_new_thread(PyThread_thread, this);
if(ident == -1) {
running = false;
return false;
}
}
else assert(false);
return true;
}
void PyThread::wait() {
while(true) {
{
PyScopedLock l(lock);
if(!running) return;
}
usleep(100);
}
}
void PyThread::stop() {
{
PyScopedLock l(lock);
if(!running) return;
stopSignal = true;
}
wait();
}
ProtectionData::ProtectionData() {
lockThreadIdent = 0;
lockCounter = 0;
isValid = true;
}
ProtectionData::~ProtectionData() {
assert(lockCounter == 0);
assert(lockThreadIdent == 0);
}
void ProtectionData::lock() {
long myThreadIdent = PyThread_get_thread_ident();
while(true) {
PyScopedLock lock(mutex);
if(lockCounter > 0 && lockThreadIdent != myThreadIdent) {
usleep(10);
continue;
}
lockCounter++;
lockThreadIdent = myThreadIdent;
return;
}
}
void ProtectionData::unlock() {
PyScopedLock lock(mutex);
assert(lockCounter > 0);
assert(lockThreadIdent == PyThread_get_thread_ident());
lockCounter--;
}
ProtectionScope::ProtectionScope(const Protection& p) : prot(p.prot) {
if(prot.get()) prot->lock();
}
ProtectionScope::~ProtectionScope() {
if(prot.get()) prot->unlock();
}
void ProtectionScope::setInvalid() {
if(prot.get()) prot->isValid = false;
}
bool ProtectionScope::isValid() {
if(prot.get()) return prot->isValid;
return false;
}
#if !defined(WIN32) || defined(HAVE_PTHREAD)
#include <pthread.h>
#ifndef HAVE_PTHREAD
#define HAVE_PTHREAD
#endif
#ifndef HAVE_PTHREAD_NAME
// pthread_setname_np only available since MacOSX SDK 10.6
#if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
#define HAVE_PTHREAD_NAME
// glibc 2.12 introduced this
#elif defined(__GLIBC_PREREQ)
# if __GLIBC_PREREQ(2,12)
# define HAVE_PTHREAD_NAME
# endif
#endif
#endif
#endif
void setCurThreadName(const std::string& name)
{
#ifdef _MSC_VER
// Code taken from http://www.codeproject.com/KB/threads/Name_threads_in_debugger.aspx
typedef struct tagTHREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
THREADNAME_INFO info;
{
info.dwType = 0x1000;
info.szName = name.c_str();
info.dwThreadID = (DWORD)-1;
info.dwFlags = 0;
}
__try {
RaiseException( 0x406D1388 /* MSVC EXCEPTION */, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info );
} __except (EXCEPTION_CONTINUE_EXECUTION) {}
#endif
#ifdef HAVE_PTHREAD_NAME
// http://stackoverflow.com/questions/2369738/can-i-set-the-name-of-a-thread-in-pthreads-linux/7989973#7989973
#ifdef __APPLE__
pthread_setname_np(name.c_str());
#else
pthread_setname_np(pthread_self(), name.c_str());
#endif
#endif
}