You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1698 lines
56 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /** @file generic.c
  2. ** @brief Generic - Definition
  3. ** @author Andrea Vedaldi
  4. **/
  5. /*
  6. Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
  7. Copyright (C) 2013 Andrea Vedaldi.
  8. All rights reserved.
  9. This file is part of the VLFeat library and is made available under
  10. the terms of the BSD license (see the COPYING file).
  11. */
  12. /**
  13. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  14. @mainpage Vision Lab Features Library (VLFeat)
  15. @version __VLFEAT_VERSION__
  16. @author The VLFeat Team
  17. @par Copyright &copy; 2012-14 The VLFeat Authors
  18. @par Copyright &copy; 2007-11 Andrea Vedaldi and Brian Fulkerson
  19. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  20. The VLFeat C library implements common computer
  21. vision algorithms, with a special focus on visual features, as used
  22. in state-of-the-art object recognition and image
  23. matching applications.
  24. VLFeat strives to be clutter-free, simple, portable, and well documented.
  25. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  26. @section main-contents Contents
  27. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  28. - **Visual feature detectors and descriptors**
  29. - @subpage sift
  30. - @subpage dsift
  31. - @subpage mser
  32. - @subpage covdet
  33. - @subpage scalespace
  34. - @subpage hog
  35. - @subpage fisher
  36. - @subpage vlad
  37. - @subpage liop
  38. - @subpage lbp
  39. - **Clustering and indexing**
  40. - @subpage kmeans
  41. - @subpage ikmeans.h "Integer K-means (IKM)"
  42. - @subpage hikmeans.h "Hierarchical Integer K-means (HIKM)"
  43. - @subpage gmm
  44. - @subpage aib
  45. - @subpage kdtree
  46. - **Segmentation**
  47. - @subpage slic
  48. - @subpage quickshift
  49. - **Statistical methods**
  50. - @subpage aib
  51. - @subpage homkermap
  52. - @subpage svm
  53. - **Utilities**
  54. - @subpage random
  55. - @subpage mathop
  56. - @subpage stringop.h "String operations"
  57. - @subpage imopv.h "Image operations"
  58. - @subpage pgm.h "PGM image format"
  59. - @subpage heap-def.h "Generic heap object (priority queue)"
  60. - @subpage rodrigues.h "Rodrigues formula"
  61. - @subpage mexutils.h "MATLAB MEX helper functions"
  62. - @subpage getopt_long.h "Drop-in @c getopt_long replacement"
  63. - **General information**
  64. - @subpage conventions
  65. - @subpage generic
  66. - @subpage portability
  67. - @ref resources
  68. - @subpage objects
  69. - @ref threads
  70. - @subpage matlab
  71. - @subpage metaprogram
  72. - @subpage dev
  73. - @subpage glossary
  74. **/
  75. /**
  76. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  77. @page resources Memory and resource handling
  78. @author Andrea Vedaldi
  79. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  80. Some VLFeat functions return pointers to memory blocks or
  81. objects. Only ::vl_malloc, ::vl_calloc, ::vl_realloc and functions
  82. whose name contains either the keywords @c new or @c copy transfer the
  83. ownership of the memory block or object to the caller. The caller must
  84. dispose explicitly of all the resources it owns (by calling ::vl_free
  85. for a memory block, or the appropriate deletion function for an
  86. object).
  87. The memory allocation functions can be customized by
  88. ::vl_set_alloc_func (which sets the implementations of ::vl_malloc,
  89. ::vl_realloc, ::vl_calloc and ::vl_free). Remapping the memory
  90. allocation functions can be done only if there are no currently
  91. allocated VLFeat memory blocks or objects -- thus typically at the
  92. very beginning of a program. The memory allocation functions are a
  93. global property, shared by all threads.
  94. VLFeat uses three rules that simplify handling exceptions when used in
  95. combination which certain environment such as MATLAB.
  96. - The library allocates local memory only through the re-programmable
  97. ::vl_malloc, ::vl_calloc, and ::vl_realloc functions.
  98. - The only resource referenced by VLFeat objects is memory (for
  99. instance, it is illegal for an object to reference an open file).
  100. Other resources such as files or threads may be allocated within a
  101. VLFeat function call, but they are all released before the function
  102. ends, or their ownership is directly transferred to the caller.
  103. - The global library state is an exception. It cannot reference any
  104. local object created by the caller and uses the standard C memory
  105. allocation functions.
  106. In this way, the VLFeat local state can be reset at any time simply by
  107. disposing of all the memory allocated by the library so far. The
  108. latter can be done easily by mapping the memory allocation functions
  109. to implementations that track the memory blocks allocated, and then
  110. disposing of all such blocks. Since the global state does not
  111. reference any local object nor uses the remapped memory functions, it
  112. is unaffected by such an operation; conversely, since no VLFeat object
  113. references anything but memory, this guarantees that all allocated
  114. resources are properly disposed (avoiding leaking resource). This is
  115. used extensively in the design of MATLAB MEX files (see @ref
  116. matlab).
  117. **/
  118. /**
  119. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  120. @page conventions Conventions
  121. @author Andrea Vedaldi
  122. @tableofcontents
  123. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  124. This page summarizes some of the conventions used by the library.
  125. @section conventions-storage Matrix and image storage conventions
  126. If not otherwise specified, matrices in VLFeat are stored in memory in
  127. <em>column major</em> order. Given a matrix $[A_{ij}] \in \real^{m
  128. \times n}$, this amounts of enumerating the elements one column per
  129. time: $A_{11}, A_{21}, \dots, A_{m1}, A_{12}, \dots, A_{mn}$. This
  130. convention is compatible with Fortran, MATLAB, and popular numerical
  131. libraries.
  132. Matrices are often used in the library to pack a number data vectors
  133. $\bx_1,\dots,\bx_n \in \real^m$ of equal dimension together. These are
  134. normally stored as the columns of the matrix:
  135. \[
  136. X = \begin{bmatrix} \bx_1, \dots, \bx_n \end{bmatrix},
  137. \qquad
  138. X \in \real_{m\times n}
  139. \]
  140. In this manner, consecutive elements of each data vector $\bx_i$ is
  141. stored in consecutive memory locations, improving memory access
  142. locality in most algorithms.
  143. Images $I(x,y)$ are stored instead in <em>row-major</em> order,
  144. i.e. one row after the other. Note that an image can be naturally
  145. identified as a matrix $I_{yx}$, where the vertical coordinate $y$
  146. indexes the rows and the horizontal coordinate $x$ the columns. The
  147. image convention amounts to storing this matrix in row-major rather
  148. than column-major order, which is in conflict with the rule given
  149. above. The reason for this choice is that most image processing and
  150. graphical libraries assume this convention; it is, however,
  151. <em>not</em> the same as MATLAB's.
  152. **/
  153. /**
  154. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  155. @page objects Objects
  156. @author Andrea Vedaldi
  157. @tableofcontents
  158. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  159. Many VLFeat algorithms are available in the form of *objects*. The C
  160. language, used by VLFeat, does not support objects explicitly. Here an
  161. object is intended a C structure along with a number of functions (the
  162. object member functions or methods) operating on it. Ideally, the
  163. object data structure is kept opaque to the user, for example by
  164. defining it in the @c .c implementation files which are not accessible
  165. to the library user.
  166. Object names are capitalized and start with the <code>Vl</code> prefix
  167. (for example @c VlExampleObject). Object methods are lowercase and
  168. start with the <code>vl_<object_name>_</code> suffix
  169. (e.g. @c vl_example_object_new).
  170. <!-- ------------------------------------------------------------ -->
  171. @section objects-lifecycle Object lifecycle
  172. <!-- ------------------------------------------------------------ -->
  173. Conceptually, an object undergoes four phases during its lifecycle:
  174. allocation, initialization, finalization, and deallocation:
  175. - **Allocation.** The memory to hold the object structure is allocated.
  176. This is usually done by calling a memory allocation function such as
  177. ::vl_calloc to reserve an object of the required size @c
  178. sizeof(VlExampleObject). Alternatively, the object can simply by
  179. allocated on the stack by declaring a local variable of type
  180. VlExampleObject.
  181. - **Initialization.** The object is initialized by assigning a value to
  182. its data members and potentially allocating a number of resources,
  183. including other objects or memory buffers. Initialization is
  184. done by methods containing the @c init keyword, e.g. @c
  185. vl_example_object_init. Several such methods may be provided.
  186. - **Finalization.** Initialization is undone by finalization, whose main
  187. purpose is to release any resource allocated and still owned by the
  188. object. Finalization is done by the @c vl_example_object_finalize
  189. method.
  190. - **Deallocation.** The memory holding the object structure is
  191. disposed of, for example by calling ::vl_free or automatically when
  192. the corresponding local variable is popped from the stack.
  193. In practice, most VlFeat object are supposed to be created on the
  194. heap. To this end, allocation/initialization and
  195. finalization/deallocation are combined into two operations:
  196. - **Creating a new object.** This allocates a new object on the heap
  197. and initializes it, combining allocation and initialization in a
  198. single operation. It is done by methods containing the @c new keyword,
  199. e.g. @c vl_example_object_new.
  200. - **Deleting an object.** This disposes of an object created by a @c
  201. new method, combining finalization and deallocation, for example
  202. @c vl_example_object_delete.
  203. <!-- ------------------------------------------------------------ -->
  204. @section objects-getters-setters Getters and setters
  205. <!-- ------------------------------------------------------------ -->
  206. Most objects contain a number of methods to get (getters) and set
  207. (setters) properties. These should contain the @c get and @c set
  208. keywords in their name, for example
  209. @code
  210. double x = vl_example_object_get_property () ;
  211. vl_example_object_set_property(x) ;
  212. @endcode
  213. **/
  214. /**
  215. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  216. @page matlab MATLAB integration
  217. @author Andrea Vedaldi
  218. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  219. The VLFeat C library is designed to integrate seamlessly with MATLAB.
  220. Binary compatibility is simplified by the use of the C language
  221. (rather than C++). In addition, the library design follows certain
  222. restrictions that make it compatible with the MATLAB MEX interface.
  223. The main issue in calling a library function from a MATLAB MEX
  224. function is that MATLAB can abort the execution of the MEX function
  225. at any point, either due to an error, or directly upon a user request
  226. (Ctrl-C) (empirically, however, a MEX function seems to be
  227. incorruptible only during the invocation of certain functions of the
  228. MEX API such as @c mexErrMsgTxt).
  229. When a MEX function is interrupted, resources (memory blocks or
  230. objects) whose ownership was transferred from VLFeat to the MEX
  231. function may be leaked. Notice that interrupting a MEX function would
  232. similarly leak any memory block allocated within the MEX function. To
  233. solve this issue, MATLAB provides his own memory manager (@c
  234. mxMalloc, @c mxRealloc, ...). When a MEX file is interrupted or ends,
  235. all memory blocks allocated by using one of such functions are
  236. released, preventing leakage.
  237. In order to integrate VLFeat with this model in the most seamless
  238. way, VLFeat memory allocation functions (::vl_malloc, ::vl_realloc,
  239. ::vl_calloc) are mapped to the corresponding MEX memory allocation
  240. functions. Such functions automatically dispose of all the memory
  241. allocated by a MEX function when the function ends (even because of
  242. an exception). Because of the restrictions of the library design
  243. illustrated in @ref resources, this operation is safe and
  244. correctly dispose of VLFeat local state. As a consequence, it is
  245. possible to call @c mexErrMsgTxt at any point in the MEX function
  246. without worrying about leaking resources.
  247. This however comes at the price of some limitations. Beyond the
  248. restrictions illustrated in @ref resources, here we note that no
  249. VLFeat local resource (memory blocks or objects) can persist across
  250. MEX file invocations. This implies that any result produced by a
  251. VLFeat MEX function must be converted back to a MATLAB object such as
  252. a vector or a structure. In particular, there is no direct way of
  253. creating an object within a MEX file, returning it to MATLAB, and
  254. passing it again to another MEX file.
  255. **/
  256. /**
  257. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  258. @page metaprogram Preprocessor metaprogramming
  259. @author Andrea Vedaldi
  260. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  261. Part of VLFeat code uses a simple form of preprocessor metaprogramming.
  262. This technique is used, similarly to C++ templates, to instantiate
  263. multiple version of a given algorithm for different data types
  264. (e.g. @c float and @c double).
  265. In most cases preprocessor metaprogramming is invisible to the library
  266. user, as it is used only internally.
  267. **/
  268. /**
  269. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  270. @page glossary Glossary
  271. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  272. - <b>Column-major.</b> A <em>M x N </em> matrix <em>A</em> is
  273. stacked with column-major order as the sequence \f$(A_{11}, A_{21},
  274. \dots, A_{12}, \dots)\f$. More in general, when stacking a multi
  275. dimensional array this indicates that the first index is the one
  276. varying most quickly, with the other followed in the natural order.
  277. - <b>Opaque structure.</b> A structure is opaque if the user is not supposed
  278. to access its member directly, but through appropriate interface functions.
  279. Opaque structures are commonly used to define objects.
  280. - <b>Row-major.</b> A <em>M x N </em> matrix <em>A</em> is
  281. stacked with row-major order as the sequence \f$(A_{11}, A_{12},
  282. \dots, A_{21}, \dots)\f$. More in general, when stacking a multi
  283. dimensional array this indicates that the last index is the one
  284. varying most quickly, with the other followed in reverse order.
  285. - <b>Feature frame.</b> A <em>feature frame</em> is the geometrical
  286. description of a visual features. For instance, the frame of
  287. a @ref sift.h "SIFT feature" is oriented disk and the frame of
  288. @ref mser.h "MSER feature" is either a compact and connected set or
  289. a disk.
  290. - <b>Feature descriptor.</b> A <em>feature descriptor</em> is a quantity
  291. (usually a vector) which describes compactly the appearance of an
  292. image region (usually corresponding to a feature frame).
  293. **/
  294. /**
  295. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  296. @page dev Developing the library
  297. @tableofcontents
  298. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  299. This page contains information useful to the developer of VLFeat.
  300. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  301. @section dev-copy Copyright
  302. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  303. A short copyright notice is added at the beginning of each file. For
  304. example:
  305. <pre>
  306. Copyright (C) 2013 Milan Sulc
  307. Copyright (C) 2012 Daniele Perrone.
  308. Copyright (C) 2011-13 Andrea Vedaldi.
  309. All rights reserved.
  310. This file is part of the VLFeat library and is made available under
  311. the terms of the BSD license (see the COPYING file).
  312. </pre>
  313. The copyright of each file is assigned to the authors of the file.
  314. Every author making a substantial contribution to a file should
  315. note its copyright by adding a line to the copyright list with the year
  316. of the modification. Year ranges are acceptable. Lines are never
  317. deleted, only appended, or potentially modified to list
  318. more years.
  319. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  320. @section dev-style Coding style
  321. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  322. <ul>
  323. <li><b>Look at existing code before you start.</b> The general rule
  324. is: try to match the style of the existing code as much as
  325. possible.</li>
  326. <li><b>No white spaces at the end of lines.</b> White spaces introduce
  327. invisible changes in the code that are however picked up by control
  328. version systems such as Git.</li>
  329. <li><b>Descriptive variable names.</b> Most variable names start with
  330. a lower case letter and are capitalized, e.g., @c numElements. Only
  331. the following abbreviations are considered acceptable: @c num. The @c
  332. dimension of a vector is the number of elements it contains (for other
  333. objects that could be a @c size, a @c length, or a @c
  334. numElements). For multi-dimensional arrays, @c dimensions could
  335. indicate the array with each of the @c numDimensions dimensions.</li>
  336. <li><b>Short variable names.</b> For indexes in short for loops it is
  337. fine to use short index names such as @c i, @c j, and @c k. For example:
  338. <pre>
  339. for (i = 0 ; i < numEntries ; ++i) values[i] ++ ;
  340. </pre>
  341. is considered acceptable.</li>
  342. <li><b>Function arguments.</b> VLFeat functions that operate on an
  343. object (member functions) should be passed the object address as first
  344. argument; this argument should be called @c self. For example:
  345. <pre>
  346. void vl_object_do_something(VlObject *self) ;
  347. </pre>
  348. Multi-dimensional arrays should be specified first by their address,
  349. and then by their dimensions. For example
  350. <pre>
  351. void vl_use_array (float * array, vl_size numColumns, vl_size numRows) ; // good
  352. void vl_use_array (vl_size numColumns, vl_size numRows, float * array) ; // bad
  353. </pre>
  354. Arguments that are used as outputs should be specified first (closer to
  355. the left-hand side of an expression). For example
  356. <pre>
  357. void vl_sum_numbers (float * output, float input1, float input2) ; // good
  358. void vl_sum_numbers (float input1, float input2, float * output) ; // bad
  359. </pre>
  360. These rules can be combined. For example
  361. <pre>
  362. void vl_object_sum_to_array (VlObject * self, float * outArray,
  363. vl_size numColumns, vl_size numRows, float * inArray) ; // good
  364. </pre>
  365. Note that in this case no dimension for @c inArray is specified as it
  366. is assumed that @c numColumns and @c numRows are the dimensions of
  367. both arrays.
  368. </li>
  369. </ul>
  370. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  371. @subsection dev-style-matlab MATLAB coding style
  372. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  373. <ul>
  374. <li><b>Help messages.</b> Each @c .m file should include a standard
  375. help comment block (accessible from MATLAB @c help() command).
  376. The first line of the block has a space, the name of the function,
  377. 4 spaces, and a brief command description. The body of the help
  378. message is indented with 4 spaces. For example
  379. @code
  380. % VL_FUNCTION An example function
  381. % VL_FUNCTION() does nothing.
  382. @endcode
  383. The content HELP message itself should follow MATLAB default style.
  384. For example, rather than giving a list of formal input and output
  385. arguments as often done, one simply shows how to use the function, explaining
  386. along the way the different ways the function can be called and
  387. the format of the parameters.
  388. </li>
  389. </ul>
  390. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  391. @section dev-doc Documenting the code
  392. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  393. The VLFeat C library code contains its own in documentation <a
  394. href='http://www.stack.nl/~dimitri/doxygen/'>Doxygen</a> format. The
  395. documentation consists in generic pages, such as the @ref index
  396. "index" and the page you are reading, and documentations for each
  397. library module, usually corresponding to a certain header file.
  398. - **Inline comments.** Inline Doxygen comments are discouraged except
  399. in the documentation of data members of structures. They start with
  400. a capital letter and end with a period. For example:
  401. @code
  402. struct VlExampleStructure {
  403. int aMember ; /\*\*< A useful data member.
  404. }
  405. @endcode
  406. - **Brief comments.** Brief Doxygen comments starts by a capital
  407. and end with a period. The documentation of all functions start
  408. with a brief comment.
  409. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  410. @subsection devl-doc-modules Documenting the library modules
  411. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  412. A library module groups a number of data types and functions that
  413. implement a certain functionality of VLFeat. The documentation of a
  414. library module is generally organized as follows:
  415. 1. A page introducing the module and including a getting started
  416. section (3.g. @ref svm-starting) containing a short tutorial to
  417. quickly familiarize the user with the module (e.g. @ref svm).
  418. 2. One or more pages of detailed technical background discussing the
  419. algorithms implemented. These sections are used not just as part of
  420. the C API, but also as documentation for other APIs such as MATLAB
  421. (e.g. @ref svm-fundamentals).
  422. 3. One or more pages with the structure and function documentation
  423. (e.g. @ref svm.h).
  424. More in detail, consider a module called <em>Example Module</em>. Then one would
  425. typically have:
  426. <ul>
  427. <li>A header or declaration file @c example-module.h. Such a file has an
  428. heading of the type:
  429. @verbinclude example-module-doc.h
  430. This comment block contains a file directive, causing the file to be
  431. included in the documentation, a brief directive, specifying a short
  432. description of what the file is, and a list of authors. A
  433. (non-Doxygen) comment block with a short the copyright notice follows.
  434. The brief directive should include a <code>@@ref</code> directive to point
  435. to the main documentation page describing the module, if there is one.
  436. </li>
  437. <li> An implementation or definition file @c example-module.c. This file
  438. has an heading of the type:
  439. @verbinclude example-module-doc.c
  440. This is similar to the declaration file, except for the content of the
  441. brief comment.
  442. </li>
  443. </ul>
  444. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  445. @subsection devl-doc-functions Documenting functions
  446. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  447. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  448. @subsection devl-doc-structures Documenting structures
  449. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  450. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  451. @subsection devl-doc-structures Documenting objects
  452. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  453. As seen in @ref objects, VLFeat treats certain structures with
  454. an object-like semantics. Usually, a module defines exactly one such
  455. objects. In this case, the object member functions should be grouped
  456. (by using Doxygen grouping functionality) as
  457. - **Construct and destroy** for the @c vl_object_new, @c
  458. vl_object_delete and similar member functions.
  459. - **Set parameters** for setter functions.
  460. - **Retrieve parameters and data** for getter functions.
  461. - **Process data** for functions processing data.
  462. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  463. @subsection devl-doc-bib Bibliographic references
  464. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  465. Since version 0.9.14, the VLFeat C library documentation makes use of
  466. a proper bibliographic reference in BibTeX format (see the file @c
  467. docsrc/vlfeat.bib). Doxygen uses this file when it sees instances of
  468. the <code>@@cite{xyz}</code> command. Here @c xyz is a BibTeX
  469. key. For example, @c vlfeat.bib file contains the entry:
  470. <pre>
  471. @@inproceedings{martin97the-det-curve,
  472. Author = {A. Martin and G. Doddington and T. Kamm and M. Ordowski and M. Przybocki},
  473. Booktitle = {Proc. Conf. on Speech Communication and Technology},
  474. Title = {The {DET} curve in assessment of detection task performance},
  475. Year = {1997}}
  476. </pre>
  477. For example, the Doxygen directive
  478. <code>@@cite{martin97the-det-curve}</code> generates the output
  479. @cite{martin97the-det-curve}, which is a link to the corresponding
  480. entry in the bibliography.
  481. **/
  482. /**
  483. @file generic.h
  484. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  485. @page generic General support functionalities
  486. @author Andrea Vedaldi
  487. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  488. VLFeat contains several support functionalities addressing the C
  489. preprocessors, using multiple threads (including parallel computations),
  490. handling errors, allocating memory, etc. These are described in
  491. the following pages:
  492. - @subpage resources
  493. - @subpage threads
  494. - @subpage misc
  495. **/
  496. /**
  497. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  498. @page misc Preprocssor, library state, etc.
  499. @author Andrea Vedaldi
  500. @tableofcontents
  501. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  502. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  503. @section misc-preproc C preprocessor helpers
  504. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  505. VLFeat provides a few C preprocessor macros of general
  506. utility. These include stringification (::VL_STRINGIFY,
  507. ::VL_XSTRINGIFY) and concatenation (::VL_CAT, ::VL_XCAT) of symbols.
  508. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  509. @section misc-state VLFeat state and configuration parameters
  510. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  511. VLFeat has some global configuration parameters that can
  512. changed. Changing the configuration is thread unsave
  513. (@ref threads). Use ::vl_set_simd_enabled to toggle the use of
  514. a SIMD unit (Intel SSE code), ::vl_set_alloc_func to change
  515. the memory allocation functions, and ::vl_set_printf_func
  516. to change the logging function.
  517. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  518. @section misc-error Error handling
  519. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  520. Some VLFeat functions signal errors in a way similar to the
  521. standard C library. In case of error, a VLFeat function
  522. may return an error code directly,
  523. or an invalid result (for instance a negative file descriptor or a null
  524. pointer). Then ::vl_get_last_error and ::vl_get_last_error_message can be used
  525. to retrieve further details about the error (these functions should be
  526. used right after an error has occurred, before any other VLFeat call).
  527. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  528. @section misc-memory Memory allocation
  529. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  530. VLFeat uses the ::vl_malloc, ::vl_realloc, ::vl_calloc and ::vl_free
  531. functions to allocate memory. Normally these functions are mapped to
  532. the underlying standard C library implementations. However
  533. ::vl_set_alloc_func can be used to map them to other
  534. implementations. For instance, in MATALB MEX files these functions
  535. are mapped to the MATLAB equivalent which has a garbage collection
  536. mechanism to cope with interruptions during execution.
  537. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  538. @section misc-logging Logging
  539. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  540. VLFeat uses the macros ::VL_PRINT and ::VL_PRINTF to print progress
  541. or debug informations. These functions are normally mapped to the @c
  542. printf function of the underlying standard C library. However
  543. ::vl_set_printf_func can be used to map it to a different
  544. implementation. For instance, in MATLAB MEX files this function is
  545. mapped to @c mexPrintf. Setting the function to @c NULL disables
  546. logging.
  547. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  548. @section misc-time Measuring time
  549. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  550. VLFeat provides ::vl_tic and ::vl_toc as an easy way of measuring
  551. elapsed time.
  552. **/
  553. /**
  554. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  555. @page threads Threading
  556. @tableofcontents
  557. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  558. VLFeat supports for threaded computations can be used to take advantage
  559. of multi-core architectures. Threading support includes:
  560. - Supporting using VLFeat functions and objects from multiple threads
  561. simultaneously. This is discussed in @ref threads-multiple.
  562. - Using multiple cores to accelerate computations. This is
  563. discussed in @ref threads-parallel.
  564. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  565. @section threads-multiple Using VLFeat from multiple threads
  566. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  567. VLFeat can be used from multiple threads simultaneously if proper
  568. rules are followed.
  569. - <b>A VLFeat object instance is accessed only from one thread at any
  570. given time.</b> Functions operating on objects (member functions)
  571. are conditionally thread safe: the same function may be called
  572. simultaneously from multiple threads provided that it operates on
  573. different, independent objects. However, modifying the same object
  574. from multiple threads (using the same or different member functions)
  575. is possible only from one thread at any given time, and should
  576. therefore be synchronized. Certain VLFeat objects may contain
  577. features specific to simplify multi-threaded operations
  578. (e.g. ::VlKDForest).
  579. - <b>Thread-safe global functions are used.</b> These include
  580. thread-specific operations such as retrieving the last error by
  581. ::vl_get_last_error and obtaining the thread-specific random number
  582. generator instance by ::vl_get_rand. In these cases, the functions
  583. operate on thread-specific data that VLFeat creates and
  584. maintains. Note in particular that each thread has an independent
  585. default random number generator (as returned by
  586. ::vl_get_rand). VLFeat objects that involve using random numbers
  587. will typically use the random number generator of the thread
  588. currently accessing the object (although an object-specific
  589. generator can be often be specified instead).
  590. - <b>Any other global function is considered non-thread safe and is
  591. accessed exclusively by one thread at a time.</b> A small number of
  592. operations are non-reentrant <em>and</em> affect all threads
  593. simultaneously. These are restricted to changing certain global
  594. configuration parameters, such as the memory allocation functions by
  595. ::vl_set_alloc_func. These operations are <em>not</em> thread safe
  596. and are preferably executed before multiple threads start to operate
  597. with the library.
  598. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  599. @section threads-parallel Parallel computations
  600. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  601. VLFeat uses OpenMP to implement parallel computations. Generally, this
  602. means that multiple cores are uses appropriately and transparently,
  603. provided that other multi-threaded parts of the application use OpenMP
  604. and that VLFeat and the application link to the same OpenMP library.
  605. If finer control is required, read on.
  606. VLFeat functions avoids affecting OpenMP global state, including the
  607. desired number of computational threads, in order to minimize side
  608. effects to the linked application (e.g. MATLAB). Instead, VLFeat
  609. duplicates a few OpenMP control parameters when needed (this approach
  610. is similar to the method used by other libraries such as Intel MKL).
  611. The maximum number of threads available to the application can be
  612. obtained by ::vl_get_thread_limit (for OpenMP version 3.0 and
  613. greater). This limit is controlled by the OpenMP library (the function
  614. is a wrapper around @c omp_get_thread_limit), which in turn may
  615. determined that based on the number of computational cores or the
  616. value of the @c OMP_THREAD_LIMIT variable when the program is
  617. launched. This value is an upper bound on the number of computation
  618. threads that can be used at any time.
  619. The maximum number of computational thread that VLFeat should use is
  620. set by ::vl_set_num_threads() and retrieved by ::vl_get_max_threads().
  621. This number is a target value as well as an upper bound to the number
  622. of threads used by VLFeat. This value is stored in the VLFeat private
  623. state and is not necessarily equal to the corresponding OpenMP state
  624. variable retrieved by calling @c omp_get_max_threads(). @c
  625. vl_set_num_threads(1) disables the use of multiple threads and @c
  626. vl_set_num_threads(0) uses the value returned by the OpenMP call @c
  627. omp_get_max_threads(). The latter value is controlled, for example, by
  628. calling @c omp_set_num_threads() in the application. Note that:
  629. - @c vl_set_num_threads(0) determines the number of treads using @c
  630. omp_get_max_threads() *when it is called*. Subsequent calls to @c
  631. omp_set_num_threads() will therefore *not* affect the number of
  632. threads used by VLFeat.
  633. - @c vl_set_num_threads(vl_get_thread_limit()) causes VLFeat use all
  634. the available threads, regardless on the number of threads set
  635. within the application by calls to @c omp_set_num_threads().
  636. - OpenMP may still dynamically decide to use a smaller number of
  637. threads in any specific parallel computation.
  638. @sa http://software.intel.com/sites/products/documentation/doclib/mkl_sa/11/mkl_userguide_win/GUID-C2295BC8-DD22-466B-94C9-5FAA79D4F56D.htm
  639. http://software.intel.com/sites/products/documentation/doclib/mkl_sa/11/mkl_userguide_win/index.htm#GUID-DEEF0363-2B34-4BAB-87FA-A75DBE842040.htm
  640. http://software.intel.com/sites/products/documentation/hpc/mkl/lin/MKL_UG_managing_performance/Using_Additional_Threading_Control.htm
  641. **/
  642. #include "generic.h"
  643. #include <assert.h>
  644. #include <stdlib.h>
  645. #include <stdio.h>
  646. #include <stdarg.h>
  647. #include <math.h>
  648. #if defined(VL_OS_WIN)
  649. #include <Windows.h>
  650. #endif
  651. #if ! defined(VL_DISABLE_THREADS) && defined(VL_THREADS_POSIX)
  652. #include <pthread.h>
  653. #endif
  654. #if defined(VL_OS_MACOSX) || defined(VL_OS_LINUX)
  655. #include <unistd.h>
  656. #endif
  657. #if defined(_OPENMP)
  658. #include <omp.h>
  659. #endif
  660. /* ---------------------------------------------------------------- */
  661. /* Global and thread states */
  662. /* ---------------------------------------------------------------- */
  663. /* Thread state */
  664. typedef struct _VlThreadState
  665. {
  666. /* errors */
  667. int lastError ;
  668. char lastErrorMessage [VL_ERR_MSG_LEN] ;
  669. /* random number generator */
  670. VlRand rand ;
  671. /* time */
  672. #if defined(VL_OS_WIN)
  673. LARGE_INTEGER ticFreq ;
  674. LARGE_INTEGER ticMark ;
  675. #else
  676. clock_t ticMark ;
  677. #endif
  678. } VlThreadState ;
  679. /* Gobal state */
  680. typedef struct _VlState
  681. {
  682. /* The thread state uses either a mutex (POSIX)
  683. or a critical section (Win) */
  684. #if defined(VL_DISABLE_THREADS)
  685. VlThreadState * threadState ;
  686. #else
  687. #if defined(VL_THREADS_POSIX)
  688. pthread_key_t threadKey ;
  689. pthread_mutex_t mutex ;
  690. pthread_t mutexOwner ;
  691. pthread_cond_t mutexCondition ;
  692. size_t mutexCount ;
  693. #elif defined(VL_THREADS_WIN)
  694. DWORD tlsIndex ;
  695. CRITICAL_SECTION mutex;
  696. #endif
  697. #endif /* VL_DISABLE_THREADS */
  698. /* Configurable functions */
  699. int (*printf_func) (char const * format, ...) ;
  700. void *(*malloc_func) (size_t) ;
  701. void *(*realloc_func) (void*,size_t) ;
  702. void *(*calloc_func) (size_t, size_t) ;
  703. void (*free_func) (void*) ;
  704. #if defined(VL_ARCH_IX86) || defined(VL_ARCH_X64) || defined(VL_ARCH_IA64)
  705. VlX86CpuInfo cpuInfo ;
  706. #endif
  707. vl_size numCPUs ;
  708. vl_bool simdEnabled ;
  709. vl_size numThreads ;
  710. } VlState ;
  711. /* Global state instance */
  712. VlState _vl_state ;
  713. /* ----------------------------------------------------------------- */
  714. VL_INLINE VlState * vl_get_state () ;
  715. VL_INLINE VlThreadState * vl_get_thread_specific_state () ;
  716. static void vl_lock_state (void) ;
  717. static void vl_unlock_state (void) ;
  718. static VlThreadState * vl_thread_specific_state_new (void) ;
  719. static void vl_thread_specific_state_delete (VlThreadState * self) ;
  720. /** @brief Get VLFeat version string
  721. ** @return the library version string.
  722. **/
  723. char const *
  724. vl_get_version_string ()
  725. {
  726. return VL_VERSION_STRING ;
  727. }
  728. /** @brief Get VLFeat configuration string.
  729. ** @return a new configuration string.
  730. **
  731. ** The function returns a new string containing a human readable
  732. ** description of the library configuration.
  733. **/
  734. char *
  735. vl_configuration_to_string_copy ()
  736. {
  737. char * string = 0 ;
  738. int length = 0 ;
  739. char * staticString = vl_static_configuration_to_string_copy() ;
  740. char * cpuString =
  741. #if defined(VL_ARCH_IX86) || defined(VL_ARCH_X64) || defined(VL_ARCH_IA64)
  742. _vl_x86cpu_info_to_string_copy(&vl_get_state()->cpuInfo) ;
  743. #else
  744. "Generic CPU" ;
  745. #endif
  746. #if defined(DEBUG)
  747. int const debug = 1 ;
  748. #else
  749. int const debug = 0 ;
  750. #endif
  751. while (string == 0) {
  752. if (length > 0) {
  753. string = (char*)vl_malloc(sizeof(char) * length) ;
  754. if (string == NULL) break ;
  755. }
  756. length = snprintf(string, length,
  757. "VLFeat version %s\n"
  758. " Static config: %s\n"
  759. " %" VL_FMT_SIZE " CPU(s): %s\n"
  760. #if defined(_OPENMP)
  761. " OpenMP: max threads: %d (library: %" VL_FMT_SIZE ")\n"
  762. #endif
  763. " Debug: %s\n",
  764. vl_get_version_string (),
  765. staticString,
  766. vl_get_num_cpus(), cpuString,
  767. #if defined(_OPENMP)
  768. omp_get_max_threads(), vl_get_max_threads(),
  769. #endif
  770. VL_YESNO(debug)) ;
  771. length += 1 ;
  772. }
  773. if (staticString) vl_free(staticString) ;
  774. if (cpuString) vl_free(cpuString) ;
  775. return string ;
  776. }
  777. /** @internal @brief A printf that does not do anything */
  778. static int
  779. do_nothing_printf (char const* format VL_UNUSED, ...)
  780. {
  781. return 0 ;
  782. }
  783. /** @internal
  784. ** @brief Lock VLFeat state
  785. **
  786. ** The function locks VLFeat global state mutex.
  787. **
  788. ** The mutex is recursive: locking multiple times from the same thread
  789. ** is a valid operations, but requires an equivalent number
  790. ** of calls to ::vl_unlock_state.
  791. **
  792. ** @sa ::vl_unlock_state
  793. **/
  794. static void
  795. vl_lock_state (void)
  796. {
  797. #if ! defined(VL_DISABLE_THREADS)
  798. #if defined(VL_THREADS_POSIX)
  799. VlState * state = vl_get_state () ;
  800. pthread_t thisThread = pthread_self () ;
  801. pthread_mutex_lock (&state->mutex) ;
  802. if (state->mutexCount >= 1 &&
  803. pthread_equal (state->mutexOwner, thisThread)) {
  804. state->mutexCount ++ ;
  805. } else {
  806. while (state->mutexCount >= 1) {
  807. pthread_cond_wait (&state->mutexCondition, &state->mutex) ;
  808. }
  809. state->mutexOwner = thisThread ;
  810. state->mutexCount = 1 ;
  811. }
  812. pthread_mutex_unlock (&state->mutex) ;
  813. #elif defined(VL_THREADS_WIN)
  814. EnterCriticalSection((LPCRITICAL_SECTION)&vl_get_state()->mutex);
  815. #endif
  816. #endif
  817. }
  818. /** @internal
  819. ** @brief Unlock VLFeat state
  820. **
  821. ** The function unlocks VLFeat global state mutex.
  822. **
  823. ** @sa ::vl_lock_state
  824. **/
  825. static void
  826. vl_unlock_state (void)
  827. {
  828. #if ! defined(VL_DISABLE_THREADS)
  829. #if defined(VL_THREADS_POSIX)
  830. VlState * state = vl_get_state () ;
  831. pthread_mutex_lock (&state->mutex) ;
  832. -- state->mutexCount ;
  833. if (state->mutexCount == 0) {
  834. pthread_cond_signal (&state->mutexCondition) ;
  835. }
  836. pthread_mutex_unlock (&state->mutex) ;
  837. #elif defined(VL_THREADS_WIN)
  838. LeaveCriticalSection (&vl_get_state()->mutex) ;
  839. #endif
  840. #endif
  841. }
  842. /** @internal
  843. ** @brief Return VLFeat global state
  844. **
  845. ** The function returns a pointer to VLFeat global state.
  846. **
  847. ** @return pointer to the global state structure.
  848. **/
  849. VL_INLINE VlState *
  850. vl_get_state (void)
  851. {
  852. return &_vl_state ;
  853. }
  854. /** @internal@brief Get VLFeat thread state
  855. ** @return pointer to the thread state structure.
  856. **
  857. ** The function returns a pointer to VLFeat thread state.
  858. **/
  859. VL_INLINE VlThreadState *
  860. vl_get_thread_specific_state (void)
  861. {
  862. #ifdef VL_DISABLE_THREADS
  863. return vl_get_state()->threadState ;
  864. #else
  865. VlState * state ;
  866. VlThreadState * threadState ;
  867. vl_lock_state() ;
  868. state = vl_get_state() ;
  869. #if defined(VL_THREADS_POSIX)
  870. threadState = (VlThreadState *) pthread_getspecific(state->threadKey) ;
  871. #elif defined(VL_THREADS_WIN)
  872. threadState = (VlThreadState *) TlsGetValue(state->tlsIndex) ;
  873. #endif
  874. if (! threadState) {
  875. threadState = vl_thread_specific_state_new () ;
  876. }
  877. #if defined(VL_THREADS_POSIX)
  878. pthread_setspecific(state->threadKey, threadState) ;
  879. #elif defined(VL_THREADS_WIN)
  880. TlsSetValue(state->tlsIndex, threadState) ;
  881. #endif
  882. vl_unlock_state() ;
  883. return threadState ;
  884. #endif
  885. }
  886. /* ---------------------------------------------------------------- */
  887. /** @brief Get the number of CPU cores of the host
  888. ** @return number of CPU cores.
  889. **/
  890. vl_size
  891. vl_get_num_cpus (void)
  892. {
  893. return vl_get_state()->numCPUs ;
  894. }
  895. /** @fn ::vl_set_simd_enabled(vl_bool)
  896. ** @brief Toggle usage of SIMD instructions
  897. ** @param x @c true if SIMD instructions are used.
  898. **
  899. ** Notice that SIMD instructions are used only if the CPU model
  900. ** supports them. Note also that data alignment may restrict the use
  901. ** of such instructions.
  902. **
  903. ** @see ::vl_cpu_has_sse2(), ::vl_cpu_has_sse3(), etc.
  904. **/
  905. void
  906. vl_set_simd_enabled (vl_bool x)
  907. {
  908. vl_get_state()->simdEnabled = x ;
  909. }
  910. /** @brief Are SIMD instructons enabled?
  911. ** @return @c true if SIMD instructions are enabled.
  912. **/
  913. vl_bool
  914. vl_get_simd_enabled (void)
  915. {
  916. return vl_get_state()->simdEnabled ;
  917. }
  918. /** @brief Check for AVX instruction set
  919. ** @return @c true if AVX is present.
  920. **/
  921. vl_bool
  922. vl_cpu_has_avx (void)
  923. {
  924. #if defined(VL_ARCH_IX86) || defined(VL_ARCH_X64) || defined(VL_ARCH_IA64)
  925. return vl_get_state()->cpuInfo.hasAVX ;
  926. #else
  927. return VL_FALSE ;
  928. #endif
  929. }
  930. /** @brief Check for SSE3 instruction set
  931. ** @return @c true if SSE3 is present.
  932. **/
  933. vl_bool
  934. vl_cpu_has_sse3 (void)
  935. {
  936. #if defined(VL_ARCH_IX86) || defined(VL_ARCH_X64) || defined(VL_ARCH_IA64)
  937. return vl_get_state()->cpuInfo.hasSSE3 ;
  938. #else
  939. return VL_FALSE ;
  940. #endif
  941. }
  942. /** @brief Check for SSE2 instruction set
  943. ** @return @c true if SSE2 is present.
  944. **/
  945. vl_bool
  946. vl_cpu_has_sse2 (void)
  947. {
  948. #if defined(VL_ARCH_IX86) || defined(VL_ARCH_X64) || defined(VL_ARCH_IA64)
  949. return vl_get_state()->cpuInfo.hasSSE2 ;
  950. #else
  951. return VL_FALSE ;
  952. #endif
  953. }
  954. /* ---------------------------------------------------------------- */
  955. /** @brief Get the number of computational threads available to the application
  956. ** @return number of threads.
  957. **
  958. ** This function wraps the OpenMP function @c
  959. ** omp_get_thread_limit(). If VLFeat was compiled without OpenMP
  960. ** support, this function returns 1. If VLFeat was compiled with
  961. ** OpenMP prior to version 3.0 (2008/05), it returns 0.
  962. **
  963. ** @sa @ref threads-parallel
  964. **/
  965. vl_size
  966. vl_get_thread_limit (void)
  967. {
  968. #if defined(_OPENMP)
  969. #if _OPENMP >= 200805
  970. /* OpenMP version >= 3.0 */
  971. return omp_get_thread_limit() ;
  972. #else
  973. return 0 ;
  974. #endif
  975. #else
  976. return 1 ;
  977. #endif
  978. }
  979. /** @brief Get the maximum number of computational threads used by VLFeat.
  980. ** @return number of threads.
  981. **
  982. ** This function returns the maximum number of thread used by
  983. ** VLFeat. VLFeat will try to use this number of computational
  984. ** threads and never exceed it.
  985. **
  986. ** This is similar to the OpenMP function @c omp_get_max_threads();
  987. ** however, it reads a parameter private to VLFeat which is
  988. ** independent of the value used by the OpenMP library.
  989. **
  990. ** If VLFeat was compiled without OpenMP support, this function
  991. ** returns 1.
  992. **
  993. ** @sa vl_set_num_threads(), @ref threads-parallel
  994. **/
  995. vl_size
  996. vl_get_max_threads (void)
  997. {
  998. #if defined(_OPENMP)
  999. return vl_get_state()->numThreads ;
  1000. #else
  1001. return 1 ;
  1002. #endif
  1003. }
  1004. /** @brief Set the maximum number of threads used by VLFeat.
  1005. ** @param numThreads number of threads to use.
  1006. **
  1007. ** This function sets the maximum number of computational threads
  1008. ** that will be used by VLFeat. VLFeat may in practice use fewer
  1009. ** threads (for example because @a numThreads is larger than the
  1010. ** number of computational cores in the host, or because the number
  1011. ** of threads exceeds the limit available to the application).
  1012. **
  1013. ** If @c numThreads is set to 0, then VLFeat sets the number of
  1014. ** threads to the OpenMP current maximum, obtained by calling @c
  1015. ** omp_get_max_threads().
  1016. **
  1017. ** This function is similar to @c omp_set_num_threads() but changes a
  1018. ** parameter internal to VLFeat rather than affecting OpenMP global
  1019. ** state.
  1020. **
  1021. ** If VLFeat was compiled without, this function does nothing.
  1022. **
  1023. ** @sa vl_get_max_threads(), @ref threads-parallel
  1024. **/
  1025. #if defined(_OPENMP)
  1026. void
  1027. vl_set_num_threads (vl_size numThreads)
  1028. {
  1029. if (numThreads == 0) {
  1030. numThreads = omp_get_max_threads() ;
  1031. }
  1032. vl_get_state()->numThreads = numThreads ;
  1033. }
  1034. #else
  1035. void
  1036. vl_set_num_threads (vl_size numThreads VL_UNUSED) { }
  1037. #endif
  1038. /* ---------------------------------------------------------------- */
  1039. /** @brief Set last VLFeat error
  1040. ** @param error error code.
  1041. ** @param errorMessage error message format string.
  1042. ** @param ... format string arguments.
  1043. ** @return error code.
  1044. **
  1045. ** The function sets the code and optionally the error message
  1046. ** of the last encountered error. @a errorMessage is the message
  1047. ** format. It uses the @c printf convention and is followed by
  1048. ** the format arguments. The maximum length of the error message is
  1049. ** given by ::VL_ERR_MSG_LEN (longer messages are truncated).
  1050. **
  1051. ** Passing @c NULL as @a errorMessage
  1052. ** sets the error message to the empty string.
  1053. **/
  1054. int
  1055. vl_set_last_error (int error, char const * errorMessage, ...)
  1056. {
  1057. VlThreadState * state = vl_get_thread_specific_state() ;
  1058. va_list args;
  1059. va_start(args, errorMessage) ;
  1060. if (errorMessage) {
  1061. #ifdef VL_COMPILER_LCC
  1062. vsprintf(state->lastErrorMessage, errorMessage, args) ;
  1063. #else
  1064. vsnprintf(state->lastErrorMessage,
  1065. sizeof(state->lastErrorMessage)/sizeof(char),
  1066. errorMessage, args) ;
  1067. #endif
  1068. } else {
  1069. state->lastErrorMessage[0] = 0 ;
  1070. }
  1071. state->lastError = error ;
  1072. va_end(args) ;
  1073. return error ;
  1074. }
  1075. /** @brief Get the code of the last error
  1076. ** @return error code.
  1077. ** @sa ::vl_get_last_error_message.
  1078. **/
  1079. int
  1080. vl_get_last_error (void) {
  1081. return vl_get_thread_specific_state()->lastError ;
  1082. }
  1083. /** @brief Get the last error message
  1084. ** @return pointer to the error message.
  1085. ** @sa ::vl_get_last_error.
  1086. **/
  1087. char const *
  1088. vl_get_last_error_message (void)
  1089. {
  1090. return vl_get_thread_specific_state()->lastErrorMessage ;
  1091. }
  1092. /* ---------------------------------------------------------------- */
  1093. /** @brief Set memory allocation functions
  1094. ** @param malloc_func pointer to @c malloc.
  1095. ** @param realloc_func pointer to @c realloc.
  1096. ** @param calloc_func pointer to @c calloc.
  1097. ** @param free_func pointer to @c free.
  1098. **/
  1099. void
  1100. vl_set_alloc_func (void *(*malloc_func) (size_t),
  1101. void *(*realloc_func) (void*, size_t),
  1102. void *(*calloc_func) (size_t, size_t),
  1103. void (*free_func) (void*))
  1104. {
  1105. VlState * state ;
  1106. //vl_lock_state () ;
  1107. state = vl_get_state() ;
  1108. state->malloc_func = malloc_func ;
  1109. state->realloc_func = realloc_func ;
  1110. state->calloc_func = calloc_func ;
  1111. state->free_func = free_func ;
  1112. //vl_unlock_state () ;
  1113. }
  1114. /** @brief Allocate a memory block
  1115. ** @param n size in bytes of the new block.
  1116. ** @return pointer to the allocated block.
  1117. **
  1118. ** This function allocates a memory block of the specified size.
  1119. ** The synopsis is the same as the POSIX @c malloc function.
  1120. **/
  1121. void *
  1122. vl_malloc (size_t n)
  1123. {
  1124. return (vl_get_state()->malloc_func)(n) ;
  1125. //return (memalign)(32,n) ;
  1126. }
  1127. /** @brief Reallocate a memory block
  1128. ** @param ptr pointer to a memory block previously allocated.
  1129. ** @param n size in bytes of the new block.
  1130. ** @return pointer to the new block.
  1131. **
  1132. ** This function reallocates a memory block to change its size.
  1133. ** The synopsis is the same as the POSIX @c realloc function.
  1134. **/
  1135. void *
  1136. vl_realloc (void* ptr, size_t n)
  1137. {
  1138. return (vl_get_state()->realloc_func)(ptr, n) ;
  1139. }
  1140. /** @brief Free and clear a memory block
  1141. ** @param n number of items to allocate.
  1142. ** @param size size in bytes of an item.
  1143. ** @return pointer to the new block.
  1144. **
  1145. ** This function allocates and clears a memory block.
  1146. ** The synopsis is the same as the POSIX @c calloc function.
  1147. **/
  1148. void *
  1149. vl_calloc (size_t n, size_t size)
  1150. {
  1151. return (vl_get_state()->calloc_func)(n, size) ;
  1152. }
  1153. /** @brief Free a memory block
  1154. ** @param ptr pointer to the memory block.
  1155. **
  1156. ** This function frees a memory block allocated by ::vl_malloc,
  1157. ** ::vl_calloc, or ::vl_realloc. The synopsis is the same as the POSIX
  1158. ** @c malloc function.
  1159. **/
  1160. void
  1161. vl_free (void *ptr)
  1162. {
  1163. (vl_get_state()->free_func)(ptr) ;
  1164. }
  1165. /* ---------------------------------------------------------------- */
  1166. /** @brief Set the printf function
  1167. ** @param printf_func pointer to a @c printf implementation.
  1168. ** Set @c print_func to NULL to disable printf.
  1169. **/
  1170. void
  1171. vl_set_printf_func (printf_func_t printf_func)
  1172. {
  1173. vl_get_state()->printf_func = printf_func ? printf_func : do_nothing_printf ;
  1174. }
  1175. /** @brief Get the printf function
  1176. ** @return printf_func pointer to the @c printf implementation.
  1177. ** @sa ::vl_set_printf_func.
  1178. **/
  1179. printf_func_t
  1180. vl_get_printf_func (void) {
  1181. return vl_get_state()->printf_func ;
  1182. }
  1183. /* ---------------------------------------------------------------- */
  1184. /** @brief Get processor time
  1185. ** @return processor time in seconds.
  1186. ** @sa ::vl_tic, ::vl_toc
  1187. **/
  1188. double
  1189. vl_get_cpu_time ()
  1190. {
  1191. #ifdef VL_OS_WIN
  1192. VlThreadState * threadState = vl_get_thread_specific_state() ;
  1193. LARGE_INTEGER mark ;
  1194. QueryPerformanceCounter (&mark) ;
  1195. return (double)mark.QuadPart / (double)threadState->ticFreq.QuadPart ;
  1196. #else
  1197. return (double)clock() / (double)CLOCKS_PER_SEC ;
  1198. #endif
  1199. }
  1200. /** @brief Reset processor time reference
  1201. ** The function resets VLFeat TIC/TOC time reference. There is one
  1202. ** such reference per thread.
  1203. ** @sa ::vl_get_cpu_time, ::vl_toc.
  1204. **/
  1205. void
  1206. vl_tic (void)
  1207. {
  1208. VlThreadState * threadState = vl_get_thread_specific_state() ;
  1209. #ifdef VL_OS_WIN
  1210. QueryPerformanceCounter (&threadState->ticMark) ;
  1211. #else
  1212. threadState->ticMark = clock() ;
  1213. #endif
  1214. }
  1215. /** @brief Get elapsed time since tic
  1216. ** @return elapsed time in seconds.
  1217. **
  1218. ** The function
  1219. ** returns the processor time elapsed since ::vl_tic was called last.
  1220. **
  1221. ** @remark In multi-threaded applications, there is an independent
  1222. ** timer for each execution thread.
  1223. **
  1224. ** @remark On UNIX, this function uses the @c clock() system call.
  1225. ** On Windows, it uses the @c QueryPerformanceCounter() system call,
  1226. ** which is more accurate than @c clock() on this platform.
  1227. **/
  1228. double
  1229. vl_toc (void)
  1230. {
  1231. VlThreadState * threadState = vl_get_thread_specific_state() ;
  1232. #ifdef VL_OS_WIN
  1233. LARGE_INTEGER tocMark ;
  1234. QueryPerformanceCounter(&tocMark) ;
  1235. return (double) (tocMark.QuadPart - threadState->ticMark.QuadPart) /
  1236. threadState->ticFreq.QuadPart ;
  1237. #else
  1238. return (double) (clock() - threadState->ticMark) / CLOCKS_PER_SEC ;
  1239. #endif
  1240. }
  1241. /* ---------------------------------------------------------------- */
  1242. /** @brief Get the default random number generator.
  1243. ** @return random number generator.
  1244. **
  1245. ** The function returns a pointer to the default
  1246. ** random number generator.
  1247. ** There is one such generator per thread.
  1248. **/
  1249. VL_EXPORT VlRand *
  1250. vl_get_rand (void)
  1251. {
  1252. return &vl_get_thread_specific_state()->rand ;
  1253. }
  1254. /* ---------------------------------------------------------------- */
  1255. /* Library construction and destruction routines */
  1256. /* --------------------------------------------------------------- */
  1257. /** @internal@brief Construct a new thread state object
  1258. ** @return new state structure.
  1259. **/
  1260. static VlThreadState *
  1261. vl_thread_specific_state_new (void)
  1262. {
  1263. VlThreadState * self ;
  1264. #if defined(DEBUG)
  1265. printf("VLFeat DEBUG: thread constructor begins.\n") ;
  1266. #endif
  1267. self = (VlThreadState*)malloc(sizeof(VlThreadState)) ;
  1268. self->lastError = 0 ;
  1269. self->lastErrorMessage[0] = 0 ;
  1270. #if defined(VL_OS_WIN)
  1271. QueryPerformanceFrequency (&self->ticFreq) ;
  1272. self->ticMark.QuadPart = 0 ;
  1273. #else
  1274. self->ticMark = 0 ;
  1275. #endif
  1276. vl_rand_init (&self->rand) ;
  1277. return self ;
  1278. }
  1279. /** @internal@brief Delete a thread state structure
  1280. ** @param self thread state object.
  1281. **/
  1282. static void
  1283. vl_thread_specific_state_delete (VlThreadState * self)
  1284. {
  1285. #if defined(DEBUG)
  1286. printf("VLFeat DEBUG: thread destructor begins.\n") ;
  1287. #endif
  1288. free (self) ;
  1289. }
  1290. /* ---------------------------------------------------------------- */
  1291. /* DLL entry and exit points */
  1292. /* ---------------------------------------------------------------- */
  1293. /* A constructor and a destructor must be called to initialize or dispose of VLFeat
  1294. * state when the DLL is loaded or unloaded. This is obtained
  1295. * in different ways depending on the operating system.
  1296. */
  1297. #if (defined(VL_OS_LINUX) || defined(VL_OS_MACOSX)) && defined(VL_COMPILER_GNUC)
  1298. static void vl_constructor () __attribute__ ((constructor)) ;
  1299. static void vl_destructor () __attribute__ ((destructor)) ;
  1300. #endif
  1301. #if defined(VL_OS_WIN)
  1302. static void vl_constructor () ;
  1303. static void vl_destructor () ;
  1304. BOOL WINAPI DllMain(
  1305. HINSTANCE hinstDLL, // handle to DLL module
  1306. DWORD fdwReason, // reason for calling function
  1307. LPVOID lpReserved ) // reserved
  1308. {
  1309. VlState * state ;
  1310. VlThreadState * threadState ;
  1311. switch (fdwReason) {
  1312. case DLL_PROCESS_ATTACH:
  1313. /* Initialize once for each new process */
  1314. vl_constructor () ;
  1315. break ;
  1316. case DLL_THREAD_ATTACH:
  1317. /* Do thread-specific initialization */
  1318. break ;
  1319. case DLL_THREAD_DETACH:
  1320. /* Do thread-specific cleanup */
  1321. #if ! defined(VL_DISABLE_THREADS) && defined(VL_THREADS_WIN)
  1322. state = vl_get_state() ;
  1323. threadState = (VlThreadState*) TlsGetValue(state->tlsIndex) ;
  1324. if (threadState) {
  1325. vl_thread_specific_state_delete (threadState) ;
  1326. }
  1327. #endif
  1328. break;
  1329. case DLL_PROCESS_DETACH:
  1330. /* Perform any necessary cleanup */
  1331. vl_destructor () ;
  1332. break;
  1333. }
  1334. return TRUE ; /* Successful DLL_PROCESS_ATTACH */
  1335. }
  1336. #endif /* VL_OS_WIN */
  1337. /* ---------------------------------------------------------------- */
  1338. /* Library constructor and destructor */
  1339. /* ---------------------------------------------------------------- */
  1340. /** @internal @brief Initialize VLFeat state */
  1341. static void
  1342. vl_constructor (void)
  1343. {
  1344. VlState * state ;
  1345. #if defined(DEBUG)
  1346. printf("VLFeat DEBUG: constructor begins.\n") ;
  1347. #endif
  1348. state = vl_get_state() ;
  1349. #if ! defined(VL_DISABLE_THREADS)
  1350. #if defined(DEBUG)
  1351. printf("VLFeat DEBUG: constructing thread specific state.\n") ;
  1352. #endif
  1353. #if defined(VL_THREADS_POSIX)
  1354. {
  1355. typedef void (*destructorType)(void * );
  1356. pthread_key_create (&state->threadKey,
  1357. (destructorType)
  1358. vl_thread_specific_state_delete) ;
  1359. pthread_mutex_init (&state->mutex, NULL) ;
  1360. pthread_cond_init (&state->mutexCondition, NULL) ;
  1361. }
  1362. #elif defined(VL_THREADS_WIN)
  1363. InitializeCriticalSection (&state->mutex) ;
  1364. state->tlsIndex = TlsAlloc () ;
  1365. #endif
  1366. #else
  1367. /* threading support disabled */
  1368. #if defined(DEBUG)
  1369. printf("VLFeat DEBUG: constructing the generic thread state instance (threading support disabled).\n") ;
  1370. #endif
  1371. vl_get_state()->threadState = vl_thread_specific_state_new() ;
  1372. #endif
  1373. state->malloc_func = malloc ;
  1374. state->realloc_func = realloc ;
  1375. state->calloc_func = calloc ;
  1376. state->free_func = free ;
  1377. state->printf_func = printf ;
  1378. /* on x86 platforms read the CPUID register */
  1379. #if defined(VL_ARCH_IX86) || defined(VL_ARCH_X64) || defined(VL_ARCH_IA64)
  1380. _vl_x86cpu_info_init (&state->cpuInfo) ;
  1381. #endif
  1382. /* get the number of CPUs */
  1383. #if defined(VL_OS_WIN)
  1384. {
  1385. SYSTEM_INFO info;
  1386. GetSystemInfo (&info) ;
  1387. state->numCPUs = info.dwNumberOfProcessors ;
  1388. }
  1389. #elif defined(VL_OS_MACOSX) || defined(VL_OS_LINUX)
  1390. state->numCPUs = sysconf(_SC_NPROCESSORS_ONLN) ;
  1391. #else
  1392. state->numCPUs = 1 ;
  1393. #endif
  1394. state->simdEnabled = VL_TRUE ;
  1395. /* get the number of (OpenMP) threads used by the library */
  1396. #if defined(_OPENMP)
  1397. state->numThreads = omp_get_max_threads() ;
  1398. #else
  1399. state->numThreads = 1 ;
  1400. #endif
  1401. #if defined(DEBUG)
  1402. printf("VLFeat DEBUG: constructor ends.\n") ;
  1403. #endif
  1404. }
  1405. /** @internal @brief Destruct VLFeat */
  1406. static void
  1407. vl_destructor ()
  1408. {
  1409. VlState * state ;
  1410. #if defined(DEBUG)
  1411. printf("VLFeat DEBUG: destructor begins.\n") ;
  1412. #endif
  1413. state = vl_get_state() ;
  1414. #if ! defined(VL_DISABLE_THREADS)
  1415. #if defined(DEBUG)
  1416. printf("VLFeat DEBUG: destroying a thread specific state instance.\n") ;
  1417. #endif
  1418. #if defined(VL_THREADS_POSIX)
  1419. {
  1420. /* Delete the thread state of this thread as the
  1421. destructor is not called by pthread_key_delete or after
  1422. the key is deleted. When the library
  1423. is unloaded, this thread should also be the last one
  1424. using the library, so this is fine.
  1425. */
  1426. VlThreadState * threadState = (VlThreadState*) pthread_getspecific(state->threadKey) ;
  1427. if (threadState) {
  1428. vl_thread_specific_state_delete (threadState) ;
  1429. pthread_setspecific(state->threadKey, NULL) ;
  1430. }
  1431. }
  1432. pthread_cond_destroy (&state->mutexCondition) ;
  1433. pthread_mutex_destroy (&state->mutex) ;
  1434. pthread_key_delete (state->threadKey) ;
  1435. #elif defined(VL_THREADS_WIN)
  1436. {
  1437. /* Delete the thread state of this thread as the
  1438. destructor is not called by pthread_key_delete or after
  1439. the key is deleted. When the library
  1440. is unloaded, this thread should also be the last one
  1441. using the library, so this is fine.
  1442. */
  1443. VlThreadState * threadState =(VlThreadState*)TlsGetValue(state->tlsIndex) ;
  1444. if (threadState) {
  1445. vl_thread_specific_state_delete (threadState) ;
  1446. TlsSetValue(state->tlsIndex, NULL) ;
  1447. }
  1448. }
  1449. TlsFree (state->tlsIndex) ;
  1450. DeleteCriticalSection (&state->mutex) ;
  1451. #endif
  1452. #else
  1453. #if defined(DEBUG)
  1454. printf("VLFeat DEBUG: destroying the generic thread state instance (threading support disabled).\n") ;
  1455. #endif
  1456. vl_thread_specific_state_delete(vl_get_state()->threadState) ;
  1457. #endif
  1458. #if defined(DEBUG)
  1459. printf("VLFeat DEBUG: destructor ends.\n") ;
  1460. #endif
  1461. }