1// Copyright 2013 Google Inc. All Rights Reserved.
2//
3// Use of this source code is governed by a BSD-style license
4// that can be found in the COPYING file in the root of the source
5// tree. An additional intellectual property rights grant can be found
6// in the file PATENTS. All contributing project authors may
7// be found in the AUTHORS file in the root of the source tree.
8// -----------------------------------------------------------------------------
9//
10// Multi-threaded worker
11//
12// Original source:
13//  http://git.chromium.org/webm/libwebp.git
14//  100644 blob 7bd451b124ae3b81596abfbcc823e3cb129d3a38  src/utils/thread.h
15
16#ifndef VP9_DECODER_VP9_THREAD_H_
17#define VP9_DECODER_VP9_THREAD_H_
18
19#include "./vpx_config.h"
20
21#ifdef __cplusplus
22extern "C" {
23#endif
24
25#if CONFIG_MULTITHREAD
26
27#if defined(_WIN32)
28#include <errno.h>  // NOLINT
29#include <process.h>  // NOLINT
30#include <windows.h>  // NOLINT
31typedef HANDLE pthread_t;
32typedef CRITICAL_SECTION pthread_mutex_t;
33typedef struct {
34  HANDLE waiting_sem_;
35  HANDLE received_sem_;
36  HANDLE signal_event_;
37} pthread_cond_t;
38
39//------------------------------------------------------------------------------
40// simplistic pthread emulation layer
41
42// _beginthreadex requires __stdcall
43#define THREADFN unsigned int __stdcall
44#define THREAD_RETURN(val) (unsigned int)((DWORD_PTR)val)
45
46static INLINE int pthread_create(pthread_t* const thread, const void* attr,
47                                 unsigned int (__stdcall *start)(void*),
48                                 void* arg) {
49  (void)attr;
50  *thread = (pthread_t)_beginthreadex(NULL,   /* void *security */
51                                      0,      /* unsigned stack_size */
52                                      start,
53                                      arg,
54                                      0,      /* unsigned initflag */
55                                      NULL);  /* unsigned *thrdaddr */
56  if (*thread == NULL) return 1;
57  SetThreadPriority(*thread, THREAD_PRIORITY_ABOVE_NORMAL);
58  return 0;
59}
60
61static INLINE int pthread_join(pthread_t thread, void** value_ptr) {
62  (void)value_ptr;
63  return (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0 ||
64          CloseHandle(thread) == 0);
65}
66
67// Mutex
68static INLINE int pthread_mutex_init(pthread_mutex_t *const mutex,
69                                     void* mutexattr) {
70  (void)mutexattr;
71  InitializeCriticalSection(mutex);
72  return 0;
73}
74
75static INLINE int pthread_mutex_trylock(pthread_mutex_t *const mutex) {
76  return TryEnterCriticalSection(mutex) ? 0 : EBUSY;
77}
78
79static INLINE int pthread_mutex_lock(pthread_mutex_t *const mutex) {
80  EnterCriticalSection(mutex);
81  return 0;
82}
83
84static INLINE int pthread_mutex_unlock(pthread_mutex_t *const mutex) {
85  LeaveCriticalSection(mutex);
86  return 0;
87}
88
89static INLINE int pthread_mutex_destroy(pthread_mutex_t *const mutex) {
90  DeleteCriticalSection(mutex);
91  return 0;
92}
93
94// Condition
95static INLINE int pthread_cond_destroy(pthread_cond_t *const condition) {
96  int ok = 1;
97  ok &= (CloseHandle(condition->waiting_sem_) != 0);
98  ok &= (CloseHandle(condition->received_sem_) != 0);
99  ok &= (CloseHandle(condition->signal_event_) != 0);
100  return !ok;
101}
102
103static INLINE int pthread_cond_init(pthread_cond_t *const condition,
104                                    void* cond_attr) {
105  (void)cond_attr;
106  condition->waiting_sem_ = CreateSemaphore(NULL, 0, 1, NULL);
107  condition->received_sem_ = CreateSemaphore(NULL, 0, 1, NULL);
108  condition->signal_event_ = CreateEvent(NULL, FALSE, FALSE, NULL);
109  if (condition->waiting_sem_ == NULL ||
110      condition->received_sem_ == NULL ||
111      condition->signal_event_ == NULL) {
112    pthread_cond_destroy(condition);
113    return 1;
114  }
115  return 0;
116}
117
118static INLINE int pthread_cond_signal(pthread_cond_t *const condition) {
119  int ok = 1;
120  if (WaitForSingleObject(condition->waiting_sem_, 0) == WAIT_OBJECT_0) {
121    // a thread is waiting in pthread_cond_wait: allow it to be notified
122    ok = SetEvent(condition->signal_event_);
123    // wait until the event is consumed so the signaler cannot consume
124    // the event via its own pthread_cond_wait.
125    ok &= (WaitForSingleObject(condition->received_sem_, INFINITE) !=
126           WAIT_OBJECT_0);
127  }
128  return !ok;
129}
130
131static INLINE int pthread_cond_wait(pthread_cond_t *const condition,
132                                    pthread_mutex_t *const mutex) {
133  int ok;
134  // note that there is a consumer available so the signal isn't dropped in
135  // pthread_cond_signal
136  if (!ReleaseSemaphore(condition->waiting_sem_, 1, NULL))
137    return 1;
138  // now unlock the mutex so pthread_cond_signal may be issued
139  pthread_mutex_unlock(mutex);
140  ok = (WaitForSingleObject(condition->signal_event_, INFINITE) ==
141        WAIT_OBJECT_0);
142  ok &= ReleaseSemaphore(condition->received_sem_, 1, NULL);
143  pthread_mutex_lock(mutex);
144  return !ok;
145}
146#else  // _WIN32
147#include <pthread.h> // NOLINT
148# define THREADFN void*
149# define THREAD_RETURN(val) val
150#endif
151
152#endif  // CONFIG_MULTITHREAD
153
154// State of the worker thread object
155typedef enum {
156  NOT_OK = 0,   // object is unusable
157  OK,           // ready to work
158  WORK          // busy finishing the current task
159} VP9WorkerStatus;
160
161// Function to be called by the worker thread. Takes two opaque pointers as
162// arguments (data1 and data2), and should return false in case of error.
163typedef int (*VP9WorkerHook)(void*, void*);
164
165// Platform-dependent implementation details for the worker.
166typedef struct VP9WorkerImpl VP9WorkerImpl;
167
168// Synchronization object used to launch job in the worker thread
169typedef struct {
170  VP9WorkerImpl *impl_;
171  VP9WorkerStatus status_;
172  VP9WorkerHook hook;     // hook to call
173  void *data1;            // first argument passed to 'hook'
174  void *data2;            // second argument passed to 'hook'
175  int had_error;          // return value of the last call to 'hook'
176} VP9Worker;
177
178// The interface for all thread-worker related functions. All these functions
179// must be implemented.
180typedef struct {
181  // Must be called first, before any other method.
182  void (*init)(VP9Worker *const worker);
183  // Must be called to initialize the object and spawn the thread. Re-entrant.
184  // Will potentially launch the thread. Returns false in case of error.
185  int (*reset)(VP9Worker *const worker);
186  // Makes sure the previous work is finished. Returns true if worker->had_error
187  // was not set and no error condition was triggered by the working thread.
188  int (*sync)(VP9Worker *const worker);
189  // Triggers the thread to call hook() with data1 and data2 arguments. These
190  // hook/data1/data2 values can be changed at any time before calling this
191  // function, but not be changed afterward until the next call to Sync().
192  void (*launch)(VP9Worker *const worker);
193  // This function is similar to launch() except that it calls the
194  // hook directly instead of using a thread. Convenient to bypass the thread
195  // mechanism while still using the VP9Worker structs. sync() must
196  // still be called afterward (for error reporting).
197  void (*execute)(VP9Worker *const worker);
198  // Kill the thread and terminate the object. To use the object again, one
199  // must call reset() again.
200  void (*end)(VP9Worker *const worker);
201} VP9WorkerInterface;
202
203// Install a new set of threading functions, overriding the defaults. This
204// should be done before any workers are started, i.e., before any encoding or
205// decoding takes place. The contents of the interface struct are copied, it
206// is safe to free the corresponding memory after this call. This function is
207// not thread-safe. Return false in case of invalid pointer or methods.
208int vp9_set_worker_interface(const VP9WorkerInterface *const winterface);
209
210// Retrieve the currently set thread worker interface.
211const VP9WorkerInterface *vp9_get_worker_interface(void);
212
213//------------------------------------------------------------------------------
214
215#ifdef __cplusplus
216}    // extern "C"
217#endif
218
219#endif  // VP9_DECODER_VP9_THREAD_H_
220