Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/openh264/codec/common/src/WelsThreadLib.cpp
Line
Count
Source
1
/*!
2
 * \copy
3
 *     Copyright (c)  2009-2013, Cisco Systems
4
 *     All rights reserved.
5
 *
6
 *     Redistribution and use in source and binary forms, with or without
7
 *     modification, are permitted provided that the following conditions
8
 *     are met:
9
 *
10
 *        * Redistributions of source code must retain the above copyright
11
 *          notice, this list of conditions and the following disclaimer.
12
 *
13
 *        * Redistributions in binary form must reproduce the above copyright
14
 *          notice, this list of conditions and the following disclaimer in
15
 *          the documentation and/or other materials provided with the
16
 *          distribution.
17
 *
18
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
 *     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
 *     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21
 *     FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22
 *     COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23
 *     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24
 *     BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
 *     CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27
 *     LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28
 *     ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
 *     POSSIBILITY OF SUCH DAMAGE.
30
 *
31
 *
32
 * \file    WelsThreadLib.c
33
 *
34
 * \brief   Interfaces introduced in thread programming
35
 *
36
 * \date    11/17/2009 Created
37
 *
38
 *************************************************************************************
39
 */
40
41
42
#if defined(__linux__) || defined(__GNU__)
43
#ifndef _GNU_SOURCE
44
#define _GNU_SOURCE
45
#endif
46
#include <sched.h>
47
#elif !defined(_WIN32) && !defined(__CYGWIN__)
48
#include <sys/types.h>
49
#include <sys/param.h>
50
#include <unistd.h>
51
#ifdef __EMSCRIPTEN__
52
#include <emscripten/threading.h>
53
#elif !defined(__Fuchsia__)
54
#include <sys/sysctl.h>
55
#endif
56
#ifdef __APPLE__
57
#define HW_NCPU_NAME "hw.logicalcpu"
58
#elif defined(HW_NCPUONLINE)
59
#define HW_NCPU_NAME "hw.ncpuonline"
60
#else
61
#define HW_NCPU_NAME "hw.ncpu"
62
#endif
63
#endif
64
#ifdef ANDROID_NDK
65
#include <cpu-features.h>
66
#endif
67
#ifdef __ANDROID__
68
#include <android/api-level.h>
69
#endif
70
71
#include "WelsThreadLib.h"
72
#include <stdio.h>
73
#include <stdlib.h>
74
75
76
#if defined(_WIN32) || defined(__CYGWIN__)
77
78
WELS_THREAD_ERROR_CODE    WelsMutexInit (WELS_MUTEX*    mutex) {
79
  InitializeCriticalSection (mutex);
80
81
  return WELS_THREAD_ERROR_OK;
82
}
83
84
WELS_THREAD_ERROR_CODE    WelsMutexLock (WELS_MUTEX*    mutex) {
85
  EnterCriticalSection (mutex);
86
87
  return WELS_THREAD_ERROR_OK;
88
}
89
90
WELS_THREAD_ERROR_CODE    WelsMutexUnlock (WELS_MUTEX* mutex) {
91
  LeaveCriticalSection (mutex);
92
93
  return WELS_THREAD_ERROR_OK;
94
}
95
96
WELS_THREAD_ERROR_CODE    WelsMutexDestroy (WELS_MUTEX* mutex) {
97
  DeleteCriticalSection (mutex);
98
99
  return WELS_THREAD_ERROR_OK;
100
}
101
102
#else /* _WIN32 */
103
104
0
WELS_THREAD_ERROR_CODE    WelsMutexInit (WELS_MUTEX*    mutex) {
105
0
  return pthread_mutex_init (mutex, NULL);
106
0
}
107
108
0
WELS_THREAD_ERROR_CODE    WelsMutexLock (WELS_MUTEX*    mutex) {
109
0
  return pthread_mutex_lock (mutex);
110
0
}
111
112
0
WELS_THREAD_ERROR_CODE    WelsMutexUnlock (WELS_MUTEX* mutex) {
113
0
  return pthread_mutex_unlock (mutex);
114
0
}
115
116
0
WELS_THREAD_ERROR_CODE    WelsMutexDestroy (WELS_MUTEX* mutex) {
117
0
  return pthread_mutex_destroy (mutex);
118
0
}
119
120
#endif /* !_WIN32 */
121
122
#if defined(_WIN32) || defined(__CYGWIN__)
123
124
WELS_THREAD_ERROR_CODE    WelsEventOpen (WELS_EVENT* event, const char* event_name) {
125
  WELS_EVENT   h = CreateEvent (NULL, FALSE, FALSE, NULL);
126
  *event = h;
127
  if (h == NULL) {
128
    return WELS_THREAD_ERROR_GENERAL;
129
  }
130
  return WELS_THREAD_ERROR_OK;
131
}
132
133
WELS_THREAD_ERROR_CODE    WelsEventSignal (WELS_EVENT* event, WELS_MUTEX *pMutex, int* iCondition) {
134
  WelsMutexLock (pMutex);
135
  const bool bSignal = (-- (*iCondition) <= 0);
136
  // Unlock pMutex before signaling hEvent, as the woken thread may immediately
137
  // destroy the object that owns pMutex, event, and iCondition.
138
  WELS_EVENT hEvent = *event;
139
  WelsMutexUnlock (pMutex);
140
  if (bSignal && hEvent != NULL) {
141
    if (SetEvent (hEvent)) {
142
      return WELS_THREAD_ERROR_OK;
143
    }
144
  }
145
  return WELS_THREAD_ERROR_GENERAL;
146
}
147
148
WELS_THREAD_ERROR_CODE    WelsEventWait (WELS_EVENT* event, WELS_MUTEX* pMutex, int& iCondition) {
149
  return WaitForSingleObject (*event, INFINITE);
150
}
151
152
WELS_THREAD_ERROR_CODE    WelsEventWaitWithTimeOut (WELS_EVENT* event, uint32_t dwMilliseconds, WELS_MUTEX* pMutex) {
153
  return WaitForSingleObject (*event, dwMilliseconds);
154
}
155
156
WELS_THREAD_ERROR_CODE    WelsMultipleEventsWaitSingleBlocking (uint32_t nCount,
157
    WELS_EVENT* event_list, WELS_EVENT* master_even, WELS_MUTEX* pMutext) {
158
  // Don't need/use the master event for anything, since windows has got WaitForMultipleObjects
159
  return WaitForMultipleObjects (nCount, event_list, FALSE, INFINITE);
160
}
161
162
WELS_THREAD_ERROR_CODE    WelsEventClose (WELS_EVENT* event, const char* event_name) {
163
  CloseHandle (*event);
164
165
  *event = NULL;
166
  return WELS_THREAD_ERROR_OK;
167
}
168
169
#ifndef WP80
170
void WelsSleep (uint32_t dwMilliSecond) {
171
  ::Sleep (dwMilliSecond);
172
}
173
#else
174
void WelsSleep (uint32_t dwMilliSecond) {
175
  static WELS_EVENT hSleepEvent = NULL;
176
  if (!hSleepEvent) {
177
    WELS_EVENT hLocalSleepEvent = NULL;
178
    WELS_THREAD_ERROR_CODE ret = WelsEventOpen (&hLocalSleepEvent);
179
    if (WELS_THREAD_ERROR_OK != ret) {
180
      return;
181
    }
182
    WELS_EVENT hPreviousEvent = InterlockedCompareExchangePointerRelease (&hSleepEvent, hLocalSleepEvent, NULL);
183
    if (hPreviousEvent) {
184
      WelsEventClose (&hLocalSleepEvent);
185
    }
186
    //On this singleton usage idea of using InterlockedCompareExchangePointerRelease:
187
    //   similar idea of can be found at msdn blog when introducing InterlockedCompareExchangePointerRelease
188
  }
189
190
  WaitForSingleObject (hSleepEvent, dwMilliSecond);
191
}
192
#endif
193
194
WELS_THREAD_ERROR_CODE    WelsThreadCreate (WELS_THREAD_HANDLE* thread,  LPWELS_THREAD_ROUTINE  routine,
195
    void* arg, WELS_THREAD_ATTR attr) {
196
  WELS_THREAD_HANDLE   h = CreateThread (NULL, 0, routine, arg, 0, NULL);
197
198
  if (h == NULL) {
199
    return WELS_THREAD_ERROR_GENERAL;
200
  }
201
  * thread = h;
202
203
  return WELS_THREAD_ERROR_OK;
204
}
205
206
WELS_THREAD_ERROR_CODE WelsThreadSetName (const char* thread_name) {
207
  // do nothing
208
  return WELS_THREAD_ERROR_OK;
209
}
210
211
212
WELS_THREAD_ERROR_CODE    WelsThreadJoin (WELS_THREAD_HANDLE  thread) {
213
  WaitForSingleObject (thread, INFINITE);
214
  CloseHandle (thread);
215
216
  return WELS_THREAD_ERROR_OK;
217
}
218
219
220
WELS_THREAD_HANDLE        WelsThreadSelf() {
221
  return GetCurrentThread();
222
}
223
224
WELS_THREAD_ERROR_CODE    WelsQueryLogicalProcessInfo (WelsLogicalProcessInfo* pInfo) {
225
  SYSTEM_INFO  si;
226
227
  GetSystemInfo (&si);
228
229
  pInfo->ProcessorCount = si.dwNumberOfProcessors;
230
231
  return WELS_THREAD_ERROR_OK;
232
}
233
234
#else //platform: #ifdef _WIN32
235
236
WELS_THREAD_ERROR_CODE    WelsThreadCreate (WELS_THREAD_HANDLE* thread,  LPWELS_THREAD_ROUTINE  routine,
237
0
    void* arg, WELS_THREAD_ATTR attr) {
238
0
  WELS_THREAD_ERROR_CODE err = 0;
239
240
0
  pthread_attr_t at;
241
0
  err = pthread_attr_init (&at);
242
0
  if (err)
243
0
    return err;
244
0
#if !defined(__ANDROID__) && !defined(__Fuchsia__)
245
0
  err = pthread_attr_setscope (&at, PTHREAD_SCOPE_SYSTEM);
246
0
  if (err)
247
0
    return err;
248
0
  err = pthread_attr_setschedpolicy (&at, SCHED_FIFO);
249
0
  if (err)
250
0
    return err;
251
0
#endif
252
0
  err = pthread_create (thread, &at, routine, arg);
253
254
0
  pthread_attr_destroy (&at);
255
256
0
  return err;
257
0
}
258
259
0
WELS_THREAD_ERROR_CODE WelsThreadSetName (const char* thread_name) {
260
#ifdef APPLE_IOS
261
  pthread_setname_np (thread_name);
262
#endif
263
#if defined(__ANDROID__) && __ANDROID_API__ >= 9
264
  pthread_setname_np (pthread_self(), thread_name);
265
#endif
266
  // do nothing
267
0
  return WELS_THREAD_ERROR_OK;
268
0
}
269
270
0
WELS_THREAD_ERROR_CODE    WelsThreadJoin (WELS_THREAD_HANDLE  thread) {
271
0
  return pthread_join (thread, NULL);
272
0
}
273
274
0
WELS_THREAD_HANDLE        WelsThreadSelf() {
275
0
  return pthread_self();
276
0
}
277
278
// unnamed semaphores aren't supported on OS X
279
280
0
WELS_THREAD_ERROR_CODE    WelsEventOpen (WELS_EVENT* p_event, const char* event_name) {
281
#ifdef __APPLE__
282
  WELS_THREAD_ERROR_CODE err= pthread_cond_init (p_event, NULL);
283
  return err;
284
#else
285
0
  WELS_EVENT event = (WELS_EVENT) malloc (sizeof (*event));
286
0
  if (event == NULL){
287
0
    *p_event = NULL;
288
0
    return WELS_THREAD_ERROR_GENERAL;
289
0
  }
290
0
  WELS_THREAD_ERROR_CODE err = sem_init (event, 0, 0);
291
0
  if (!err) {
292
0
    *p_event = event;
293
0
    return err;
294
0
  }
295
0
  free (event);
296
0
  *p_event = NULL;
297
0
  return err;
298
0
#endif
299
0
}
300
0
WELS_THREAD_ERROR_CODE    WelsEventClose (WELS_EVENT* event, const char* event_name) {
301
  //printf("event_close:%x, %s\n", event, event_name);
302
#ifdef __APPLE__
303
  WELS_THREAD_ERROR_CODE err = pthread_cond_destroy (event);
304
  return err;
305
#else
306
0
  WELS_THREAD_ERROR_CODE err = sem_destroy (*event); // match with sem_init
307
0
  free (*event);
308
0
  *event = NULL;
309
0
  return err;
310
0
#endif
311
0
}
312
313
0
void WelsSleep (uint32_t dwMilliSecond) {
314
0
  usleep (dwMilliSecond * 1000);
315
0
}
316
317
0
WELS_THREAD_ERROR_CODE   WelsEventSignal (WELS_EVENT* event, WELS_MUTEX *pMutex, int* iCondition) {
318
0
  WELS_THREAD_ERROR_CODE err = 0;
319
  //fprintf( stderr, "before signal it, event=%x iCondition= %d..\n", event, *iCondition );
320
0
  WelsMutexLock (pMutex);
321
0
  const bool bSignal = (-- (*iCondition) <= 0);
322
#ifdef __APPLE__
323
  // On macOS, WELS_EVENT is a pthread_cond_t and WelsEventWait re-acquires pMutex
324
  // before returning, so keep pMutex locked across the condition update and signal.
325
  if (bSignal) {
326
    err = pthread_cond_signal (event);
327
    //fprintf( stderr, "signal it, event=%x iCondition= %d..\n",event, *iCondition );
328
  }
329
  WelsMutexUnlock (pMutex);
330
#else
331
  // Unlock pMutex before sem_post, as the woken thread waiting in sem_wait
332
  // does not acquire pMutex and may immediately destroy the owner of pMutex.
333
0
  WELS_EVENT hEvent = *event;
334
0
  WelsMutexUnlock (pMutex);
335
0
  if (bSignal && hEvent != NULL) {
336
//  int32_t val = 0;
337
//  sem_getvalue(event, &val);
338
//  fprintf( stderr, "before signal it, val= %d..\n",val );
339
0
    err = sem_post (hEvent);
340
//  sem_getvalue(event, &val);
341
    //fprintf( stderr, "signal it, event=%x iCondition= %d..\n",event, *iCondition );
342
0
  }
343
0
#endif
344
  //fprintf( stderr, "after signal it, event=%x  iCondition= %d..\n",event, *iCondition );
345
0
  return err;
346
0
}
347
348
0
WELS_THREAD_ERROR_CODE WelsEventWait (WELS_EVENT* event, WELS_MUTEX* pMutex, int& iCondition) {
349
#ifdef __APPLE__
350
  int err = 0;
351
  WelsMutexLock(pMutex);
352
  //fprintf( stderr, "WelsEventWait event %x %d..\n", event, iCondition );
353
  while (iCondition>0) {
354
    err = pthread_cond_wait (event, pMutex);
355
  }
356
  WelsMutexUnlock(pMutex);
357
  return err;
358
#else
359
0
  return sem_wait (*event); // blocking until signaled
360
0
#endif
361
0
}
362
363
0
WELS_THREAD_ERROR_CODE    WelsEventWaitWithTimeOut (WELS_EVENT* event, uint32_t dwMilliseconds, WELS_MUTEX* pMutex) {
364
365
0
  if (dwMilliseconds != (uint32_t) - 1) {
366
#if defined(__APPLE__)
367
    return pthread_cond_wait (event, pMutex);
368
#else
369
0
    return sem_wait (*event);
370
0
#endif
371
0
  } else {
372
0
    struct timespec ts;
373
0
    struct timeval tv;
374
375
0
    gettimeofday (&tv, 0);
376
377
0
    ts.tv_nsec = tv.tv_usec * 1000 + dwMilliseconds * 1000000;
378
0
    ts.tv_sec = tv.tv_sec + ts.tv_nsec / 1000000000;
379
0
    ts.tv_nsec %= 1000000000;
380
381
#if defined(__APPLE__)
382
    return pthread_cond_timedwait (event, pMutex, &ts);
383
#else
384
0
    return sem_timedwait (*event, &ts);
385
0
#endif
386
0
  }
387
388
0
}
389
390
WELS_THREAD_ERROR_CODE    WelsMultipleEventsWaitSingleBlocking (uint32_t nCount,
391
0
    WELS_EVENT* event_list, WELS_EVENT* master_event, WELS_MUTEX* pMutex) {
392
0
  uint32_t nIdx = 0;
393
0
  uint32_t uiAccessTime = 2; // 2 us once
394
395
0
  if (nCount == 0)
396
0
    return WELS_THREAD_ERROR_WAIT_FAILED;
397
#if defined(__APPLE__)
398
  if (master_event != NULL) {
399
    // This design relies on the events actually being semaphores;
400
    // if multiple events in the list have been signalled, the master
401
    // event should have a similar count (events in windows can't keep
402
    // track of the actual count, but the master event isn't needed there
403
    // since it uses WaitForMultipleObjects).
404
    int32_t err = pthread_cond_wait (master_event, pMutex);
405
    if (err != WELS_THREAD_ERROR_OK)
406
      return err;
407
    uiAccessTime = 0; // no blocking, just quickly loop through all to find the one that was signalled
408
  }
409
410
  while (1) {
411
    nIdx = 0; // access each event by order
412
    while (nIdx < nCount) {
413
      int32_t err = 0;
414
      int32_t wait_count = 0;
415
416
      /*
417
       * although such interface is not used in __GNUC__ like platform, to use
418
       * pthread_cond_timedwait() might be better choice if need
419
       */
420
      do {
421
        err = pthread_cond_wait (&event_list[nIdx], pMutex);
422
        if (WELS_THREAD_ERROR_OK == err)
423
          return WELS_THREAD_ERROR_WAIT_OBJECT_0 + nIdx;
424
        else if (wait_count > 0 || uiAccessTime == 0)
425
          break;
426
        usleep (uiAccessTime);
427
        ++ wait_count;
428
      } while (1);
429
      // we do need access next event next time
430
      ++ nIdx;
431
    }
432
    usleep (1); // switch to working threads
433
    if (master_event != NULL) {
434
      // A master event was used and was signalled, but none of the events in the
435
      // list was found to be signalled, thus wait a little more when rechecking
436
      // the list to avoid busylooping here.
437
      // If we ever hit this codepath it's mostly a bug in the code that signals
438
      // the events.
439
      uiAccessTime = 2;
440
    }
441
  }
442
#else
443
0
  if (master_event != NULL) {
444
    // This design relies on the events actually being semaphores;
445
    // if multiple events in the list have been signalled, the master
446
    // event should have a similar count (events in windows can't keep
447
    // track of the actual count, but the master event isn't needed there
448
    // since it uses WaitForMultipleObjects).
449
0
    int32_t err = sem_wait (*master_event);
450
0
    if (err != WELS_THREAD_ERROR_OK)
451
0
      return err;
452
0
    uiAccessTime = 0; // no blocking, just quickly loop through all to find the one that was signalled
453
0
  }
454
455
0
  while (1) {
456
0
    nIdx = 0; // access each event by order
457
0
    while (nIdx < nCount) {
458
0
      int32_t err = 0;
459
0
      int32_t wait_count = 0;
460
461
      /*
462
       * although such interface is not used in __GNUC__ like platform, to use
463
       * pthread_cond_timedwait() might be better choice if need
464
       */
465
0
      do {
466
0
        err = sem_trywait (event_list[nIdx]);
467
0
        if (WELS_THREAD_ERROR_OK == err)
468
0
          return WELS_THREAD_ERROR_WAIT_OBJECT_0 + nIdx;
469
0
        else if (wait_count > 0 || uiAccessTime == 0)
470
0
          break;
471
0
        usleep (uiAccessTime);
472
0
        ++ wait_count;
473
0
      } while (1);
474
      // we do need access next event next time
475
0
      ++ nIdx;
476
0
    }
477
0
    usleep (1); // switch to working threads
478
0
    if (master_event != NULL) {
479
      // A master event was used and was signalled, but none of the events in the
480
      // list was found to be signalled, thus wait a little more when rechecking
481
      // the list to avoid busylooping here.
482
      // If we ever hit this codepath it's mostly a bug in the code that signals
483
      // the events.
484
0
      uiAccessTime = 2;
485
0
    }
486
0
  }
487
488
0
#endif
489
0
  return WELS_THREAD_ERROR_WAIT_FAILED;
490
0
}
491
492
3.79k
WELS_THREAD_ERROR_CODE    WelsQueryLogicalProcessInfo (WelsLogicalProcessInfo* pInfo) {
493
#ifdef ANDROID_NDK
494
  pInfo->ProcessorCount = android_getCpuCount();
495
  return WELS_THREAD_ERROR_OK;
496
#elif defined(__linux__) || defined(__GNU__)
497
498
3.79k
  cpu_set_t cpuset;
499
500
3.79k
  CPU_ZERO (&cpuset);
501
502
3.79k
  if (!sched_getaffinity (0, sizeof (cpuset), &cpuset)) {
503
3.79k
#ifdef CPU_COUNT
504
3.79k
    pInfo->ProcessorCount = CPU_COUNT (&cpuset);
505
#else
506
    int32_t count = 0;
507
    for (int i = 0; i < CPU_SETSIZE; i++) {
508
      if (CPU_ISSET (i, &cpuset)) {
509
        count++;
510
      }
511
    }
512
    pInfo->ProcessorCount = count;
513
#endif
514
3.79k
  } else {
515
0
    pInfo->ProcessorCount = 1;
516
0
  }
517
518
3.79k
  return WELS_THREAD_ERROR_OK;
519
520
#elif defined(__EMSCRIPTEN__)
521
522
  // There is not yet a way to determine CPU count in emscripten JS environment.
523
  pInfo->ProcessorCount = emscripten_num_logical_cores();
524
  return WELS_THREAD_ERROR_OK;
525
526
#elif defined(__Fuchsia__)
527
528
  pInfo->ProcessorCount = sysconf(_SC_NPROCESSORS_ONLN);
529
  return WELS_THREAD_ERROR_OK;
530
#else
531
532
  size_t len = sizeof (pInfo->ProcessorCount);
533
534
#if defined(__OpenBSD__)
535
  int scname[] = { CTL_HW, HW_NCPUONLINE };
536
  if (sysctl (scname, 2, &pInfo->ProcessorCount, &len, NULL, 0) == -1)
537
#else
538
  if (sysctlbyname (HW_NCPU_NAME, &pInfo->ProcessorCount, &len, NULL, 0) == -1)
539
#endif
540
    pInfo->ProcessorCount = 1;
541
542
  return WELS_THREAD_ERROR_OK;
543
544
#endif//__linux__
545
3.79k
}
546
547
#endif